Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c321ec2213 | ||
|
|
1439a5ef19 | ||
|
|
9f3a1bf96d | ||
|
|
def5deb113 |
@@ -13,7 +13,6 @@
|
||||
|
||||
# Development files
|
||||
/TESTING.md
|
||||
/Makefile
|
||||
/requirements-dev.txt
|
||||
/.coveragerc
|
||||
/.flake8
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# Tailwind standalone CLI (downloaded by `make css-setup`)
|
||||
tailwindcss
|
||||
|
||||
# AI tooling / local config
|
||||
.claude/
|
||||
.playwright-mcp/
|
||||
|
||||
@@ -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
@@ -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**
|
||||
|
||||
|
||||
@@ -214,18 +214,21 @@ Set `PROMPT_MANAGER_DATA_DIR` to an absolute folder to keep the library somewher
|
||||
- **Older images:** a one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
|
||||
- **Going back isn't supported.** Workflows are now stored once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
|
||||
|
||||
## The old pages 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.
|
||||
The dashboard, tags page, gallery and metadata viewer have been removed. Everything they did is in the workspace, and their URLs and bookmarks still work: 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 it, the address follows the tags you set in **Filters**, and you can bookmark or write such a link 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
|
||||
|
||||
|
||||
+153
-118
@@ -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
|
||||
@@ -1619,8 +1634,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 +2878,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 +3262,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 +3386,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 +3590,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 +3862,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 +3886,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 +4013,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.
|
||||
@@ -5615,8 +5625,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 +5635,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 +5660,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 +5760,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 +5771,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 +5796,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 +5839,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 +5865,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 +6022,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 +7675,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 +7804,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 +7813,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+26
-8
@@ -274,6 +274,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,
|
||||
@@ -621,17 +632,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 ───────────────────────────────────────
|
||||
|
||||
|
||||
+6
-2
@@ -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):
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -466,6 +466,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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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');
|
||||
}
|
||||
});
|
||||
@@ -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]);
|
||||
}
|
||||
});
|
||||
@@ -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. */
|
||||
|
||||
@@ -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 · /);
|
||||
|
||||
@@ -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('');
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
|
||||
Vendored
+16
@@ -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
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 993 B |
@@ -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');
|
||||
});
|
||||
}
|
||||
@@ -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">`), "<a href="x">");
|
||||
});
|
||||
|
||||
test("the browser ViewRouter global resolves the tags deep link", () => {
|
||||
const window = loadInFakeBrowser("view-router.js");
|
||||
assert.equal(window.ViewRouter.resolveView("#/tags/a"), "tags");
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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',
|
||||
]);
|
||||
});
|
||||
@@ -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, []);
|
||||
});
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
@@ -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(`&<>"'`), "&<>"'");
|
||||
});
|
||||
|
||||
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, `" onmouseover="alert(1)`);
|
||||
assert.equal(`<a data-tag="${escaped}">`, `<a data-tag="" onmouseover="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, `' onclick='alert(1)`);
|
||||
});
|
||||
|
||||
test("a script tag is neutralised in text context", () => {
|
||||
assert.equal(escapeHtml("<script>x</script>"), "<script>x</script>");
|
||||
});
|
||||
|
||||
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;");
|
||||
});
|
||||
|
||||
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>" }), "<b>");
|
||||
});
|
||||
|
||||
test("escapeAttr is the same function as escapeHtml", () => {
|
||||
assert.equal(escapeAttr, escapeHtml);
|
||||
assert.equal(escapeAttr(`a"b`), "a"b");
|
||||
});
|
||||
@@ -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(""><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 | <b>");
|
||||
});
|
||||
|
||||
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("</pre><script>"), 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 "a": 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.");
|
||||
});
|
||||
@@ -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"));
|
||||
|
||||
@@ -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']]);
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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));
|
||||
}
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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)));
|
||||
});
|
||||
@@ -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});
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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
@@ -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",
|
||||
):
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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"])
|
||||
@@ -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)">'
|
||||
|
||||
+46
-1
@@ -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."""
|
||||
|
||||
|
||||
@@ -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]}',
|
||||
|
||||
@@ -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"
|
||||
@@ -1140,6 +1141,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
|
||||
|
||||
@@ -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
|
||||
@@ -88,16 +87,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,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.
|
||||
|
||||
+3
-3
@@ -16,7 +16,7 @@ test('browser coverage maps nested JS/MJS and excludes unrelated and traversal p
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const urls = [
|
||||
'/prompt_manager/js/gallery.js',
|
||||
'/prompt_manager/js/api-client.js',
|
||||
'/prompt_manager/js/shared/controls/button.mjs?v=1',
|
||||
'/prompt_manager/js/shared/panel.js',
|
||||
'/scripts/app.js', '/prompt_manager/js/../private.js',
|
||||
@@ -25,7 +25,7 @@ test('browser coverage maps nested JS/MJS and excludes unrelated and traversal p
|
||||
await saveCoverage({ coverage: { stopJSCoverage: async () => urls.map(url => ({ url: `http://127.0.0.1:8765${url}`, functions: [] })) } }, 'chromium');
|
||||
const report = JSON.parse(readFileSync(join(directory, readdirSync(directory)[0]), 'utf8'));
|
||||
const root = fileURLToPath(new URL('../../web/js/', import.meta.url));
|
||||
assert.deepEqual(report.result.map(entry => fileURLToPath(entry.url)), [join(root, 'gallery.js'), join(root, 'shared/controls/button.mjs'), join(root, 'shared/panel.js')]);
|
||||
assert.deepEqual(report.result.map(entry => fileURLToPath(entry.url)), [join(root, 'api-client.js'), join(root, 'shared/controls/button.mjs'), join(root, 'shared/panel.js')]);
|
||||
});
|
||||
|
||||
// #432: every raw file repeated each script's full source (about 84% of its bytes) and the coverage merge ran out of
|
||||
@@ -40,7 +40,7 @@ test('browser coverage writes no script source, only what c8 maps', async t => {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const functions = [{ functionName: 'f', isBlockCoverage: true, ranges: [{ startOffset: 0, endOffset: 9, count: 1 }] }];
|
||||
await saveCoverage({ coverage: { stopJSCoverage: async () => [{ url: 'http://127.0.0.1:8765/prompt_manager/js/gallery.js',
|
||||
await saveCoverage({ coverage: { stopJSCoverage: async () => [{ url: 'http://127.0.0.1:8765/prompt_manager/js/api-client.js',
|
||||
scriptId: '7', source: 'x'.repeat(100_000), functions }] } }, 'chromium');
|
||||
const report = JSON.parse(readFileSync(join(directory, readdirSync(directory)[0]), 'utf8'));
|
||||
assert.equal(report.result.length, 1);
|
||||
|
||||
+11
-106
@@ -1,11 +1,11 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { COLUMNS, CONTROL_EXEMPTIONS, PAGES, REMOVAL_COLUMNS, STATUSES, declaredTitles, duplicateRemovals, idUses, methodUses,
|
||||
parseControl, parseCoverageTable, parseRemovalTable, readCoverageTable, readPage, readRemovalTable, removalProblems,
|
||||
import { COLUMNS, CONTROL_EXEMPTIONS, STATUSES, declaredTitles, parseControl, parseCoverageTable, readCoverageTable,
|
||||
rowProblems } from '../../tools/vendor/legacy-coverage.mjs';
|
||||
|
||||
// TESTING.md "Legacy System capability coverage" (#249 System S12, #329): every legacy System capability names an
|
||||
// owner, a known status, a well-formed native control and a test its file really declares.
|
||||
// TESTING.md "Legacy System capability coverage" (#249 System S12, #329): every System capability the old pages had
|
||||
// names an owner, a known status, a well-formed native control and a test its file really declares. The old pages are
|
||||
// gone (#668), so nothing is "kept in legacy" any more.
|
||||
|
||||
const ROW = Object.freeze({ Capability: 'Clear/truncate logs', 'Legacy anchor': '`admin.html:915`', Owner: 'S12 Logs',
|
||||
Status: 'covered', 'Native control': '`diagnostics` · button · "Clear all logs…"', Test: 'clears the logs (clear.spec.mjs)' });
|
||||
@@ -19,7 +19,10 @@ test('every coverage row has an owner, a known status and a declared test', () =
|
||||
assert.ok(row.Owner.trim());
|
||||
assert.ok(STATUSES.includes(row.Status));
|
||||
}
|
||||
assert.ok(rows.some(row => row.Status === 'kept in legacy') && rows.some(row => row.Status === 'approved removal'));
|
||||
assert.deepEqual(STATUSES, ['covered', 'approved removal']);
|
||||
assert.ok(rows.some(row => row.Status === 'approved removal'));
|
||||
// #668: the old pages are gone, so a row can no longer point at them.
|
||||
assert.ok(rowProblems({ ...rows[0], Status: 'kept in legacy' }).includes('unknown status "kept in legacy"'));
|
||||
// A broken row fails: an empty owner, an unknown status, a test its file does not declare.
|
||||
const [first] = rows;
|
||||
assert.deepEqual(rowProblems({ ...first, Owner: '' }), ['no owner']);
|
||||
@@ -79,8 +82,8 @@ test('a malformed native control cell fails', () => {
|
||||
assert.match(rowProblems({ ...ROW, 'Native control': cell }, declaring("test('clears the logs', () => {});")).join(), message);
|
||||
}
|
||||
// Only a covered row names a control.
|
||||
assert.deepEqual(rowProblems({ ...ROW, Status: 'kept in legacy' }, declaring("test('clears the logs', () => {});")),
|
||||
['a kept in legacy row names a native control']);
|
||||
assert.deepEqual(rowProblems({ ...ROW, Status: 'approved removal' }, declaring("test('clears the logs', () => {});")),
|
||||
['only a covered row names a native control, and this row is approved removal']);
|
||||
// The table itself must keep its six columns.
|
||||
assert.throws(() => parseCoverageTable(`### Legacy System capability coverage\n\n| Capability | Owner |\n| --- | --- |\n`), /columns/);
|
||||
assert.deepEqual(COLUMNS, ['Capability', 'Legacy anchor', 'Owner', 'Status', 'Native control', 'Test']);
|
||||
@@ -101,9 +104,7 @@ test('a skipped test does not prove a capability', () => {
|
||||
test('a covered row names its native control unless it is exempt', () => {
|
||||
const source = declaring("test('clears the logs', () => {});");
|
||||
assert.deepEqual(rowProblems({ ...ROW, 'Native control': '—' }, source), ['a covered row names no native control']);
|
||||
for (const status of ['kept in legacy', 'approved removal']) {
|
||||
assert.deepEqual(rowProblems({ ...ROW, Status: status, 'Native control': '—' }, source), [], status);
|
||||
}
|
||||
assert.deepEqual(rowProblems({ ...ROW, Status: 'approved removal', 'Native control': '—' }, source), []);
|
||||
const [exempt] = Object.keys(CONTROL_EXEMPTIONS);
|
||||
assert.deepEqual(rowProblems({ ...ROW, Capability: exempt, 'Native control': '—' }, source), []);
|
||||
// Every exemption has a reason and names a covered row of the table that has no control.
|
||||
@@ -115,99 +116,3 @@ test('a covered row names its native control unless it is exempt', () => {
|
||||
assert.deepEqual([row.Status, row['Native control']], ['covered', '—']);
|
||||
}
|
||||
});
|
||||
|
||||
// TESTING.md "Legacy System UI removed by S13" (#330): a legacy element is removed only when its capability is
|
||||
// `covered`, the removal copies that row's native test, and the element is really gone from its page.
|
||||
const COVERAGE_HEADER = '| Capability | Legacy anchor | Owner | Status | Native control | Test |\n| --- | --- | --- | --- | --- | --- |';
|
||||
const REMOVAL_HEADER = '| Capability | Page | Removed ids | Removed methods | Native test |\n| --- | --- | --- | --- | --- |';
|
||||
const FIXTURE_COVERAGE = parseCoverageTable(['### Legacy System capability coverage', '', COVERAGE_HEADER,
|
||||
'| View logs | `admin.html:1` | S12 Logs | covered | `diagnostics` · combobox · "Level" | level filter works (logs.spec.mjs) |',
|
||||
'| Infinite scrolling default | `admin.html:2` | Legacy prompt list | kept in legacy | — | scrolls (list-state.test.js) |',
|
||||
''].join('\n'));
|
||||
const removalRow = cells => parseRemovalTable(['### Legacy System UI removed by S13', '', REMOVAL_HEADER, `| ${cells} |`, '']
|
||||
.join('\n'))[0];
|
||||
const EMPTY_PAGE = () => ({ html: '<button id="kept">Kept</button>', script: 'class Admin {\n kept() {}\n}\n' });
|
||||
|
||||
test('every removed legacy element cites a covered capability and its native test', () => {
|
||||
const coverage = readCoverageTable();
|
||||
const rows = readRemovalTable();
|
||||
for (const row of rows) {
|
||||
const cited = coverage.find(item => item.Capability === row.Capability);
|
||||
assert.ok(cited, `TESTING.md:${row.line} cites "${row.Capability}"`);
|
||||
assert.equal(cited.Status, 'covered', `TESTING.md:${row.line} ${row.Capability}`);
|
||||
assert.equal(row['Native test'], cited.Test, `TESTING.md:${row.line} ${row.Capability}`);
|
||||
assert.ok(Object.keys(PAGES).includes(row.Page), `TESTING.md:${row.line} page ${row.Page}`);
|
||||
}
|
||||
assert.deepEqual(duplicateRemovals(rows), []);
|
||||
assert.deepEqual(REMOVAL_COLUMNS, ['Capability', 'Page', 'Removed ids', 'Removed methods', 'Native test']);
|
||||
});
|
||||
|
||||
test('a removed id or method is gone from its page', () => {
|
||||
const coverage = readCoverageTable();
|
||||
for (const row of readRemovalTable()) {
|
||||
assert.deepEqual(removalProblems(row, coverage, page => readPage(page)), [], `TESTING.md:${row.line} ${row.Capability}`);
|
||||
}
|
||||
// Each way a page can still hold an id or a method is found; a call through another object, or a longer name, is not
|
||||
// a definition.
|
||||
const page = {
|
||||
html: '<div id="logsModal"></div><button onclick="window.admin.closeLogs()">x</button>',
|
||||
script: [
|
||||
"document.getElementById('logLevel').value;",
|
||||
"this.showModal('diagnosticsModal');",
|
||||
'<span data-id="logsContainer"></span>',
|
||||
'document.querySelector("#logLimit option");',
|
||||
"const backdrops = ['settingsModal', 'duplicatesModal'];",
|
||||
'class Admin {',
|
||||
' async refreshLogs(level) {',
|
||||
' }',
|
||||
'} displayLogs(logs) {',
|
||||
' }',
|
||||
'this.loadLogStats();',
|
||||
'// downloadLogs() {',
|
||||
'other.formatBytesLater(1);',
|
||||
].join('\n'),
|
||||
};
|
||||
assert.deepEqual(idUses('logsModal', page), ['id="logsModal" in the markup']);
|
||||
assert.deepEqual(idUses('logLevel', page), ["getElementById('logLevel')"]);
|
||||
assert.deepEqual(idUses('logLimit', page), ["querySelector('#logLimit')"]);
|
||||
assert.deepEqual(idUses('duplicatesModal', page), ["'duplicatesModal' in a modal list"]);
|
||||
assert.deepEqual(idUses('logLevelX', page), []);
|
||||
assert.deepEqual(idUses('diagnosticsModal', page), ["a …Modal('diagnosticsModal') call"]);
|
||||
assert.deepEqual(idUses('logsContainer', page), []);
|
||||
assert.deepEqual(methodUses('closeLogs', page), ['.closeLogs( called in the markup']);
|
||||
assert.deepEqual(methodUses('refreshLogs', page), ['refreshLogs() defined']);
|
||||
assert.deepEqual(methodUses('displayLogs', page), ['displayLogs() defined']);
|
||||
assert.deepEqual(methodUses('loadLogStats', page), ['.loadLogStats( called']);
|
||||
assert.deepEqual(methodUses('downloadLogs', page), []);
|
||||
assert.deepEqual(methodUses('formatBytes', page), []);
|
||||
// One id or method is listed on one row per page.
|
||||
const twice = [removalRow('View logs | admin | `#logsModal` | — | level filter works (logs.spec.mjs)'),
|
||||
{ ...removalRow('View logs | admin | `#logsModal` | — | level filter works (logs.spec.mjs)'), line: 9 }];
|
||||
assert.match(duplicateRemovals(twice).join(), /admin #logsModal is listed on rows/);
|
||||
assert.deepEqual(removalProblems(removalRow('View logs | admin | `logsModal`, `#ok` | `close` | level filter works (logs.spec.mjs)'),
|
||||
FIXTURE_COVERAGE, EMPTY_PAGE), ['malformed entry "logsModal"', 'malformed entry "close"']);
|
||||
});
|
||||
|
||||
test('a removal citing a kept-in-legacy capability fails', () => {
|
||||
const row = removalRow('Infinite scrolling default | admin | `#infiniteScrollDefault` | — | scrolls (list-state.test.js)');
|
||||
assert.deepEqual(removalProblems(row, FIXTURE_COVERAGE, EMPTY_PAGE), ['cites a kept in legacy capability']);
|
||||
const unknown = removalRow('Something else | admin | — | — | scrolls (list-state.test.js)');
|
||||
assert.deepEqual(removalProblems(unknown, FIXTURE_COVERAGE, EMPTY_PAGE), ['cites no single coverage row "Something else"']);
|
||||
});
|
||||
|
||||
test('a removal whose native test differs fails', () => {
|
||||
const row = removalRow('View logs | admin | `#logsModal` | `showLogsModal()` | another title (logs.spec.mjs)');
|
||||
assert.deepEqual(removalProblems(row, FIXTURE_COVERAGE, EMPTY_PAGE),
|
||||
['its native test differs from the coverage row\'s "level filter works (logs.spec.mjs)"']);
|
||||
assert.deepEqual(removalProblems({ ...row, 'Native test': 'level filter works (logs.spec.mjs)' }, FIXTURE_COVERAGE, EMPTY_PAGE), []);
|
||||
});
|
||||
|
||||
test('a removed id still on its page fails', () => {
|
||||
const row = removalRow('View logs | admin | `#logsModal` | `showLogsModal()` | level filter works (logs.spec.mjs)');
|
||||
const page = () => ({ html: '<div id="logsModal" class="hidden"></div>', script: 'class Admin {\n showLogsModal() {\n }\n}\n' });
|
||||
assert.deepEqual(removalProblems(row, FIXTURE_COVERAGE, page), [
|
||||
'#logsModal is still on the admin page: id="logsModal" in the markup',
|
||||
'showLogsModal() is still on the admin page: showLogsModal() defined',
|
||||
]);
|
||||
assert.deepEqual(removalProblems({ ...row, Page: 'metadata' }, FIXTURE_COVERAGE, page), ['unknown page "metadata"']);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Write tests/fixtures/media/comfyui_avif.avif with ComfyUI's own AVIF writer.
|
||||
|
||||
Run from a ComfyUI checkout with ComfyUI's Python (torch, and PyAV built with
|
||||
SVT-AV1), because the fixture must be what ``SaveImageAdvanced`` writes, not
|
||||
an AVIF some other encoder made:
|
||||
|
||||
cd /path/to/ComfyUI
|
||||
python custom_nodes/ComfyUI-PromptManager/tools/make_avif_fixture.py
|
||||
|
||||
``comfy_extras.nodes_images._save_avif`` encodes the pixels through PyAV and
|
||||
then ``inject_avif_metadata`` writes the same EXIF item ComfyUI writes:
|
||||
``prompt:{json}`` at tag 0x0110, then ``workflow:{json}`` and every other key
|
||||
from 0x010F down. ``utils/exif_text`` reads those tags back (#652).
|
||||
|
||||
The image is a 96x96 sRGB gradient at CRF 18: small enough to keep in the
|
||||
repository and large enough that the EXIF item dominates the file.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Importing comfy_extras requires ComfyUI's own root on sys.path; the script
|
||||
# is run from that root (see the docstring).
|
||||
sys.path.insert(0, os.getcwd())
|
||||
|
||||
import torch # noqa: E402
|
||||
|
||||
from comfy_extras.nodes_images import _save_avif # noqa: E402
|
||||
|
||||
# A PromptManager run: the positive prompt is the node's own text (the shape
|
||||
# tests/test_image_linking.py's graph uses), so both the scan and the monitor
|
||||
# link the image to that stored prompt instead of calling it a foreign output.
|
||||
PROMPT = {
|
||||
"1": {
|
||||
"class_type": "PromptManager",
|
||||
"inputs": {"text": "a small avif fixture"},
|
||||
},
|
||||
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": "bad"}},
|
||||
"3": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {"positive": ["1", 0], "negative": ["2", 0]},
|
||||
},
|
||||
}
|
||||
WORKFLOW = {
|
||||
"nodes": [
|
||||
{"id": 1, "type": "PromptManager", "inputs": {"text": "a small avif fixture"}},
|
||||
{"id": 2, "type": "CLIPTextEncode", "inputs": {"text": "bad"}},
|
||||
{"id": 3, "type": "KSampler", "inputs": {}},
|
||||
],
|
||||
"links": [
|
||||
[1, 0, 3, 0, "CONDITIONING"],
|
||||
[2, 0, 3, 1, "CONDITIONING"],
|
||||
],
|
||||
}
|
||||
OUTPUT = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"tests",
|
||||
"fixtures",
|
||||
"media",
|
||||
"comfyui_avif.avif",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
os.makedirs(os.path.dirname(OUTPUT), exist_ok=True)
|
||||
# (frames, height, width, channels), floats in 0..1 as ComfyUI's IMAGE is.
|
||||
ramp = torch.linspace(0.0, 1.0, 96).view(1, 1, 96, 1).expand(1, 96, 96, 3)
|
||||
_save_avif(
|
||||
ramp.contiguous(),
|
||||
OUTPUT,
|
||||
"8-bit YUV420",
|
||||
"sRGB",
|
||||
18,
|
||||
metadata={"prompt": PROMPT, "workflow": WORKFLOW},
|
||||
)
|
||||
print(f"{OUTPUT}: {os.path.getsize(OUTPUT)} bytes")
|
||||
print(json.dumps({"prompt_keys": list(PROMPT), "workflow_keys": list(WORKFLOW)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Vendored
+6
-4
@@ -2,7 +2,8 @@
|
||||
|
||||
ComfyUI serves the committed files in `web/lib/viewerjs/`. Node and npm are only
|
||||
needed by maintainers and CI. Keep upstream files pristine; application behavior
|
||||
belongs in `web/js/`, and theme overrides belong in `comfyui-theme.css`.
|
||||
belongs in `web/js/`, and theme overrides belong in the workspace's own stylesheet
|
||||
(`web/js/workspace/workspace.css`).
|
||||
|
||||
## Install and verify
|
||||
|
||||
@@ -18,9 +19,10 @@ npm run --prefix tools/vendor test:browser
|
||||
```
|
||||
|
||||
On Linux, use `playwright install --with-deps chromium` when browser system
|
||||
libraries are missing. The browser tests use synthetic images and mock the
|
||||
ComfyUI API boundary; they run production viewer methods and the committed
|
||||
Viewer.js JS/CSS, without a running ComfyUI instance.
|
||||
libraries are missing. The browser tests are a smoke of the committed Viewer.js
|
||||
JS/CSS on a synthetic page, without a running ComfyUI instance: open at an image,
|
||||
move on, close, destroy, and a touch swipe. The workspace's own viewer is proven
|
||||
by the real-page workflows.
|
||||
|
||||
`check` is read-only and fails if any JS, CSS, license, or provenance file differs
|
||||
from the installed package. The manifest, lockfile, installed package, and asset
|
||||
|
||||
+2
-74
@@ -1,10 +1,4 @@
|
||||
{
|
||||
"admin.js": {
|
||||
"lines": 47,
|
||||
"branches": 64,
|
||||
"functions": 50,
|
||||
"statements": 47
|
||||
},
|
||||
"api-client.js": {
|
||||
"lines": 98,
|
||||
"branches": 96,
|
||||
@@ -29,12 +23,6 @@
|
||||
"functions": 98,
|
||||
"statements": 97
|
||||
},
|
||||
"data-actions.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"focused-node.js": {
|
||||
"lines": 97,
|
||||
"branches": 87,
|
||||
@@ -47,30 +35,12 @@
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"gallery.js": {
|
||||
"lines": 54,
|
||||
"branches": 72,
|
||||
"functions": 58,
|
||||
"statements": 54
|
||||
},
|
||||
"html-escape.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"image-helpers.js": {
|
||||
"legacy-links.js": {
|
||||
"lines": 96,
|
||||
"branches": 92,
|
||||
"branches": 88,
|
||||
"functions": 98,
|
||||
"statements": 96
|
||||
},
|
||||
"list-state.js": {
|
||||
"lines": 98,
|
||||
"branches": 92,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"metadata-autocomplete.js": {
|
||||
"lines": 98,
|
||||
"branches": 83,
|
||||
@@ -101,12 +71,6 @@
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"prompt-list-sort.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"workspace-entry.js": {
|
||||
"lines": 80,
|
||||
"branches": 80,
|
||||
@@ -119,12 +83,6 @@
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"scan-progress.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"shared/toolkit/core.js": {
|
||||
"lines": 98,
|
||||
"branches": 96,
|
||||
@@ -143,42 +101,12 @@
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"sse-stream.js": {
|
||||
"lines": 98,
|
||||
"branches": 92,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"tag-autocomplete.js": {
|
||||
"lines": 98,
|
||||
"branches": 94,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"tags-page.js": {
|
||||
"lines": 57,
|
||||
"branches": 48,
|
||||
"functions": 56,
|
||||
"statements": 57
|
||||
},
|
||||
"text-links.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"theme-bridge.js": {
|
||||
"lines": 90,
|
||||
"branches": 53,
|
||||
"functions": 98,
|
||||
"statements": 90
|
||||
},
|
||||
"view-router.js": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
},
|
||||
"workspace/activity-job-view.mjs": {
|
||||
"lines": 97,
|
||||
"branches": 87,
|
||||
|
||||
Vendored
+12
-142
@@ -1,7 +1,9 @@
|
||||
// The legacy System capability coverage table (TESTING.md "Legacy System capability coverage", #249 System S12 #329):
|
||||
// every capability of the legacy admin and gallery pages names its owner, a status, the native control that replaces it
|
||||
// every capability the old admin and gallery pages had names its owner, a status, the native control that replaces it
|
||||
// and a declared test. tests/vendor/legacy-coverage.test.mjs checks each row against the test files; the browser spec
|
||||
// `every covered legacy System capability has its native control` finds each covered row's control on its System page.
|
||||
// The old pages are gone (#668): a capability is `covered` or an `approved removal`, and the Legacy anchor cells are
|
||||
// history (they name lines of 3.7.2).
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -9,7 +11,7 @@ import { fileURLToPath } from 'node:url';
|
||||
export const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
export const HEADING = '### Legacy System capability coverage';
|
||||
export const COLUMNS = Object.freeze(['Capability', 'Legacy anchor', 'Owner', 'Status', 'Native control', 'Test']);
|
||||
export const STATUSES = Object.freeze(['covered', 'kept in legacy', 'approved removal']);
|
||||
export const STATUSES = Object.freeze(['covered', 'approved removal']);
|
||||
export const SECTIONS = Object.freeze(['overview', 'appearance', 'sources', 'integrations', 'tagging', 'maintenance', 'backups',
|
||||
'diagnostics']);
|
||||
export const ROLES = Object.freeze(['button', 'combobox', 'switch', 'slider', 'spinbutton', 'textbox', 'group', 'status', 'term']);
|
||||
@@ -42,30 +44,25 @@ function cells(line) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The rows, keyed by `columns`, of the first Markdown table under `heading` (`label` names it in errors). */
|
||||
function parseTable(markdown, heading, columns, label) {
|
||||
/** The table's rows as objects keyed by COLUMNS, from the section that starts at HEADING. */
|
||||
export function parseCoverageTable(markdown) {
|
||||
const lines = markdown.split('\n');
|
||||
const start = lines.findIndex(line => line.trim() === heading);
|
||||
if (start === -1) throw new Error(`TESTING.md has no "${heading}" section`);
|
||||
const start = lines.findIndex(line => line.trim() === HEADING);
|
||||
if (start === -1) throw new Error(`TESTING.md has no "${HEADING}" section`);
|
||||
const header = lines.findIndex((line, index) => index > start && line.trim().startsWith('|'));
|
||||
if (header === -1 || lines.slice(start + 1, header).some(line => /^#{1,3} /.test(line))) {
|
||||
throw new Error(`The ${label} section has no table`);
|
||||
throw new Error('The coverage section has no table');
|
||||
}
|
||||
const found = cells(lines[header]);
|
||||
if (found.join('|') !== columns.join('|')) throw new Error(`The ${label} table's columns are ${found.join(', ')}`);
|
||||
if (found.join('|') !== COLUMNS.join('|')) throw new Error(`The coverage table's columns are ${found.join(', ')}`);
|
||||
const rows = [];
|
||||
for (let index = header + 2; index < lines.length && lines[index].trim().startsWith('|'); index += 1) {
|
||||
const values = cells(lines[index]);
|
||||
rows.push({ line: index + 1, ...Object.fromEntries(columns.map((column, at) => [column, values[at] ?? ''])) });
|
||||
rows.push({ line: index + 1, ...Object.fromEntries(COLUMNS.map((column, at) => [column, values[at] ?? ''])) });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** The table's rows as objects keyed by COLUMNS, from the section that starts at HEADING. */
|
||||
export function parseCoverageTable(markdown) {
|
||||
return parseTable(markdown, HEADING, COLUMNS, 'coverage');
|
||||
}
|
||||
|
||||
/**
|
||||
* A Native control cell: `` `<section>` · <role> · "<name>" ``, optionally ` · in "<row title>"` when the name is shared
|
||||
* by several rows of the section → {section, role, name, row}; `—` → null; else it throws.
|
||||
@@ -193,7 +190,7 @@ export function rowProblems(row, { root = ROOT, locate = file => testFile(file,
|
||||
} catch (error) {
|
||||
problems.push(error.message);
|
||||
}
|
||||
if (control && row.Status !== 'covered') problems.push(`a ${row.Status} row names a native control`);
|
||||
if (control && row.Status !== 'covered') problems.push(`only a covered row names a native control, and this row is ${row.Status}`);
|
||||
if (row.Status === 'covered' && row['Native control'] === NONE && !Object.hasOwn(CONTROL_EXEMPTIONS, row.Capability)) {
|
||||
problems.push('a covered row names no native control');
|
||||
}
|
||||
@@ -218,130 +215,3 @@ export function rowProblems(row, { root = ROOT, locate = file => testFile(file,
|
||||
export function readCoverageTable(root = ROOT) {
|
||||
return parseCoverageTable(readFileSync(join(root, 'TESTING.md'), 'utf8'));
|
||||
}
|
||||
|
||||
// ── Legacy System UI removed by S13 (#330) ──────────────────────────────────────────────────────────────────────────
|
||||
// TESTING.md "Legacy System UI removed by S13": one row per covered capability whose legacy UI S13 removed, with the
|
||||
// element ids and methods that went. A row must cite a `covered` coverage row and copy its Test cell, and none of its
|
||||
// ids or methods may still be on its page.
|
||||
export const REMOVAL_HEADING = '### Legacy System UI removed by S13';
|
||||
export const REMOVAL_COLUMNS = Object.freeze(['Capability', 'Page', 'Removed ids', 'Removed methods', 'Native test']);
|
||||
/** Each legacy page's markup and script. */
|
||||
export const PAGES = Object.freeze({
|
||||
admin: Object.freeze({ html: 'web/admin.html', script: 'web/js/admin.js' }),
|
||||
gallery: Object.freeze({ html: 'web/gallery.html', script: 'web/js/gallery.js' }),
|
||||
});
|
||||
|
||||
/** The removal table's rows, from the section that starts at REMOVAL_HEADING. */
|
||||
export function parseRemovalTable(markdown) {
|
||||
return parseTable(markdown, REMOVAL_HEADING, REMOVAL_COLUMNS, 'removal');
|
||||
}
|
||||
|
||||
/** The removal table read from TESTING.md. */
|
||||
export function readRemovalTable(root = ROOT) {
|
||||
return parseRemovalTable(readFileSync(join(root, 'TESTING.md'), 'utf8'));
|
||||
}
|
||||
|
||||
/** A Removed ids or Removed methods cell → its entries without backticks (`—` → none). */
|
||||
export function listCell(cell) {
|
||||
if (cell.trim() === NONE) return [];
|
||||
return cell.split(',').map(entry => entry.trim().replace(/^`|`$/g, '')).filter(Boolean);
|
||||
}
|
||||
|
||||
/** The removed ids of a row (without `#`) and its malformed entries. */
|
||||
function removedIds(row) {
|
||||
const entries = listCell(row['Removed ids']);
|
||||
return { ids: entries.filter(entry => /^#[\w-]+$/.test(entry)).map(entry => entry.slice(1)),
|
||||
bad: entries.filter(entry => !/^#[\w-]+$/.test(entry)) };
|
||||
}
|
||||
|
||||
/** The removed methods of a row (without `()`) and its malformed entries. */
|
||||
function removedMethods(row) {
|
||||
const entries = listCell(row['Removed methods']);
|
||||
return { names: entries.filter(entry => /^[A-Za-z_$][\w$]*\(\)$/.test(entry)).map(entry => entry.slice(0, -2)),
|
||||
bad: entries.filter(entry => !/^[A-Za-z_$][\w$]*\(\)$/.test(entry)) };
|
||||
}
|
||||
|
||||
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
/**
|
||||
* Where `id` is still on a page: `id="<id>"` in its markup or script; in its script a lookup, a `…Modal("<id>")` call
|
||||
* (`showModal`, `hideModal`) or a modal-list entry.
|
||||
*/
|
||||
export function idUses(id, { html, script }) {
|
||||
const name = escapeRegExp(id);
|
||||
const code = stripJsComments(script);
|
||||
const uses = [];
|
||||
// `id=`, not `data-id=`: the attribute starts after a space or a tag's `<name`.
|
||||
const attribute = new RegExp(`(?:^|\\s)id=["']${name}["']`, 'm');
|
||||
if (attribute.test(html)) uses.push(`id="${id}" in the markup`);
|
||||
if (attribute.test(code)) uses.push(`id="${id}" in the script`);
|
||||
if (new RegExp(`getElementById\\(\\s*["'\`]${name}["'\`]\\s*\\)`).test(code)) uses.push(`getElementById('${id}')`);
|
||||
if (new RegExp(`querySelector(?:All)?\\(\\s*["'\`]#${name}\\b`).test(code)) uses.push(`querySelector('#${id}')`);
|
||||
if (new RegExp(`\\w*Modal\\(\\s*["'\`]${name}["'\`]`).test(code)) uses.push(`a …Modal('${id}') call`);
|
||||
// A string list of modal ids (the gallery's backdrop list): the entry next to another `…Modal` entry.
|
||||
for (const list of code.matchAll(/\[[^\[\]]*\]/g)) {
|
||||
const entry = new RegExp(`["']${name}["']`);
|
||||
if (entry.test(list[0]) && /["'][\w-]*Modal["']/.test(list[0].replace(entry, ''))) {
|
||||
uses.push(`'${id}' in a modal list`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return uses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where method `name` is still on a page: a definition in its script, or a `.<name>(` call (`this.`, `window.admin.`)
|
||||
* in its script or markup.
|
||||
*/
|
||||
export function methodUses(name, { html, script }) {
|
||||
const method = escapeRegExp(name);
|
||||
const code = stripJsComments(script);
|
||||
const uses = [];
|
||||
if (new RegExp(`(?:^|[\\s;}])(?:async\\s+)?${method}\\s*\\([^)]*\\)\\s*\\{`, 'm').test(code)) uses.push(`${name}() defined`);
|
||||
if (new RegExp(`\\.${method}\\s*\\(`).test(code)) uses.push(`.${name}( called`);
|
||||
if (new RegExp(`\\.${method}\\s*\\(`).test(html)) uses.push(`.${name}( called in the markup`);
|
||||
return uses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every problem of one removal row (empty: sound). `coverage` is the coverage table's rows; `readPage(page)` returns
|
||||
* that page's `{html, script}`.
|
||||
*/
|
||||
export function removalProblems(row, coverage, readPage) {
|
||||
const problems = [];
|
||||
const cited = coverage.filter(item => item.Capability === row.Capability);
|
||||
if (cited.length !== 1) problems.push(`cites no single coverage row "${row.Capability}"`);
|
||||
else if (cited[0].Status !== 'covered') problems.push(`cites a ${cited[0].Status} capability`);
|
||||
else if (cited[0].Test !== row['Native test']) problems.push(`its native test differs from the coverage row's "${cited[0].Test}"`);
|
||||
if (!Object.hasOwn(PAGES, row.Page)) {
|
||||
problems.push(`unknown page "${row.Page}"`);
|
||||
return problems;
|
||||
}
|
||||
const { ids, bad: badIds } = removedIds(row);
|
||||
const { names, bad: badNames } = removedMethods(row);
|
||||
for (const entry of [...badIds, ...badNames]) problems.push(`malformed entry "${entry}"`);
|
||||
const page = readPage(row.Page);
|
||||
for (const id of ids) for (const use of idUses(id, page)) problems.push(`#${id} is still on the ${row.Page} page: ${use}`);
|
||||
for (const name of names) for (const use of methodUses(name, page)) problems.push(`${name}() is still on the ${row.Page} page: ${use}`);
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Ids and methods listed on more than one row of the same page. */
|
||||
export function duplicateRemovals(rows) {
|
||||
const seen = new Map();
|
||||
const duplicates = [];
|
||||
for (const row of rows) {
|
||||
for (const entry of [...listCell(row['Removed ids']), ...listCell(row['Removed methods'])]) {
|
||||
const key = `${row.Page} ${entry}`;
|
||||
if (seen.has(key)) duplicates.push(`${key} is listed on rows ${seen.get(key)} and ${row.line}`);
|
||||
else seen.set(key, row.line);
|
||||
}
|
||||
}
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
/** A page's markup and script from the repository. */
|
||||
export function readPage(page, root = ROOT) {
|
||||
const files = PAGES[page];
|
||||
return { html: readFileSync(join(root, files.html), 'utf8'), script: readFileSync(join(root, files.script), 'utf8') };
|
||||
}
|
||||
|
||||
Vendored
+37
-242
@@ -1,270 +1,65 @@
|
||||
// The vendored Viewer.js build on a synthetic page, without ComfyUI or Python: the browser check the Viewer.js update
|
||||
// workflow runs before it opens its pull request. The workspace's own viewer (web/js/workspace/media-viewer.mjs) is
|
||||
// proven against the real server by tests/browser/workspace-viewer-*.spec.mjs and the Images and history specs. The
|
||||
// old pages' viewer tests went with those pages (#668).
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { repositoryRoot as root } from '../vendor-viewerjs.mjs';
|
||||
|
||||
const source = file => readFileSync(join(root, file), 'utf8');
|
||||
const IMAGE = '<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="teal"/></svg>';
|
||||
const PAGE = '<head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><ul id="images">'
|
||||
+ [0, 1, 2].map(index => `<li><img src="http://viewer.test/original/${index}.svg" alt="Image ${index}" width="100" height="100"></li>`).join('')
|
||||
+ '</ul></body>';
|
||||
|
||||
async function waitForImage(page, index) {
|
||||
await expect.poll(() => page.evaluate(() => window.gallery.viewer?.viewed)).toBe(true);
|
||||
await expect.poll(() => page.evaluate(() => window.gallery.lastMetadata)).toContain(`/original/${index}.svg`);
|
||||
}
|
||||
|
||||
async function loadGallery(page) {
|
||||
await page.addScriptTag({ content: source('web/js/gallery.js') + '\nwindow.TestGallery = GalleryManager;' });
|
||||
await page.evaluate(() => {
|
||||
const manager = window.gallery = Object.create(TestGallery.prototype);
|
||||
Object.assign(manager, {
|
||||
viewer: null, viewMode: 'grid',
|
||||
images: Array.from({ length: 2000 }, (_, i) => ({ filename: `${i}.svg`,
|
||||
url: `http://viewer.test/original/${i}.svg`, thumbnail_url: `http://viewer.test/thumb/${i}.svg`,
|
||||
relative_path: `${i}.svg`, size: 100, modified_time: 1 })),
|
||||
getSettings: () => ({ showImageInfo: true }),
|
||||
loadImageMetadata(url, content) { this.lastMetadata = url; content.textContent = url; },
|
||||
});
|
||||
manager.renderGallery();
|
||||
});
|
||||
}
|
||||
/** The index Viewer.js reports once it has shown an image. */
|
||||
const viewedIndex = page => page.evaluate(() => window.viewed.at(-1));
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
page.viewerErrors = [];
|
||||
page.on('pageerror', error => page.viewerErrors.push(error.message));
|
||||
await page.route('http://viewer.test/**', route => route.request().resourceType() === 'document'
|
||||
? route.fulfill({ contentType: 'text/html', body: '<head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><button id="outside">Outside</button><div id="galleryGrid"></div><div id="galleryList"></div><div id="loadingState"></div><div id="errorState"></div><div id="galleryContent"></div><div id="galleryEmpty"></div><h1 id="galleryTitle"></h1></body>' })
|
||||
: route.fulfill({ contentType: 'image/svg+xml', body: '<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="teal"/></svg>' }));
|
||||
? route.fulfill({ contentType: 'text/html', body: PAGE })
|
||||
: route.fulfill({ contentType: 'image/svg+xml', body: IMAGE }));
|
||||
await page.goto('http://viewer.test/');
|
||||
await page.addStyleTag({ path: join(root, 'web/lib/tailwind/comfyui-theme.css') });
|
||||
await page.addStyleTag({ path: join(root, 'web/lib/tailwind/styles.css') });
|
||||
await page.addStyleTag({ path: join(root, 'web/lib/viewerjs/viewer.min.css') });
|
||||
await page.addStyleTag({ content: '.hidden{display:none} #galleryGrid{display:grid;grid-template-columns:repeat(8,1fr)} #galleryGrid img{width:100px;height:100px}' });
|
||||
for (const file of ['web/lib/viewerjs/viewer.min.js', 'web/js/html-escape.js', 'web/js/image-helpers.js', 'web/js/api-client.js']) {
|
||||
await page.addScriptTag({ path: join(root, file) });
|
||||
}
|
||||
await page.addScriptTag({ path: join(root, 'web/lib/viewerjs/viewer.min.js') });
|
||||
await page.evaluate(() => {
|
||||
window.viewed = [];
|
||||
const list = document.getElementById('images');
|
||||
list.addEventListener('viewed', event => window.viewed.push(event.detail.index));
|
||||
list.addEventListener('hidden', () => { window.hidden = true; });
|
||||
window.viewer = new window.Viewer(list, { transition: false });
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
expect(page.viewerErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test('gallery retains cards and navigates across bounded windows with correct metadata', async ({ page }) => {
|
||||
await loadGallery(page);
|
||||
await page.locator('[data-image-index="1500"]').click();
|
||||
await waitForImage(page, 1500);
|
||||
expect(await page.evaluate(() => gallery.viewer.length)).toBeLessThanOrEqual(100);
|
||||
expect(await page.evaluate(() => {
|
||||
const first = document.querySelector('.image-item');
|
||||
gallery.images.push({ ...gallery.images[0], filename: 'appended.svg' });
|
||||
gallery.renderGallery({ from: 2000 });
|
||||
return first === document.querySelector('.image-item');
|
||||
})).toBe(true);
|
||||
await page.evaluate(() => gallery.viewer.view(99));
|
||||
await waitForImage(page, 1549);
|
||||
test('the vendored Viewer.js opens at the clicked image, moves on with the keyboard and leaves nothing behind', async ({ page }) => {
|
||||
await page.locator('#images img').nth(1).click();
|
||||
await expect.poll(() => viewedIndex(page)).toBe(1);
|
||||
await expect(page.locator('.viewer-container')).toHaveClass(/viewer-in/);
|
||||
await expect(page.locator('.viewer-canvas img')).toHaveAttribute('src', 'http://viewer.test/original/1.svg');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await waitForImage(page, 1550);
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await waitForImage(page, 1549);
|
||||
await expect.poll(() => viewedIndex(page)).toBe(2);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect.poll(() => page.evaluate(() => gallery.viewer.isShown)).toBe(false);
|
||||
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
|
||||
await page.locator('#outside').focus();
|
||||
await expect(page.locator('#outside')).toBeFocused();
|
||||
});
|
||||
|
||||
test('gallery slideshow advances without preloading the collection and cleans up on close', async ({ page }) => {
|
||||
await loadGallery(page);
|
||||
await page.evaluate(() => gallery.openViewer(1500));
|
||||
await waitForImage(page, 1500);
|
||||
await page.clock.install();
|
||||
await page.locator('[data-viewer-action="play"]').click();
|
||||
expect(await page.evaluate(() => gallery.slideshowPlaying)).toBe(true);
|
||||
await expect(page.locator('.viewer-player img')).toHaveCount(0);
|
||||
await page.clock.fastForward(5000);
|
||||
await waitForImage(page, 1501);
|
||||
await page.locator('[data-viewer-action="play"]').click();
|
||||
expect(await page.evaluate(() => gallery.slideshowPlaying)).toBe(false);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect.poll(() => page.evaluate(() => gallery.viewer.isShown)).toBe(false);
|
||||
await page.evaluate(() => gallery.destroyViewer());
|
||||
await expect.poll(() => page.evaluate(() => window.hidden)).toBe(true);
|
||||
await page.evaluate(() => window.viewer.destroy());
|
||||
await expect(page.locator('.viewer-container')).toHaveCount(0);
|
||||
await expect(page.locator('body')).not.toHaveClass(/viewer-open/);
|
||||
});
|
||||
|
||||
test('admin gallery and filmstrip use the real viewer events and destroy temporary containers', async ({ page }) => {
|
||||
// Exercise the production class without starting the ComfyUI dashboard bootstrap.
|
||||
const adminSource = source('web/js/admin.js');
|
||||
await page.addScriptTag({ content: adminSource.slice(0, adminSource.indexOf(' function startAdmin()')) + '\nwindow.TestAdmin = PromptAdmin;' });
|
||||
await page.evaluate(async () => {
|
||||
const admin = window.admin = Object.create(TestAdmin.prototype);
|
||||
const images = Array.from({ length: 3 }, (_, i) => ({ filename: `${i}.svg`, url: `http://viewer.test/original/${i}.svg`, size: 100, created_at: 1 }));
|
||||
Object.assign(admin, {
|
||||
prompts: [{ id: 1, text: 'test' }],
|
||||
getImageUrl: image => image.url,
|
||||
loadFilmStripImages: async () => images,
|
||||
addMetadataSidebar() {},
|
||||
loadMetadataForImage(image) { this.lastMetadata = image.src; },
|
||||
});
|
||||
await admin.openFilmStripViewer(1, 1);
|
||||
});
|
||||
await expect.poll(() => page.evaluate(() => admin.lastMetadata)).toContain('/1.svg');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect.poll(() => page.evaluate(() => admin.lastMetadata)).toContain('/2.svg');
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#filmStripViewerContainer')).toHaveCount(0);
|
||||
await expect(page.locator('.viewer-container')).toHaveCount(0);
|
||||
await page.evaluate(() => admin.renderGallery([{ filename: 'a.svg', url: 'http://viewer.test/original/0.svg', size: 100, created_at: 1 }], 1));
|
||||
await expect.poll(() => page.evaluate(() => Boolean(admin.galleryViewer))).toBe(true);
|
||||
await page.evaluate(() => admin.galleryViewer.show());
|
||||
await expect.poll(() => page.evaluate(() => admin.galleryViewer.viewed)).toBe(true);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect.poll(() => page.evaluate(() => admin.galleryViewer.isShown)).toBe(false);
|
||||
await page.evaluate(() => admin.galleryViewer.destroy());
|
||||
});
|
||||
|
||||
test('tag viewer opens at the selected image and cleans up on Escape', async ({ page }) => {
|
||||
await page.addScriptTag({ path: join(root, 'web/js/tags-page.js') });
|
||||
await page.evaluate(async () => {
|
||||
const tags = Object.create(TagsPageManager.prototype);
|
||||
tags.admin = { getImageUrl: image => image.url };
|
||||
await tags.openImageViewer({ images: [0, 1, 2].map(i => ({ filename: `${i}.svg`, url: `http://viewer.test/original/${i}.svg` })), image_count: 3 }, 1);
|
||||
});
|
||||
await expect(page.locator('.viewer-canvas img')).toHaveAttribute('src', /\/1.svg$/);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect(page.locator('.viewer-canvas img')).toHaveAttribute('src', /\/2.svg$/);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('.viewer-container')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('touch swipes navigate the gallery and restore short drags', async ({ page, isMobile }) => {
|
||||
test('a touch swipe moves the vendored Viewer.js to the next image', async ({ page, isMobile }) => {
|
||||
test.skip(!isMobile, 'Touch interaction project');
|
||||
await loadGallery(page);
|
||||
await page.evaluate(() => gallery.openViewer(1500));
|
||||
await waitForImage(page, 1500);
|
||||
await page.locator('.metadata-collapse-btn').click();
|
||||
await expect(page.locator('.metadata-sidebar')).toHaveClass(/collapsed/);
|
||||
await page.evaluate(() => window.viewer.view(0));
|
||||
await expect.poll(() => viewedIndex(page)).toBe(0);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
const width = await page.evaluate(() => gallery.viewer.viewerData.width);
|
||||
const swipe = async distance => {
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: width * 0.9, y: 220 }] });
|
||||
for (let step = 1; step <= 8; step++) {
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: width * 0.9 - distance * step / 8, y: 220 }] });
|
||||
}
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
|
||||
};
|
||||
await swipe(width * 0.8);
|
||||
await waitForImage(page, 1501);
|
||||
const initialX = await page.evaluate(() => gallery.viewer.imageData.x);
|
||||
await swipe(width * 0.1);
|
||||
await waitForImage(page, 1501);
|
||||
await expect.poll(() => page.evaluate(() => gallery.viewer.imageData.x)).toBe(initialX);
|
||||
});
|
||||
|
||||
test('touch pinch zoom and rotation remain usable', async ({ page, isMobile }) => {
|
||||
test.skip(!isMobile, 'Touch interaction project');
|
||||
await loadGallery(page);
|
||||
await page.evaluate(() => gallery.openViewer(1500));
|
||||
await waitForImage(page, 1500);
|
||||
await page.locator('.metadata-collapse-btn').click();
|
||||
await expect(page.locator('.metadata-sidebar')).toHaveClass(/collapsed/);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
const points = (radius, angle = 0) => [-1, 1].map((sign, id) => ({
|
||||
id, x: 400 + sign * radius * Math.cos(angle), y: 220 + sign * radius * Math.sin(angle),
|
||||
}));
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: points(30) });
|
||||
for (let step = 1; step <= 6; step++) {
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: points(30 + step * 8) });
|
||||
const { width, height } = page.viewportSize();
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: width * 0.9, y: height / 2 }] });
|
||||
for (let step = 1; step <= 8; step += 1) {
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: width * 0.9 - width * 0.8 * step / 8, y: height / 2 }] });
|
||||
}
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
|
||||
await expect.poll(() => page.evaluate(() => gallery.viewer.imageData.ratio > 1.2)).toBe(true);
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: points(70) });
|
||||
for (let step = 1; step <= 8; step++) {
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: points(70, Math.PI / 2 * step / 8) });
|
||||
}
|
||||
await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
|
||||
await expect.poll(() => page.evaluate(() => Math.abs(gallery.viewer.imageData.rotate))).toBe(90);
|
||||
});
|
||||
|
||||
test('metadata follows the selected image when responses finish out of order', async ({ page }) => {
|
||||
await loadGallery(page);
|
||||
await page.evaluate(() => {
|
||||
delete gallery.loadImageMetadata;
|
||||
window.metadataRequests = new Map();
|
||||
gallery.extractImageMetadata = url => new Promise(resolve => metadataRequests.set(url, resolve));
|
||||
gallery.openViewer(0);
|
||||
});
|
||||
await expect.poll(() => page.evaluate(() => metadataRequests.has('http://viewer.test/original/0.svg'))).toBe(true);
|
||||
await page.evaluate(() => gallery.viewer.next());
|
||||
await expect.poll(() => page.evaluate(() => metadataRequests.has('http://viewer.test/original/1.svg'))).toBe(true);
|
||||
await page.evaluate(() => metadataRequests.get('http://viewer.test/original/1.svg')({ positivePrompt: 'Selected prompt' }));
|
||||
await expect(page.locator('#metadata-content')).toContainText('Selected prompt');
|
||||
await page.evaluate(() => metadataRequests.get('http://viewer.test/original/0.svg')({ positivePrompt: 'Stale prompt' }));
|
||||
await expect(page.locator('#metadata-content')).toContainText('Selected prompt');
|
||||
await expect(page.locator('#metadata-content')).not.toContainText('Stale prompt');
|
||||
expect(await page.evaluate(() => gallery.currentMetadata.positivePrompt)).toBe('Selected prompt');
|
||||
await page.evaluate(() => gallery.viewer.next());
|
||||
await expect.poll(() => page.evaluate(() => metadataRequests.has('http://viewer.test/original/2.svg'))).toBe(true);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
|
||||
await page.evaluate(() => metadataRequests.get('http://viewer.test/original/2.svg')({ positivePrompt: 'Closed prompt' }));
|
||||
expect(await page.evaluate(() => gallery.currentMetadata)).toBeNull();
|
||||
});
|
||||
|
||||
for (const mode of ['gallery', 'filmstrip']) {
|
||||
test(`admin ${mode} metadata ignores stale responses and clears copy state on close`, async ({ page }) => {
|
||||
const urlFor = index => mode === 'gallery' ? `http://viewer.test/prompt_manager/images/${index}/file` : `http://viewer.test/original/${index}.svg`;
|
||||
const adminSource = source('web/js/admin.js');
|
||||
await page.addScriptTag({ content: adminSource.slice(0, adminSource.indexOf(' function startAdmin()')) + '\nwindow.TestAdmin = PromptAdmin;' });
|
||||
await page.evaluate(async mode => {
|
||||
const admin = window.admin = Object.create(TestAdmin.prototype);
|
||||
const images = Array.from({ length: 3 }, (_, i) => ({ id: i, filename: `${i}.svg`, url: `http://viewer.test/original/${i}.svg`, size: 100, created_at: 1 }));
|
||||
window.pendingMetadata = new Map();
|
||||
Object.assign(admin, { prompts: [{ id: 1, text: 'test' }],
|
||||
getImageUrl: image => image.url, loadFilmStripImages: async () => images,
|
||||
extractImageMetadata: url => new Promise(resolve => pendingMetadata.set(url, resolve)),
|
||||
});
|
||||
if (mode === 'gallery') {
|
||||
admin.renderGallery(images, 1);
|
||||
} else {
|
||||
await admin.openFilmStripViewer(1, 0);
|
||||
}
|
||||
}, mode);
|
||||
if (mode === 'gallery') {
|
||||
await expect.poll(() => page.evaluate(() => Boolean(admin.galleryViewer))).toBe(true);
|
||||
await page.evaluate(() => admin.galleryViewer.show());
|
||||
}
|
||||
await expect.poll(() => page.evaluate(url => pendingMetadata.has(url), urlFor(0))).toBe(true);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect.poll(() => page.evaluate(url => pendingMetadata.has(url), urlFor(1))).toBe(true);
|
||||
await page.evaluate(url => pendingMetadata.get(url)({ positivePrompt: 'Selected prompt', negativePrompt: '', imagePath: '1.svg' }), urlFor(1));
|
||||
await expect(page.locator('#metadata-content')).toContainText('Selected prompt');
|
||||
await page.evaluate(url => pendingMetadata.get(url)({ positivePrompt: 'Stale prompt', negativePrompt: '', imagePath: '0.svg' }), urlFor(0));
|
||||
await expect(page.locator('#metadata-content')).not.toContainText('Stale prompt');
|
||||
expect(await page.evaluate(() => admin.currentMetadata.imagePath)).toBe('1.svg');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect.poll(() => page.evaluate(url => pendingMetadata.has(url), urlFor(2))).toBe(true);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
|
||||
await page.evaluate(url => pendingMetadata.get(url)({ positivePrompt: 'Closed prompt', negativePrompt: '', imagePath: '2.svg' }), urlFor(2));
|
||||
expect(await page.evaluate(() => admin.currentMetadata)).toBeNull();
|
||||
});
|
||||
}
|
||||
|
||||
test('Tags selection stays current during a delayed prompt response', async ({ page }) => {
|
||||
await page.addScriptTag({ path: join(root, 'web/js/tags-page.js') });
|
||||
await page.evaluate(() => {
|
||||
const grid = document.createElement('div'); grid.id = 'tagPromptsGrid'; document.body.append(grid);
|
||||
const manager = window.tagsManager = Object.create(TagsPageManager.prototype);
|
||||
window.pendingTagPrompts = [];
|
||||
Object.assign(manager, { selectedTags: ['cats'], filterMode: 'and', promptLimit: 20, prompts: [],
|
||||
fetchJson: url => new Promise(resolve => pendingTagPrompts.push({ url, resolve })),
|
||||
renderTagPrompts() { grid.textContent = this.prompts.map(prompt => prompt.text).join(','); },
|
||||
updatePromptCountBadge() {}, updateLoadMoreButton() {}, refreshPromptObserver() {},
|
||||
});
|
||||
manager.loadTagPrompts();
|
||||
manager.selectedTags = ['dogs'];
|
||||
manager.loadTagPrompts();
|
||||
});
|
||||
expect(await page.evaluate(() => pendingTagPrompts.length)).toBe(2);
|
||||
await page.evaluate(() => pendingTagPrompts[1].resolve({ success: true, prompts: [{ text: 'dog prompt' }], pagination: { total: 1, has_more: false } }));
|
||||
await expect(page.locator('#tagPromptsGrid')).toHaveText('dog prompt');
|
||||
await page.evaluate(() => pendingTagPrompts[0].resolve({ success: true, prompts: [{ text: 'cat prompt' }], pagination: { total: 1, has_more: false } }));
|
||||
await expect(page.locator('#tagPromptsGrid')).toHaveText('dog prompt');
|
||||
await expect.poll(() => viewedIndex(page)).toBe(1);
|
||||
});
|
||||
|
||||
@@ -298,7 +298,7 @@ class GalleryDiagnostics:
|
||||
self.logger.info(f" [DIR] {source}: {abs_path}")
|
||||
try:
|
||||
image_files = []
|
||||
for ext in [".png", ".jpg", ".jpeg", ".webp"]:
|
||||
for ext in [".png", ".jpg", ".jpeg", ".webp", ".avif"]:
|
||||
image_files.extend(
|
||||
found
|
||||
for found in Path(abs_path).rglob(f"*{ext}")
|
||||
|
||||
+13
-2
@@ -51,6 +51,7 @@ from .foreign_runs import (
|
||||
)
|
||||
from .hashing import generate_prompt_hash
|
||||
from .media_folders import in_skipped_folder, split_relative
|
||||
from .media_formats import collectable
|
||||
from .metadata_extractor import ComfyUIMetadataExtractor
|
||||
from .parallel import note_refusal, refused_at_shutdown
|
||||
from .logging_config import get_logger
|
||||
@@ -233,7 +234,14 @@ class ImageGenerationHandler(FileSystemEventHandler):
|
||||
self.supported_extensions = tuple(GalleryConfig.SUPPORTED_EXTENSIONS)
|
||||
except Exception:
|
||||
self.processing_delay = 2.0
|
||||
self.supported_extensions = (".png", ".jpg", ".jpeg", ".webp", ".gif")
|
||||
self.supported_extensions = (
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".webp",
|
||||
".gif",
|
||||
".avif", # #652: skipped in is_image_file when Pillow cannot read it
|
||||
)
|
||||
|
||||
# Settle check: the file size must be unchanged across two reads
|
||||
self.settle_interval = SETTLE_INTERVAL_SECONDS
|
||||
@@ -532,7 +540,10 @@ class ImageGenerationHandler(FileSystemEventHandler):
|
||||
# folder holds thrown-away files (#501): neither is a new output.
|
||||
if in_skipped_folder(self._folders_below_root(filepath)):
|
||||
return False
|
||||
return filepath.lower().endswith(self.supported_extensions)
|
||||
if not filepath.lower().endswith(self.supported_extensions):
|
||||
return False
|
||||
# #652: an AVIF output is watched only where Pillow can read it.
|
||||
return collectable(os.path.splitext(filepath)[1])
|
||||
|
||||
def _folders_below_root(self, filepath: str) -> list:
|
||||
"""The folder names of *filepath* below the longest watched root.
|
||||
|
||||
@@ -33,8 +33,10 @@ from typing import Callable
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
from .media_formats import collectable
|
||||
from .video_metadata import VIDEO_EXTENSIONS, is_video_path
|
||||
except ImportError: # imported with the repo root on sys.path
|
||||
from utils.media_formats import collectable
|
||||
from utils.video_metadata import VIDEO_EXTENSIONS, is_video_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -64,7 +66,7 @@ DIMENSION_REASON = (
|
||||
# restated here so utilities never import the aiohttp API package; a test pins
|
||||
# the two sets equal.
|
||||
_STILL_EXTENSIONS = frozenset(
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif"}
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif", ".avif"}
|
||||
)
|
||||
CAPTURE_EXTENSIONS = _STILL_EXTENSIONS | frozenset(VIDEO_EXTENSIONS)
|
||||
|
||||
@@ -675,7 +677,8 @@ def _relative_parts(relative) -> tuple[list[str], str]:
|
||||
if part in ("", ".", "..") or ":" in part:
|
||||
raise CaptureDenied("Invalid file path")
|
||||
extension = os.path.splitext(parts[-1])[1].lower()
|
||||
if extension not in CAPTURE_EXTENSIONS:
|
||||
# #652: an AVIF the listing would not collect is not capturable either.
|
||||
if extension not in CAPTURE_EXTENSIONS or not collectable(extension):
|
||||
raise CaptureDenied("Unsupported media type")
|
||||
return parts, extension
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Which still-image formats this install can collect (#652).
|
||||
|
||||
PNG, JPEG, WebP, GIF, BMP and TIFF are read by every Pillow PromptManager
|
||||
supports. AVIF is not: Pillow's floor here is >= 10.1.0 (ComfyUI's), and
|
||||
Pillow opens AVIF only from 11.0, and only when it was built with an AVIF
|
||||
decoder. A file-type list that names ``.avif`` unconditionally would hand the
|
||||
scan and the monitor files this install cannot open, so the lists name it (a
|
||||
served or deletable file is a file, whatever this Pillow reads) and the
|
||||
collection points ask :func:`collectable` before a file enters the library.
|
||||
|
||||
The scan (``py.api.admin``), the monitor (``utils.image_monitor``), the
|
||||
gallery walk (``py.api.images``), auto-tagging's listing
|
||||
(``py.api.autotag_routes``) and the capture store
|
||||
(``utils.media_capture``) skip AVIF quietly when the answer is no, so a
|
||||
Pillow without AVIF behaves exactly as it did before #652.
|
||||
"""
|
||||
|
||||
AVIF_EXTENSION = ".avif"
|
||||
|
||||
|
||||
def avif_supported() -> bool:
|
||||
"""Whether this Pillow can decode AVIF (``PIL.features.check("avif")``).
|
||||
|
||||
Pillow answers False on every version before 11.0 and on a build without
|
||||
an AVIF decoder, so it is the one answer the collection points need.
|
||||
"""
|
||||
try:
|
||||
from PIL import features
|
||||
except ImportError: # a partial install: no still image is read anyway
|
||||
return False
|
||||
try:
|
||||
return bool(features.check("avif"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def collectable(extension: str) -> bool:
|
||||
"""Whether a still image with *extension* may enter the library.
|
||||
|
||||
Every extension is collectable except ``.avif``, which needs
|
||||
:func:`avif_supported`. The extension is compared case-insensitively.
|
||||
"""
|
||||
return str(extension).lower() != AVIF_EXTENSION or avif_supported()
|
||||
@@ -91,8 +91,8 @@ class ComfyUIMetadataExtractor:
|
||||
metadata["file_info"] = self.get_file_info(image_path, image)
|
||||
|
||||
# ComfyUI writes PNG text chunks, read without decoding the
|
||||
# pixels (#523). WebP (and AVIF, once collected: #652) carry
|
||||
# the same records as EXIF text, so those images link too.
|
||||
# pixels (#523). WebP and AVIF (#652) carry the same records
|
||||
# as EXIF text, so those images link too.
|
||||
text = png_text(image) or exif_text(image)
|
||||
if text:
|
||||
# Look for ComfyUI workflow data
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Prompt Manager · Opening the workspace</title>
|
||||
<style>
|
||||
body { margin: 0; padding: 24px; font: 14px/1.5 system-ui, sans-serif; background: #1b1b1f; color: #eee; }
|
||||
a { color: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- #668 (D207): the old dashboard and Tags page moved to the workspace. The link stays visible, so a browser
|
||||
without scripts, or one where the script below fails, still has the way on. -->
|
||||
<p>This page moved to the workspace. <a href="workspace#/library">Open the Prompt library</a></p>
|
||||
<script src="js/legacy-links.js"></script>
|
||||
<script>
|
||||
// The server never sees the hash, so an old tag bookmark (admin#/tags/a,b?mode=or) is mapped here.
|
||||
// Replace, so Back does not return here and bounce.
|
||||
(function () {
|
||||
var target = "workspace#/library";
|
||||
try { target = window.LegacyLinks.adminTarget(window.location.hash); } catch (error) { /* the Library */ }
|
||||
window.location.replace(target);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-1000
File diff suppressed because it is too large
Load Diff
@@ -1,627 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<title>PromptManager - Gallery</title>
|
||||
<script src="js/theme-bridge.js"></script>
|
||||
<script src="js/html-escape.js"></script>
|
||||
<script src="js/image-helpers.js"></script>
|
||||
<script src="js/gallery-settings.js"></script>
|
||||
<script src="js/api-client.js"></script>
|
||||
<script src="js/png-metadata.js"></script>
|
||||
<script src="js/list-state.js"></script>
|
||||
<script src="js/sse-stream.js"></script>
|
||||
<script src="js/data-actions.js"></script>
|
||||
<link rel="stylesheet" href="lib/tailwind/comfyui-theme.css">
|
||||
<link rel="stylesheet" href="lib/tailwind/styles.css">
|
||||
<link rel="stylesheet" href="lib/viewerjs/viewer.min.css">
|
||||
<script src="lib/viewerjs/viewer.min.js"></script>
|
||||
<style>
|
||||
/* Column count from Display Settings. An id selector inside the desktop
|
||||
media query outranks the Tailwind breakpoint classes on #galleryGrid. */
|
||||
@media (min-width: 1280px) {
|
||||
#galleryGrid.gallery-columns-custom {
|
||||
grid-template-columns: var(--gallery-columns, repeat(8, minmax(0, 1fr)));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-pm-primary text-pm min-h-screen">
|
||||
<div id="legacy-removal-notice" role="note" class="bg-pm-surface border-b border-pm px-4 py-2 text-pm" style="font-size: 13px;">This page will be removed in a future release. Its features are moving to the new workspace. <a href="workspace#/images" style="text-decoration: underline;">Open the workspace</a></div>
|
||||
<div class="min-h-screen flex flex-col">
|
||||
<!-- Header -->
|
||||
<header class="bg-pm-surface border-b border-pm px-4 py-2">
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<div class="flex items-center justify-between">
|
||||
<h1 class="text-sm font-semibold text-pm">PromptManager Gallery</h1>
|
||||
<div class="hidden sm:flex items-center gap-2">
|
||||
<div class="w-2 h-2 bg-pm-success rounded-full animate-pulse"></div>
|
||||
<span class="text-pm-success text-xs font-medium">Online</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Controls -->
|
||||
<div class="bg-pm-surface border-b border-pm-subtle px-4 py-2">
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<label class="text-xs text-pm-secondary">Show:</label>
|
||||
<select id="limitSelector" class="px-2 py-1 bg-pm-input border border-pm rounded-pm-sm text-pm text-xs">
|
||||
<option value="50">50</option>
|
||||
<option value="100" selected>100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
</select>
|
||||
<span class="text-xs text-pm-secondary">images</span>
|
||||
<span class="text-pm-secondary mx-1">|</span>
|
||||
<label class="text-xs text-pm-secondary">Size:</label>
|
||||
<button id="thumbSmBtn" class="px-2 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs rounded-pm-sm transition-colors" title="Small thumbnails">S</button>
|
||||
<button id="thumbMdBtn" class="px-2 py-1 bg-pm-accent text-pm-accent-fg text-xs rounded-pm-sm transition-colors" title="Medium thumbnails">M</button>
|
||||
<button id="thumbLgBtn" class="px-2 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs rounded-pm-sm transition-colors" title="Large thumbnails">L</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button id="refreshBtn"
|
||||
class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Refresh
|
||||
</button>
|
||||
<button id="gridViewBtn"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Grid View
|
||||
</button>
|
||||
<button id="listViewBtn"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
List View
|
||||
</button>
|
||||
<a id="settingsBtn" href="workspace#/system/appearance" target="_blank" rel="noopener"
|
||||
title="Opens System › Appearance in a new tab"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Settings
|
||||
</a>
|
||||
<button id="pageOptionsBtn" type="button"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Page options
|
||||
</button>
|
||||
<button id="autoTagBtn"
|
||||
class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Auto Tag
|
||||
</button>
|
||||
<button id="addPromptBtn"
|
||||
class="px-3 py-1 bg-pm-success hover:bg-pm-success text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Add Prompt
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stats Bar -->
|
||||
<div class="bg-pm-surface px-4 py-2 border-b border-pm-subtle">
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="text-pm-secondary">
|
||||
Showing <span id="showingStart">0</span> to <span id="showingEnd">0</span> of <span id="totalImages">0</span> images
|
||||
</span>
|
||||
<span class="text-pm-secondary" id="loadingStatus">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Gallery Content -->
|
||||
<div class="flex-1 overflow-hidden">
|
||||
<div class="max-w-full mx-auto p-3 flex gap-0" style="height: calc(100vh - 140px);">
|
||||
<!-- Folder Tree Panel — sticky, scrolls independently -->
|
||||
<div id="folderTreePanel" class="hidden flex-shrink-0 bg-pm-surface border border-pm rounded-pm-sm overflow-y-auto" style="width: 240px; min-width: 160px;">
|
||||
<div class="px-3 py-2 border-b border-pm-subtle flex items-center justify-between sticky top-0 bg-pm-surface z-10">
|
||||
<span class="text-sm font-semibold text-pm">Folders</span>
|
||||
<button id="clearFolderFilterBtn" class="text-sm text-pm-secondary hover:text-pm transition-colors" title="Clear filter">×</button>
|
||||
</div>
|
||||
<div id="folderTree" class="py-1 text-sm">
|
||||
<!-- Tree nodes inserted by JS -->
|
||||
</div>
|
||||
</div>
|
||||
<!-- Resize Handle -->
|
||||
<div id="folderResizeHandle" class="hidden w-1 cursor-col-resize bg-transparent hover:bg-pm-accent/30 flex-shrink-0"></div>
|
||||
|
||||
<!-- Main Gallery Area — scrolls independently -->
|
||||
<div id="galleryScroll" class="flex-1 min-w-0 overflow-y-auto pl-3">
|
||||
<!-- Loading State -->
|
||||
<div id="loadingState" class="flex items-center justify-center py-12">
|
||||
<div class="text-center">
|
||||
<div class="w-8 h-8 border-4 border-pm-accent-tint border-t-pm-accent rounded-full animate-spin mx-auto mb-3"></div>
|
||||
<p class="text-pm-secondary text-xs">Loading gallery...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error State -->
|
||||
<div id="errorState" class="hidden flex items-center justify-center py-12">
|
||||
<div class="text-center">
|
||||
<h3 class="text-sm font-semibold text-pm-error mb-2">Error Loading Gallery</h3>
|
||||
<p class="text-pm-secondary text-xs mb-3" id="errorMessage">Something went wrong while loading the images.</p>
|
||||
<button id="retryBtn" class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Gallery Grid -->
|
||||
<div id="galleryGrid" class="hidden grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8 gap-2">
|
||||
<!-- Images will be inserted here -->
|
||||
</div>
|
||||
|
||||
<!-- Gallery List -->
|
||||
<div id="galleryList" class="hidden space-y-2">
|
||||
<!-- Images will be inserted here -->
|
||||
</div>
|
||||
|
||||
<!-- Pagination -->
|
||||
<div id="paginationControls" class="hidden mt-4 flex items-center justify-center gap-2">
|
||||
<button id="prevPageBtn" class="px-3 py-1 bg-pm-surface hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
Previous
|
||||
</button>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-pm-secondary text-xs">Page</span>
|
||||
<input id="pageInput" type="number" min="1" class="w-16 px-2 py-1 bg-pm-input text-pm text-xs text-center rounded-pm-sm border border-pm focus:border-pm-accent focus:outline-none" value="1">
|
||||
<span id="pageInfo" class="text-pm-secondary text-xs">of 1</span>
|
||||
</div>
|
||||
<button id="nextPageBtn" class="px-3 py-1 bg-pm-surface hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div> <!-- /Main Gallery Area -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Settings Modal -->
|
||||
<div id="settingsModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
|
||||
<div class="bg-pm-surface rounded-pm-md max-w-2xl w-full max-h-[90vh] overflow-hidden mx-4 border border-pm">
|
||||
<div class="p-3 border-b border-pm">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-sm font-semibold text-pm">Page options</h3>
|
||||
<button id="closeSettingsBtn" class="p-2 rounded-pm-sm hover:bg-pm-hover transition-colors">
|
||||
<svg class="w-4 h-4 text-pm-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-3 overflow-y-auto max-h-[calc(90vh-200px)] space-y-4">
|
||||
|
||||
<!-- Performance Settings -->
|
||||
<div class="space-y-3">
|
||||
<h4 class="text-sm font-semibold text-pm">Performance Settings</h4>
|
||||
|
||||
<div class="bg-pm-input rounded-pm-sm p-3 space-y-2">
|
||||
<!-- Check thumbnails at startup -->
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<label class="text-xs text-pm-secondary">Check thumbnails at startup</label>
|
||||
<p class="text-xs text-pm-muted">Prompt to generate thumbnails if missing when opening gallery</p>
|
||||
</div>
|
||||
<label class="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" id="checkThumbnailsAtStartup" class="sr-only peer" checked>
|
||||
<div class="w-11 h-6 bg-pm-input peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-pm-accent rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-pm after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-pm-accent"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="text-xs text-pm-secondary">Lazy Loading</label>
|
||||
<input type="checkbox" id="lazyLoadingToggle" checked class="w-4 h-4 text-pm-accent bg-pm-input border-pm rounded focus:ring-pm-accent">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Display Settings -->
|
||||
<div class="space-y-3">
|
||||
<h4 class="text-sm font-semibold text-pm">Display Settings</h4>
|
||||
|
||||
<div class="bg-pm-input rounded-pm-sm p-3 space-y-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="text-xs text-pm-secondary">Items per Page</label>
|
||||
<select id="defaultLimitSelect" class="px-2 py-1 bg-pm-input border border-pm rounded-pm-sm text-pm text-xs">
|
||||
<option value="50">50</option>
|
||||
<option value="100" selected>100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="text-xs text-pm-secondary">Grid Columns (Desktop)</label>
|
||||
<select id="gridColumnsSelect" class="px-2 py-1 bg-pm-input border border-pm rounded-pm-sm text-pm text-xs">
|
||||
<option value="4">4 Columns</option>
|
||||
<option value="6">6 Columns</option>
|
||||
<option value="8" selected>8 Columns</option>
|
||||
<option value="10">10 Columns</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<label class="text-xs text-pm-secondary">Infinite Scrolling</label>
|
||||
<p class="text-[11px] text-pm-muted">Load the next page as you scroll instead of showing page controls</p>
|
||||
</div>
|
||||
<input type="checkbox" id="infiniteScrollToggle" class="w-4 h-4 text-pm-accent bg-pm-input border-pm rounded focus:ring-pm-accent">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Advanced Settings -->
|
||||
<div class="space-y-3">
|
||||
<h4 class="text-sm font-semibold text-pm">Advanced</h4>
|
||||
|
||||
<div class="bg-pm-input rounded-pm-sm p-3 space-y-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="text-xs text-pm-secondary">Debug Mode</label>
|
||||
<input type="checkbox" id="debugModeToggle" class="w-4 h-4 text-pm-accent bg-pm-input border-pm rounded focus:ring-pm-accent">
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="text-xs text-pm-secondary">API Timeout (seconds)</label>
|
||||
<input type="number" id="apiTimeoutInput" value="30" min="5" max="300" class="px-2 py-1 bg-pm-input border border-pm rounded-pm-sm text-pm text-xs w-20">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-xs text-pm-secondary">Thumbnails, cache, file listing and duplicates are in System.
|
||||
<a id="pageOptionsMaintenanceLink" href="workspace#/system/maintenance" target="_blank" rel="noopener"
|
||||
title="Opens System › Maintenance in a new tab" class="text-pm-accent hover:underline">Maintenance</a>
|
||||
·
|
||||
<a id="pageOptionsSourcesLink" href="workspace#/system/sources" target="_blank" rel="noopener"
|
||||
title="Opens System › Sources & scans in a new tab" class="text-pm-accent hover:underline">Sources & scans</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="p-3 border-t border-pm flex justify-end gap-2">
|
||||
<button id="resetSettingsBtn" class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Reset to Defaults
|
||||
</button>
|
||||
<button id="saveSettingsBtn" class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Save Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auto Tag Modal -->
|
||||
<div id="autoTagModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
|
||||
<div class="bg-pm-surface rounded-pm-md p-3 max-w-lg w-full mx-4 border border-pm">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-sm font-semibold text-pm">Auto Tag Images</h3>
|
||||
<button onclick="hideModal('autoTagModal')" class="p-2 rounded-pm-sm hover:bg-pm-hover transition-colors">
|
||||
<svg class="w-4 h-4 text-pm-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Model Selection -->
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-2">Model Selection</label>
|
||||
<div class="space-y-2">
|
||||
<label class="flex items-center justify-between p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<div class="flex items-center">
|
||||
<input type="radio" name="autoTagModel" value="gguf" checked class="w-4 h-4 text-pm-accent bg-pm-input border-pm focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">GGUF Model</span>
|
||||
<span class="text-pm-secondary text-xs ml-2">(Recommended, ~4.5GB)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ggufModelStatus" class="flex items-center gap-2">
|
||||
<span class="text-pm-secondary text-xs">Checking...</span>
|
||||
</div>
|
||||
</label>
|
||||
<label class="flex items-center justify-between p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<div class="flex items-center">
|
||||
<input type="radio" name="autoTagModel" value="hf" class="w-4 h-4 text-pm-accent bg-pm-input border-pm focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">HuggingFace Model</span>
|
||||
<span class="text-pm-secondary text-xs ml-2">(~16GB)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="hfModelStatus" class="flex items-center gap-2">
|
||||
<span class="text-pm-secondary text-xs">Checking...</span>
|
||||
</div>
|
||||
</label>
|
||||
<label class="flex items-center justify-between p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<div class="flex items-center">
|
||||
<input type="radio" name="autoTagModel" value="wd14-swinv2" class="w-4 h-4 text-pm-accent bg-pm-input border-pm focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">WD14 SwinV2</span>
|
||||
<span class="text-pm-secondary text-xs ml-2">(~400MB, fast classifier)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wd14SwinV2ModelStatus" class="flex items-center gap-2">
|
||||
<span class="text-pm-secondary text-xs">Checking...</span>
|
||||
</div>
|
||||
</label>
|
||||
<label class="flex items-center justify-between p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<div class="flex items-center">
|
||||
<input type="radio" name="autoTagModel" value="wd14-vit" class="w-4 h-4 text-pm-accent bg-pm-input border-pm focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">WD14 ViT</span>
|
||||
<span class="text-pm-secondary text-xs ml-2">(~400MB, ViT architecture)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wd14VitModelStatus" class="flex items-center gap-2">
|
||||
<span class="text-pm-secondary text-xs">Checking...</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Keep Model in Memory Option -->
|
||||
<div class="mb-3">
|
||||
<label class="flex items-center justify-between p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<div class="flex items-center">
|
||||
<input type="checkbox" id="keepModelInMemory" checked class="w-4 h-4 text-pm-accent bg-pm-input border-pm rounded focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">Keep model in memory</span>
|
||||
<span class="text-pm-secondary text-xs ml-2">(Faster processing, uses ~4-16GB VRAM)</span>
|
||||
</div>
|
||||
</div>
|
||||
<a id="unloadModelBtn" href="workspace#/system/tagging" target="_blank" rel="noopener"
|
||||
title="Unload the model in System › Auto-tagging (opens a new tab)"
|
||||
class="px-3 py-1 bg-pm-error hover:bg-pm-error text-pm text-xs rounded-pm-sm transition-colors hidden">
|
||||
Manage in System
|
||||
</a>
|
||||
</label>
|
||||
<p id="modelLoadedStatus" class="text-pm-muted text-xs mt-1 hidden">
|
||||
<span class="text-pm-success">●</span> Model currently loaded: <span id="loadedModelType">none</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Prompt Template (LLM models only) -->
|
||||
<div id="promptSection" class="mb-3">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-2">Tag Generation Prompt</label>
|
||||
<textarea id="autoTagPrompt" rows="6"
|
||||
class="w-full px-3 py-2 bg-pm-input border border-pm rounded-pm-sm focus:ring-2 focus:ring-pm-accent focus:border-pm-accent text-pm text-xs font-mono resize-none"
|
||||
placeholder="Enter prompt template...">Generate only comma-separated Danbooru tags (lowercase_underscores, no spaces).
|
||||
Include: subject_count (1girl/1boy/etc), gender, ethnicity (asian, caucasian, etc), age_approx (teen, young_woman), body_attributes, face_features, hairstyle, appearance, clothing, accessories, pose, expression, action, camera_angle, camera_shot, scene_composition (wide_shot, long_shot, dutch_angle), environment, background_elements, lighting, mood.
|
||||
Prioritize visual accuracy.
|
||||
No sentences, no commentary, no captions. Only tags. Keep length short but descriptive.</textarea>
|
||||
</div>
|
||||
|
||||
<!-- WD14 Threshold Controls -->
|
||||
<div id="wd14ThresholdSection" class="mb-3 hidden">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-2">Tag Confidence Thresholds</label>
|
||||
<div class="space-y-3">
|
||||
<div class="p-2.5 bg-pm-input rounded-pm-sm border border-pm">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-pm text-xs">General tags</span>
|
||||
<span id="wd14GeneralThresholdValue" class="text-pm-accent text-xs font-mono">0.35</span>
|
||||
</div>
|
||||
<input type="range" id="wd14GeneralThreshold" min="0" max="1" step="0.05" value="0.35"
|
||||
class="w-full h-1.5 bg-pm-primary rounded-lg appearance-none cursor-pointer accent-[var(--pm-accent)]">
|
||||
</div>
|
||||
<div class="p-2.5 bg-pm-input rounded-pm-sm border border-pm">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-pm text-xs">Character tags</span>
|
||||
<span id="wd14CharacterThresholdValue" class="text-pm-accent text-xs font-mono">0.85</span>
|
||||
</div>
|
||||
<input type="range" id="wd14CharacterThreshold" min="0" max="1" step="0.05" value="0.85"
|
||||
class="w-full h-1.5 bg-pm-primary rounded-lg appearance-none cursor-pointer accent-[var(--pm-accent)]">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="flex justify-end gap-2">
|
||||
<button onclick="hideModal('autoTagModal')"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
<button id="startReviewBtn"
|
||||
class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Review
|
||||
</button>
|
||||
<button id="startAutoTagBtn"
|
||||
class="px-3 py-1 bg-pm-accent hover:bg-pm-accent-hover text-pm-accent-fg text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Auto Tag
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auto Tag Review Modal -->
|
||||
<div id="autoTagReviewModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
|
||||
<div class="bg-pm-surface rounded-pm-md p-3 max-w-4xl w-full mx-4 border border-pm">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-sm font-semibold text-pm">
|
||||
Review Tags
|
||||
<span class="text-pm-secondary text-xs font-normal">(<span id="reviewCurrentIndex">1</span> of <span id="reviewTotalCount">0</span>)</span>
|
||||
</h3>
|
||||
<button onclick="window.gallery.cancelReview()" class="p-2 rounded-pm-sm hover:bg-pm-hover transition-colors">
|
||||
<svg class="w-4 h-4 text-pm-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<!-- Image Preview -->
|
||||
<div class="bg-pm-primary rounded-pm-sm p-3">
|
||||
<img id="reviewImage" src="" alt="Review image" class="w-full h-64 object-contain rounded-pm-sm">
|
||||
<p id="reviewImageName" class="text-pm-secondary text-xs mt-2 text-center truncate">image_name.png</p>
|
||||
</div>
|
||||
|
||||
<!-- Generated Tags -->
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-2">Generated Tags (click to remove)</label>
|
||||
<div id="reviewTagsContainer" class="flex flex-wrap gap-2 p-3 bg-pm-primary rounded-pm-sm min-h-[200px] max-h-[250px] overflow-y-auto">
|
||||
<!-- Tag chips will be inserted here -->
|
||||
</div>
|
||||
<p class="text-pm-muted text-xs mt-1">Click the x on tags to remove them before applying</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="flex justify-between mt-3">
|
||||
<button id="skipReviewBtn"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Skip
|
||||
</button>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="window.gallery.cancelReview()"
|
||||
class="px-3 py-1 bg-pm-error hover:bg-pm-error text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Cancel All
|
||||
</button>
|
||||
<button id="applyReviewBtn"
|
||||
class="px-3 py-1 bg-pm-success hover:bg-pm-success text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Apply & Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auto Tag Progress Modal -->
|
||||
<div id="autoTagProgressModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
|
||||
<div class="bg-pm-surface rounded-pm-md p-3 max-w-md w-full mx-4 border border-pm">
|
||||
<h3 class="text-sm font-semibold text-pm mb-3">Auto Tagging Progress</h3>
|
||||
|
||||
<!-- Current File -->
|
||||
<div class="mb-3">
|
||||
<p class="text-pm-secondary text-xs">Processing:</p>
|
||||
<p id="autoTagCurrentFile" class="text-pm text-xs font-medium truncate">Initializing...</p>
|
||||
</div>
|
||||
|
||||
<!-- Progress Bar -->
|
||||
<div class="mb-3">
|
||||
<div class="flex justify-between text-xs text-pm-secondary mb-1">
|
||||
<span>Progress</span>
|
||||
<span id="autoTagProgressPercent">0%</span>
|
||||
</div>
|
||||
<div class="w-full bg-pm-input rounded-full h-2">
|
||||
<div id="autoTagProgressBar" class="bg-pm-accent h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
|
||||
</div>
|
||||
<p id="autoTagCloseNote" class="text-pm-muted text-xs mt-1.5">Closing this window stops tagging. Tags already added are kept. Prompt Manager's Activity page shows the time left.</p>
|
||||
</div>
|
||||
|
||||
<!-- Stats -->
|
||||
<div class="grid grid-cols-3 gap-2 mb-3">
|
||||
<div class="bg-pm-input rounded-pm-sm p-2 text-center">
|
||||
<div class="text-sm font-semibold text-pm-accent" id="autoTagProcessed">0</div>
|
||||
<div class="text-xs text-pm-secondary">Processed</div>
|
||||
</div>
|
||||
<div class="bg-pm-input rounded-pm-sm p-2 text-center">
|
||||
<div class="text-sm font-semibold text-pm-success" id="autoTagApplied">0</div>
|
||||
<div class="text-xs text-pm-secondary">Tags Applied</div>
|
||||
</div>
|
||||
<div class="bg-pm-input rounded-pm-sm p-2 text-center">
|
||||
<div class="text-sm font-semibold text-pm-warning" id="autoTagSkipped">0</div>
|
||||
<div class="text-xs text-pm-secondary">Skipped</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cancel Button -->
|
||||
<div class="flex justify-center">
|
||||
<button id="cancelAutoTagBtn"
|
||||
class="px-3 py-1 bg-pm-error hover:bg-pm-error text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add Prompt Modal -->
|
||||
<div id="addPromptModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
|
||||
<div class="bg-pm-surface rounded-pm-md p-3 max-w-2xl w-full mx-4 border border-pm max-h-[90vh] overflow-y-auto">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-sm font-semibold text-pm">Add New Prompt</h3>
|
||||
<button onclick="window.gallery.hideAddPromptModal()" class="p-2 rounded-pm-sm hover:bg-pm-hover transition-colors">
|
||||
<svg class="w-4 h-4 text-pm-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Prompt Text -->
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-1">Prompt Text <span class="text-pm-error">*</span></label>
|
||||
<textarea id="addPromptText" rows="4"
|
||||
class="w-full px-3 py-2 bg-pm-input border border-pm rounded-pm-sm focus:ring-2 focus:ring-pm-accent focus:border-pm-accent text-pm text-xs resize-none"
|
||||
placeholder="Enter your prompt text here..."></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Category and Rating Row -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
|
||||
<!-- Category -->
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-1">Category</label>
|
||||
<div class="relative">
|
||||
<input type="text" id="addPromptCategory" list="categoryList"
|
||||
class="w-full px-3 py-2 bg-pm-input border border-pm rounded-pm-sm focus:ring-2 focus:ring-pm-accent focus:border-pm-accent text-pm text-xs"
|
||||
placeholder="Select or type category...">
|
||||
<datalist id="categoryList"></datalist>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Rating -->
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-1">Rating</label>
|
||||
<div class="flex items-center gap-1" id="addPromptRating">
|
||||
<button type="button" class="rating-star text-lg text-pm-muted hover:text-pm-warning transition-colors" data-rating="1">☆</button>
|
||||
<button type="button" class="rating-star text-lg text-pm-muted hover:text-pm-warning transition-colors" data-rating="2">☆</button>
|
||||
<button type="button" class="rating-star text-lg text-pm-muted hover:text-pm-warning transition-colors" data-rating="3">☆</button>
|
||||
<button type="button" class="rating-star text-lg text-pm-muted hover:text-pm-warning transition-colors" data-rating="4">☆</button>
|
||||
<button type="button" class="rating-star text-lg text-pm-muted hover:text-pm-warning transition-colors" data-rating="5">☆</button>
|
||||
<button type="button" class="ml-2 text-xs text-pm-muted hover:text-pm-secondary" id="clearRatingBtn">Clear</button>
|
||||
</div>
|
||||
<input type="hidden" id="addPromptRatingValue" value="">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tags -->
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-1">Tags</label>
|
||||
<div class="relative">
|
||||
<div id="addPromptTagsContainer" class="flex flex-wrap gap-2 p-2 bg-pm-input border border-pm rounded-pm-sm min-h-[44px]">
|
||||
<input type="text" id="addPromptTagInput"
|
||||
class="flex-1 min-w-[150px] bg-transparent border-none outline-none text-pm text-xs placeholder-pm"
|
||||
placeholder="Type to add tags...">
|
||||
</div>
|
||||
<div id="tagSuggestions" class="absolute left-0 right-0 top-full mt-1 bg-pm-surface border border-pm rounded-pm-sm shadow-pm hidden z-10 max-h-48 overflow-y-auto"></div>
|
||||
</div>
|
||||
<p class="text-pm-muted text-xs mt-1">Press Enter or comma to add a tag. Click a tag to remove it.</p>
|
||||
</div>
|
||||
|
||||
<!-- Notes -->
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-pm-secondary mb-1">Notes</label>
|
||||
<textarea id="addPromptNotes" rows="2"
|
||||
class="w-full px-3 py-2 bg-pm-input border border-pm rounded-pm-sm focus:ring-2 focus:ring-pm-accent focus:border-pm-accent text-pm text-xs resize-none"
|
||||
placeholder="Optional notes about this prompt..."></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Protection Option -->
|
||||
<div class="mb-3">
|
||||
<label class="flex items-start p-3 bg-pm-input rounded-pm-sm cursor-pointer hover:bg-pm-hover border border-pm">
|
||||
<input type="checkbox" id="addPromptProtected" checked class="w-4 h-4 mt-0.5 text-pm-accent bg-pm-input border-pm rounded focus:ring-pm-accent">
|
||||
<div class="ml-3">
|
||||
<span class="text-pm text-xs font-medium">Protect from orphan cleanup</span>
|
||||
<p class="text-pm-secondary text-xs mt-1">Keep this prompt even if it has no linked images. Uncheck if you want this prompt to be automatically removed during maintenance when it has no images.</p>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="flex justify-end gap-2">
|
||||
<button onclick="window.gallery.hideAddPromptModal()"
|
||||
class="px-3 py-1 bg-pm-input hover:bg-pm-hover text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
<button id="saveNewPromptBtn"
|
||||
class="px-3 py-1 bg-pm-success hover:bg-pm-success text-pm text-xs font-medium rounded-pm-sm transition-colors">
|
||||
Add Prompt
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script src="js/comfy-metadata.js"></script>
|
||||
<script src="js/gallery.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
-3102
File diff suppressed because it is too large
Load Diff
@@ -6,8 +6,8 @@
|
||||
* keywords in the text. Falls back to the UI `workflow` graph only for
|
||||
* fields the API graph could not provide.
|
||||
*
|
||||
* Shared by admin.js, gallery.js and metadata.html; also loadable in Node
|
||||
* for tests.
|
||||
* Loaded by the workspace (web/workspace.html); also loadable in Node for
|
||||
* tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Dispatch for elements rendered with `data-action="..."`.
|
||||
*
|
||||
* The admin and gallery pages build HTML from server data with template
|
||||
* literals. Inline `onclick="...${value}..."` handlers would put that data
|
||||
* inside JavaScript source, where HTML escaping does not help; instead the
|
||||
* markup carries `data-*` attributes and one delegated click listener per page
|
||||
* calls `dispatch(element.dataset, handlers, element)`.
|
||||
*
|
||||
* Loadable in the browser (window.DataActions) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
function toInt(value) {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const n = parseInt(value, 10);
|
||||
return Number.isNaN(n) ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DOMStringMap|Object|null|undefined} dataset
|
||||
* @returns {{action: string, promptId: number|null, index: number|null} & Object<string, string>}
|
||||
*/
|
||||
function readAction(dataset) {
|
||||
const data = dataset || {};
|
||||
return {
|
||||
...data,
|
||||
action: typeof data.action === "string" ? data.action : "",
|
||||
promptId: toInt(data.promptId),
|
||||
index: toInt(data.index),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DOMStringMap|Object} dataset - the clicked element's dataset
|
||||
* @param {Object<string, Function>} handlers - handler per action name
|
||||
* @param {...*} extra - passed to the handler after the parsed action
|
||||
* @returns {boolean} whether a handler ran
|
||||
*/
|
||||
function dispatch(dataset, handlers, ...extra) {
|
||||
const parsed = readAction(dataset);
|
||||
if (!parsed.action || !Object.prototype.hasOwnProperty.call(handlers, parsed.action)) return false;
|
||||
handlers[parsed.action](parsed, ...extra);
|
||||
return true;
|
||||
}
|
||||
|
||||
const api = { readAction, dispatch };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.DataActions = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
-3053
File diff suppressed because it is too large
Load Diff
@@ -1,42 +0,0 @@
|
||||
/**
|
||||
* HTML escaping for the admin, gallery and metadata pages.
|
||||
*
|
||||
* Escapes the five characters that matter in both text and attribute context
|
||||
* (& < > " '), so one function is safe for `innerHTML` text nodes and for
|
||||
* `data-*` / `value` / `title` attributes alike. The old `textContent` ->
|
||||
* `innerHTML` trick left quotes untouched and let a tag such as
|
||||
* `" onmouseover="alert(1)` break out of an attribute.
|
||||
*
|
||||
* Loadable in the browser (window.escapeHtml / window.HtmlEscape) and in Node
|
||||
* for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const REPLACEMENTS = Object.freeze({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
});
|
||||
const UNSAFE = /[&<>"']/g;
|
||||
|
||||
/**
|
||||
* @param {unknown} value - anything; null/undefined become "", others go through String()
|
||||
* @returns {string} text safe to interpolate into HTML text or a quoted attribute
|
||||
*/
|
||||
function escapeHtml(value) {
|
||||
if (value === null || value === undefined) return "";
|
||||
return String(value).replace(UNSAFE, (ch) => REPLACEMENTS[ch]);
|
||||
}
|
||||
|
||||
const api = { escapeHtml, escapeAttr: escapeHtml };
|
||||
if (typeof module !== "undefined" && module.exports) {
|
||||
module.exports = api;
|
||||
} else {
|
||||
root.HtmlEscape = api;
|
||||
root.escapeHtml = escapeHtml;
|
||||
root.escapeAttr = escapeHtml;
|
||||
}
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,162 +0,0 @@
|
||||
/**
|
||||
* Pure helpers for image entries rendered by the admin and gallery pages.
|
||||
*
|
||||
* Image rows come from the database (`width`, `height`, `file_size` are stored
|
||||
* from a POST body and may be strings) or from the output-folder scan (`id` is
|
||||
* a path digest, `path` is the file). Everything these helpers return for HTML
|
||||
* is already escaped, so callers can drop it into text or a quoted attribute.
|
||||
*
|
||||
* Loadable in the browser (window.ImageHelpers) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const escapeHtml =
|
||||
typeof module !== "undefined" && module.exports
|
||||
? require("./html-escape.js").escapeHtml
|
||||
: root.escapeHtml;
|
||||
|
||||
const UNKNOWN_SIZE = "Unknown size";
|
||||
|
||||
/**
|
||||
* "640×480 | 1.2 MB" for a card body or a viewer caption, escaped.
|
||||
*
|
||||
* @param {{width?: unknown, height?: unknown, file_size?: unknown}|null|undefined} image
|
||||
* @param {{formatFileSize?: (bytes: number) => string, separator?: string}} [options]
|
||||
* @returns {string} escaped text; "Unknown size" when a dimension is missing
|
||||
*/
|
||||
function formatImageCaption(image, { formatFileSize, separator = " | " } = {}) {
|
||||
const entry = image || {};
|
||||
const parts = [];
|
||||
if (entry.width && entry.height) {
|
||||
parts.push(`${escapeHtml(entry.width)}×${escapeHtml(entry.height)}`);
|
||||
} else {
|
||||
parts.push(UNKNOWN_SIZE);
|
||||
}
|
||||
const bytes = Number(entry.file_size);
|
||||
if (formatFileSize && Number.isFinite(bytes) && bytes > 0) {
|
||||
parts.push(escapeHtml(formatFileSize(bytes)));
|
||||
}
|
||||
return parts.join(escapeHtml(separator));
|
||||
}
|
||||
|
||||
/**
|
||||
* A complete standalone page showing a workflow as pretty-printed JSON.
|
||||
* Written into a blank same-origin window, so the JSON must not be able
|
||||
* to close the <pre> and inject markup.
|
||||
*
|
||||
* @param {unknown} workflow
|
||||
* @returns {string} HTML document
|
||||
*/
|
||||
function workflowDocumentHtml(workflow) {
|
||||
const json = escapeHtml(JSON.stringify(workflow, null, 2));
|
||||
return [
|
||||
"<!DOCTYPE html>",
|
||||
"<html>",
|
||||
"<head><meta charset=\"utf-8\"><title>ComfyUI Workflow Data</title></head>",
|
||||
"<body style=\"background: #111; color: #fff; font-family: monospace; padding: 20px;\">",
|
||||
"<h2>ComfyUI Workflow JSON</h2>",
|
||||
`<pre style="background: #222; padding: 15px; border-radius: 5px; overflow: auto;">${json}</pre>`,
|
||||
"</body>",
|
||||
"</html>",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Body for POST /prompt_manager/autotag/single.
|
||||
*
|
||||
* Database rows (admin review, /images/all) have an integer id the server
|
||||
* looks up; output-folder entries (gallery review, /images/output) have a
|
||||
* path digest as id, which would 404, so those are addressed by path.
|
||||
*
|
||||
* @param {{id?: unknown, path?: unknown}} image
|
||||
* `existing` (#379): "skip" answers `already_tagged` for an image a model
|
||||
* already tagged; anything else is "merge" (always suggest).
|
||||
*
|
||||
* @param {{id?: unknown, path?: unknown}} image
|
||||
* @param {{modelType: string, generalThreshold?: number, characterThreshold?: number, prompt?: string, existing?: string}} settings
|
||||
* @returns {object} JSON-serialisable request body
|
||||
*/
|
||||
function autotagSingleBody(image, settings) {
|
||||
const target = autotagTarget(image);
|
||||
const existing = settings.existing === "skip" ? "skip" : "merge";
|
||||
const modelType = String(settings.modelType || "");
|
||||
const params = modelType.startsWith("wd14")
|
||||
? {
|
||||
general_threshold: settings.generalThreshold,
|
||||
character_threshold: settings.characterThreshold,
|
||||
}
|
||||
: { prompt: settings.prompt };
|
||||
return { ...target, model_type: modelType, existing, ...params };
|
||||
}
|
||||
|
||||
/** The image a legacy single/apply body names: its row id, or its path (and root). */
|
||||
function autotagTarget(image) {
|
||||
const entry = image || {};
|
||||
const target =
|
||||
typeof entry.path === "string" && entry.path && !Number.isInteger(entry.id)
|
||||
? { path: entry.path }
|
||||
: { image_id: entry.id };
|
||||
if ("path" in target && Number.isInteger(entry.root_index)) {
|
||||
target.root_index = entry.root_index;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Body for POST /prompt_manager/autotag/apply (#379): the image, the
|
||||
* `sha256` /autotag/single answered and the reviewed tags. The tags go to
|
||||
* that image only, never to its prompt; an empty list marks it reviewed.
|
||||
*/
|
||||
function autotagApplyBody(image, sha256, tags) {
|
||||
return { ...autotagTarget(image), sha256: String(sha256 || ""), tags: Array.isArray(tags) ? [...tags] : [] };
|
||||
}
|
||||
|
||||
/** The legacy batch's completion toast (#379): images, never prompts. */
|
||||
function autotagCompleteMessage(tagged) {
|
||||
const count = Number.isSafeInteger(tagged) && tagged > 0 ? tagged : 0;
|
||||
return `Auto tagging complete! Tagged ${count} ${count === 1 ? "image" : "images"}.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Next source to try after an <img> fails. Cards show the thumbnail first;
|
||||
* when it fails (stale cache, half-written file) the original is worth one
|
||||
* attempt. Returns null when there is nothing left to try.
|
||||
* @param {string} currentSrc
|
||||
* @param {DOMStringMap|object|undefined} dataset `data-original`, `data-fell-back`
|
||||
*/
|
||||
function fallbackImageSource(currentSrc, dataset) {
|
||||
if (!dataset || dataset.fellBack) return null;
|
||||
const original = dataset.original;
|
||||
if (!original || original === currentSrc) return null;
|
||||
return original;
|
||||
}
|
||||
|
||||
function metadataLookupUrl(imageUrl) {
|
||||
try {
|
||||
const url = new URL(imageUrl, 'http://prompt-manager.invalid');
|
||||
const marker = '/prompt_manager/images/serve/';
|
||||
const index = url.pathname.indexOf(marker);
|
||||
if (index < 0) return null;
|
||||
const relativePath = decodeURIComponent(url.pathname.slice(index + marker.length));
|
||||
const query = new URLSearchParams();
|
||||
if (url.searchParams.has('root')) query.set('root', url.searchParams.get('root'));
|
||||
const suffix = query.size ? `?${query}` : '';
|
||||
return `/prompt_manager/images/prompt/${encodeURIComponent(relativePath)}${suffix}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const api = {
|
||||
formatImageCaption,
|
||||
workflowDocumentHtml,
|
||||
autotagSingleBody,
|
||||
autotagApplyBody,
|
||||
autotagCompleteMessage,
|
||||
fallbackImageSource,
|
||||
metadataLookupUrl,
|
||||
};
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.ImageHelpers = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Where a bookmark of the retired admin page lands in the workspace (#668, D207).
|
||||
*
|
||||
* `/prompt_manager/admin` is now web/admin-redirect.html, which sends the browser
|
||||
* to the target this module computes from `location.hash` (the server never sees
|
||||
* the hash). The old routes were `#/tags` and `#/tags/<tag>,<tag>[?mode=or]`
|
||||
* (tags-page.js updateUrlHash: encodeURIComponent per tag, `?mode=or` only for
|
||||
* two or more tags; `__untagged__` stood for the prompts without a tag).
|
||||
*
|
||||
* Loadable in the browser (window.LegacyLinks) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const LIBRARY = "workspace#/library";
|
||||
const TAGS = "workspace#/tags";
|
||||
const TAGS_ROUTE = "#/tags";
|
||||
const UNTAGGED = "__untagged__";
|
||||
|
||||
/** One tag of the old comma list; a segment that cannot be decoded is used as written. */
|
||||
function decodeTag(segment) {
|
||||
const raw = segment.trim();
|
||||
try {
|
||||
return decodeURIComponent(raw).trim();
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} hash - window.location.hash of the old admin page, including the leading "#"
|
||||
* @returns {string} the workspace URL to open, relative to the old page (so a mount prefix is kept)
|
||||
*/
|
||||
function adminTarget(hash) {
|
||||
if (typeof hash !== "string") return LIBRARY;
|
||||
if (hash === TAGS_ROUTE) return TAGS;
|
||||
if (!hash.startsWith(TAGS_ROUTE + "/")) return LIBRARY;
|
||||
// As the old page read it: tags before the first "?", its query up to the next one.
|
||||
const [tagsPart, queryPart = ""] = hash.slice(TAGS_ROUTE.length + 1).split("?");
|
||||
const tags = [...new Set(tagsPart.split(",").map(decodeTag).filter(Boolean))];
|
||||
if (!tags.length) return TAGS;
|
||||
const query = new URLSearchParams();
|
||||
if (tags.includes(UNTAGGED)) {
|
||||
// The old page asked for untagged prompts whenever the entry was in the list.
|
||||
query.set("tag_mode", "untagged");
|
||||
} else {
|
||||
for (const tag of tags) query.append("tag", tag);
|
||||
if (tags.length > 1 && new URLSearchParams(queryPart).get("mode") === "or") query.set("tag_mode", "any");
|
||||
}
|
||||
return `${LIBRARY}?${query}`;
|
||||
}
|
||||
|
||||
const api = { adminTarget };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.LegacyLinks = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,64 +0,0 @@
|
||||
/**
|
||||
* Pure state helpers for the paginated prompt and image lists.
|
||||
*
|
||||
* Loadable in the browser (window.ListState) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
function nonNegativeInt(value) {
|
||||
return Number.isInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination state after a page fetch succeeded. Callers keep their current
|
||||
* state untouched while the request is in flight and only adopt the result.
|
||||
*
|
||||
* @param {{page: number, limit: number, total: number}} current
|
||||
* @param {{page?: number, limit?: number, total?: number}} response - the page
|
||||
* that was requested and the total the server reported
|
||||
* @returns {{page: number, limit: number, total: number, totalPages: number}}
|
||||
*/
|
||||
function nextPageState(current, response) {
|
||||
const limit = Number.isInteger(response.limit) && response.limit > 0 ? response.limit : current.limit;
|
||||
const total = nonNegativeInt(response.total) ?? current.total;
|
||||
const totalPages = Math.max(1, Math.ceil(total / limit));
|
||||
const requested = Number.isInteger(response.page) ? response.page : current.page;
|
||||
const page = Math.min(Math.max(1, requested), totalPages);
|
||||
return { page, limit, total, totalPages };
|
||||
}
|
||||
|
||||
/** Whether an in-place prompt edit changed the text to something worth saving. */
|
||||
function shouldSaveEdit(originalText, newText) {
|
||||
if (typeof newText !== "string") return false;
|
||||
const trimmed = newText.trim();
|
||||
return trimmed !== "" && trimmed !== String(originalText ?? "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether another page should be fetched from a capped list endpoint such as
|
||||
* /prompt_manager/images/all: the server said has_more and the last page was not empty.
|
||||
*/
|
||||
function hasMorePages(response, receivedCount) {
|
||||
const pagination = response && response.pagination;
|
||||
return Boolean(pagination && pagination.has_more) && receivedCount > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infinite scrolling: fetch the next page when the user is within `threshold`
|
||||
* pixels of the bottom (or the content does not fill the viewport yet), no
|
||||
* load is in flight and pages remain.
|
||||
*/
|
||||
function shouldLoadMore({ infiniteScroll, loading, page, limit, total, scrollTop, clientHeight, scrollHeight, threshold = 600 }) {
|
||||
if (!infiniteScroll || loading) return false;
|
||||
const pageSize = nonNegativeInt(limit) || 1;
|
||||
const totalPages = Math.ceil(nonNegativeInt(total) / pageSize);
|
||||
if (nonNegativeInt(page) >= totalPages) return false;
|
||||
const remaining = scrollHeight - clientHeight - scrollTop;
|
||||
return remaining < threshold;
|
||||
}
|
||||
|
||||
const api = { nextPageState, shouldSaveEdit, hasMorePages, shouldLoadMore };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.ListState = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,64 +0,0 @@
|
||||
/**
|
||||
* Prompt list sorting for the admin dashboard (3.2.4, #90.1).
|
||||
*
|
||||
* Sorting happens on the server so it spans every page; this module only owns the
|
||||
* option list, validation and request URLs. The option values must match
|
||||
* SORT_ORDERS in database/operations.py (enforced by tests/test_sort_contract.py).
|
||||
*
|
||||
* Loadable in the browser (window.PromptListSort) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const SORT_OPTIONS = Object.freeze(
|
||||
[
|
||||
{ value: "last_used_desc", label: "Recently Used" },
|
||||
{ value: "created_desc", label: "Newest First" },
|
||||
{ value: "created_asc", label: "Oldest First" },
|
||||
{ value: "run_count_desc", label: "Most Used" },
|
||||
{ value: "rating_desc", label: "Highest Rated" },
|
||||
{ value: "rating_asc", label: "Lowest Rated" },
|
||||
{ value: "text_asc", label: "A-Z" },
|
||||
{ value: "text_desc", label: "Z-A" },
|
||||
].map((option) => Object.freeze(option)),
|
||||
);
|
||||
|
||||
const DEFAULT_SORT = "last_used_desc";
|
||||
const DEFAULT_LIMIT = 50;
|
||||
const KNOWN = new Set(SORT_OPTIONS.map((o) => o.value));
|
||||
|
||||
/** A known sort key, or DEFAULT_SORT for anything else. */
|
||||
function normalizeSort(value) {
|
||||
return typeof value === "string" && KNOWN.has(value) ? value : DEFAULT_SORT;
|
||||
}
|
||||
|
||||
/** URL for one page of /prompt_manager/recent. */
|
||||
function buildRecentUrl({ page = 1, limit = DEFAULT_LIMIT, sort } = {}) {
|
||||
const params = new URLSearchParams({
|
||||
limit: String(limit),
|
||||
offset: String((page - 1) * limit),
|
||||
page: String(page),
|
||||
sort: normalizeSort(sort),
|
||||
});
|
||||
return `/prompt_manager/recent?${params}`;
|
||||
}
|
||||
|
||||
/** Copy of `params` with a validated sort key; the input is not modified. */
|
||||
function withSort(params, sort) {
|
||||
const copy = new URLSearchParams(params);
|
||||
copy.set("sort", normalizeSort(sort));
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Badge text for a prompt's run count; empty when the count is unknown. */
|
||||
function formatRunCount(count) {
|
||||
if (!Number.isInteger(count) || count < 0) return "";
|
||||
if (count === 0) return "Never run";
|
||||
if (count === 1) return "1 run";
|
||||
return `${count.toLocaleString("en-US")} runs`;
|
||||
}
|
||||
|
||||
const api = { SORT_OPTIONS, DEFAULT_SORT, normalizeSort, buildRecentUrl, withSort, formatRunCount };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.PromptListSort = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* State of the output-image scan as seen by the dashboard.
|
||||
*
|
||||
* The scan runs on the server as a background job (see py/api/jobs.py) and
|
||||
* reports progress over SSE. This module turns those events into a small
|
||||
* immutable state object and answers the UI questions that depend on it:
|
||||
* what dismissing the modal should do, what the minimized pill should say, and
|
||||
* how to rebuild the view from GET /prompt_manager/scan/status after a reload.
|
||||
*
|
||||
* Loadable in the browser (window.ScanProgress) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const IDLE = "idle";
|
||||
const RUNNING = "running";
|
||||
const DONE = "done";
|
||||
const FAILED = "failed";
|
||||
|
||||
function initialState() {
|
||||
return {
|
||||
status: IDLE,
|
||||
progress: 0,
|
||||
statusText: "",
|
||||
processed: 0,
|
||||
found: 0,
|
||||
added: 0,
|
||||
linked: 0,
|
||||
message: "",
|
||||
};
|
||||
}
|
||||
|
||||
function num(value, fallback) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function text(value, fallback) {
|
||||
return typeof value === "string" ? value : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} state current state (never mutated)
|
||||
* @param {object} event a decoded SSE payload: {type: "progress"|"complete"|"error", ...}
|
||||
* @returns {object} the next state, or `state` itself when the event changes nothing
|
||||
*/
|
||||
function reduceScanEvent(state, event) {
|
||||
if (!event || typeof event !== "object") return state;
|
||||
if (event.type === "progress") {
|
||||
return {
|
||||
...state,
|
||||
status: RUNNING,
|
||||
progress: num(event.progress, state.progress),
|
||||
statusText: text(event.status, state.statusText),
|
||||
processed: num(event.processed, state.processed),
|
||||
found: num(event.found, state.found),
|
||||
};
|
||||
}
|
||||
if (event.type === "complete" || event.type === "cancelled") {
|
||||
const counts = Object.fromEntries(
|
||||
['pairs_added','pair_links_added','enriched','unchanged','ambiguous','unresolved','conflict','failed']
|
||||
.map(key => [key, num(event[key], state[key] || 0)])
|
||||
);
|
||||
return {
|
||||
...state,
|
||||
...counts,
|
||||
status: DONE,
|
||||
cancelled: event.type === "cancelled",
|
||||
progress: event.type === "cancelled" ? state.progress : 100,
|
||||
statusText: event.type === "cancelled" ? "Scan cancelled." : "Scan completed!",
|
||||
processed: num(event.processed, state.processed),
|
||||
found: num(event.found, state.found),
|
||||
added: num(event.added, state.added),
|
||||
linked: num(event.linked, state.linked),
|
||||
};
|
||||
}
|
||||
if (event.type === "error") {
|
||||
return { ...state, status: FAILED, message: text(event.message, "Scan failed") };
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Rebuild the state from the /prompt_manager/scan/status payload. */
|
||||
function fromStatus(status) {
|
||||
if (!status || !status.running) return initialState();
|
||||
const state = reduceScanEvent(initialState(), status.last_event);
|
||||
if (state.status !== IDLE) return state;
|
||||
return { ...state, status: RUNNING, statusText: "Scanning..." };
|
||||
}
|
||||
|
||||
/** Closing a running scan's modal only hides it; the scan continues. */
|
||||
function dismissAction(state) {
|
||||
return state && state.status === RUNNING ? "minimize" : "close";
|
||||
}
|
||||
|
||||
/** Label for the minimized progress pill; empty when nothing is running. */
|
||||
function progressLabel(state) {
|
||||
if (!state || state.status !== RUNNING) return "";
|
||||
const pct = Math.round(state.progress);
|
||||
return `Scanning ${pct}% · ${state.processed} files · ${state.found} prompts`;
|
||||
}
|
||||
|
||||
function completionLabel(state) {
|
||||
const review = (state.ambiguous || 0) + (state.unresolved || 0) + (state.conflict || 0);
|
||||
return `${state.cancelled ? 'Scan cancelled' : 'Scan completed'}! Processed ${state.processed} files, found ${state.found} prompts; ${state.added} new image records, ${state.linked} links, ${state.enriched || 0} enriched, ${state.unchanged || 0} unchanged; ${state.pairs_added || 0} new pairs, ${state.pair_links_added || 0} pair links; ${review} need review, ${state.failed || 0} failed.`;
|
||||
}
|
||||
|
||||
const api = {
|
||||
initialState,
|
||||
completionLabel,
|
||||
reduceScanEvent,
|
||||
fromStatus,
|
||||
dismissAction,
|
||||
progressLabel,
|
||||
IDLE,
|
||||
RUNNING,
|
||||
DONE,
|
||||
FAILED,
|
||||
};
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.ScanProgress = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* Server-sent events over fetch.
|
||||
*
|
||||
* EventSource can only GET. The auto-tag download/start and thumbnail
|
||||
* generation endpoints are POST (they have side effects), so their progress
|
||||
* streams are read with fetch and a small parser. `connect()` returns an
|
||||
* object with the EventSource surface the pages already use: onmessage,
|
||||
* onerror, onclose, readyState, close(), and addEventListener(name, fn) for
|
||||
* named `event:` frames.
|
||||
*
|
||||
* Loadable in the browser (window.SseStream) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const CONNECTING = 0;
|
||||
const OPEN = 1;
|
||||
const CLOSED = 2;
|
||||
|
||||
/**
|
||||
* Parse complete events out of a buffer of SSE text.
|
||||
* @param {string} buffer
|
||||
* @returns {{events: Array<{data: string, event?: string}>, rest: string}} parsed
|
||||
* events and the trailing, still incomplete block
|
||||
*/
|
||||
function parseSseChunk(buffer) {
|
||||
const normalized = buffer.replace(/\r\n/g, "\n");
|
||||
const blocks = normalized.split("\n\n");
|
||||
const rest = blocks.pop();
|
||||
const events = [];
|
||||
for (const block of blocks) {
|
||||
const event = parseBlock(block);
|
||||
if (event) events.push(event);
|
||||
}
|
||||
return { events, rest };
|
||||
}
|
||||
|
||||
function parseBlock(block) {
|
||||
const data = [];
|
||||
let name;
|
||||
for (const line of block.split("\n")) {
|
||||
if (line === "" || line.startsWith(":")) continue;
|
||||
const colon = line.indexOf(":");
|
||||
const field = colon === -1 ? line : line.slice(0, colon);
|
||||
let value = colon === -1 ? "" : line.slice(colon + 1);
|
||||
if (value.startsWith(" ")) value = value.slice(1);
|
||||
if (field === "data") data.push(value);
|
||||
else if (field === "event") name = value;
|
||||
}
|
||||
if (data.length === 0) return null;
|
||||
const event = { data: data.join("\n") };
|
||||
if (name !== undefined) event.event = name;
|
||||
return event;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {{method?: string, body?: string|FormData, fetchImpl?: typeof fetch}} [options]
|
||||
* @returns {{onmessage: Function|null, onerror: Function|null, onclose: Function|null,
|
||||
* readyState: number, close: Function, CONNECTING: number, OPEN: number, CLOSED: number}}
|
||||
*/
|
||||
// A non-2xx answer as an Error carrying its status and, when the body is
|
||||
// the API's JSON {error}, that sentence as serverMessage for the page.
|
||||
async function httpError(response) {
|
||||
const error = new Error(`HTTP ${response.status}`);
|
||||
error.status = response.status;
|
||||
try {
|
||||
const data = await response.json();
|
||||
if (data && typeof data.error === "string" && data.error) error.serverMessage = data.error;
|
||||
} catch (_) {
|
||||
// Not JSON: the status alone.
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
function connect(url, { method = "GET", body, fetchImpl } = {}) {
|
||||
const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
|
||||
const controller = new AbortController();
|
||||
const listeners = new Map();
|
||||
const source = {
|
||||
onmessage: null,
|
||||
onerror: null,
|
||||
onclose: null,
|
||||
readyState: CONNECTING,
|
||||
CONNECTING,
|
||||
OPEN,
|
||||
CLOSED,
|
||||
close() {
|
||||
if (source.readyState === CLOSED) return;
|
||||
source.readyState = CLOSED;
|
||||
controller.abort();
|
||||
},
|
||||
/** Named `event:` frames reach listeners for that name; unnamed ones reach "message". */
|
||||
addEventListener(name, listener) {
|
||||
if (!listeners.has(name)) listeners.set(name, new Set());
|
||||
listeners.get(name).add(listener);
|
||||
},
|
||||
removeEventListener(name, listener) {
|
||||
const set = listeners.get(name);
|
||||
if (set) set.delete(listener);
|
||||
},
|
||||
};
|
||||
|
||||
function deliver(event) {
|
||||
if (source.onmessage) source.onmessage(event);
|
||||
const set = listeners.get(event.event || "message");
|
||||
if (!set) return;
|
||||
for (const listener of Array.from(set)) {
|
||||
if (source.readyState === CLOSED) return;
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const init = { method, headers: { Accept: "text/event-stream" }, signal: controller.signal };
|
||||
if (body !== undefined) init.body = body;
|
||||
const requestUrl = root.ApiClient ? root.ApiClient.resolveUrl(url) : url;
|
||||
const response = await doFetch(requestUrl, init);
|
||||
if (!response.ok) throw await httpError(response);
|
||||
if (source.readyState === CLOSED) return;
|
||||
source.readyState = OPEN;
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (source.readyState === CLOSED) return;
|
||||
buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
|
||||
const { events, rest } = parseSseChunk(buffer);
|
||||
buffer = rest;
|
||||
for (const event of events) {
|
||||
if (source.readyState === CLOSED) return;
|
||||
deliver(event);
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
source.readyState = CLOSED;
|
||||
if (source.onclose) source.onclose();
|
||||
} catch (error) {
|
||||
if (source.readyState === CLOSED) return; // closed by the caller
|
||||
source.readyState = CLOSED;
|
||||
if (source.onerror) source.onerror(error);
|
||||
}
|
||||
})();
|
||||
|
||||
return source;
|
||||
}
|
||||
|
||||
const api = { parseSseChunk, connect, CONNECTING, OPEN, CLOSED };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.SseStream = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* Tag autocomplete for comma-separated tag inputs.
|
||||
*
|
||||
* The text before the last comma is the committed context; the text after it
|
||||
* is the tag being typed. Suggestions come from
|
||||
* GET /prompt_manager/tags/suggest, which offers only tags that co-occur with
|
||||
* every committed tag, so "asian, " narrows to tags seen together with asian.
|
||||
*
|
||||
* Loadable in the browser (window.TagAutocomplete) and in Node for tests.
|
||||
*/
|
||||
(function (root) {
|
||||
"use strict";
|
||||
|
||||
const SUGGEST_URL = "/prompt_manager/tags/suggest";
|
||||
const DEFAULT_LIMIT = 15;
|
||||
|
||||
/** @returns {{committed: string[], current: string}} */
|
||||
function splitTagInput(value) {
|
||||
const parts = String(value == null ? "" : value).split(",");
|
||||
const current = parts.pop().trim();
|
||||
const committed = [];
|
||||
const seen = new Set();
|
||||
for (const part of parts) {
|
||||
const tag = part.trim();
|
||||
if (!tag) continue;
|
||||
const key = tag.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
committed.push(tag);
|
||||
}
|
||||
return { committed, current };
|
||||
}
|
||||
|
||||
/** Replace the tag being typed with `tag`; the result ends with ", " for the next one. */
|
||||
function applySuggestion(value, tag) {
|
||||
const { committed } = splitTagInput(value);
|
||||
const known = new Set(committed.map((t) => t.toLowerCase()));
|
||||
const tags = known.has(tag.toLowerCase()) ? committed : committed.concat([tag]);
|
||||
return tags.join(", ") + ", ";
|
||||
}
|
||||
|
||||
function suggestUrl(value, limit = DEFAULT_LIMIT) {
|
||||
const { committed, current } = splitTagInput(value);
|
||||
const params = new URLSearchParams();
|
||||
params.set("q", current);
|
||||
params.set("with", committed.join(","));
|
||||
params.set("limit", String(limit));
|
||||
return `${SUGGEST_URL}?${params.toString()}`;
|
||||
}
|
||||
|
||||
/** Keyboard navigation: -1 means nothing selected; wraps at both ends. */
|
||||
function moveSelection(index, delta, count) {
|
||||
if (!count || count <= 0) return -1;
|
||||
if (index < 0) return delta > 0 ? 0 : count - 1;
|
||||
return (((index + delta) % count) + count) % count;
|
||||
}
|
||||
|
||||
const api = { splitTagInput, applySuggestion, suggestUrl, moveSelection, SUGGEST_URL, DEFAULT_LIMIT };
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.TagAutocomplete = api;
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
-1146
File diff suppressed because it is too large
Load Diff
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* Theme Bridge — Detects ComfyUI palette and applies body-level styling.
|
||||
*
|
||||
* When running inside ComfyUI, the parent page already injects palette CSS
|
||||
* variables so our --pm-* tokens auto-resolve. This script adds a data
|
||||
* attribute for CSS selectors that need to distinguish light vs dark.
|
||||
*
|
||||
* When running standalone (direct URL), we fall back to dark defaults.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const LIGHT_PALETTES = ['light', 'solarized', 'github', 'arc'];
|
||||
|
||||
async function detectPalette() {
|
||||
try {
|
||||
const prefix = window.location.pathname.match(/^(.*)\/prompt_manager(?:\/|$)/)?.[1] || '';
|
||||
const res = await fetch(`${prefix}/api/settings/Comfy.ColorPalette`);
|
||||
if (!res.ok) return 'dark';
|
||||
const data = await res.json();
|
||||
// data is the palette name string, or an object with value
|
||||
const name = (typeof data === 'string' ? data : data?.value || 'dark').toLowerCase();
|
||||
return name;
|
||||
} catch {
|
||||
// Standalone mode — no ComfyUI API available
|
||||
return 'dark';
|
||||
}
|
||||
}
|
||||
|
||||
function applyPalette(name) {
|
||||
const isLight = LIGHT_PALETTES.some(p => name.includes(p));
|
||||
document.documentElement.setAttribute('data-pm-theme', isLight ? 'light' : 'dark');
|
||||
}
|
||||
|
||||
// Run immediately — script is loaded in <head> so body isn't parsed yet.
|
||||
// We set the attribute as soon as possible to prevent flash.
|
||||
document.documentElement.setAttribute('data-pm-theme', 'dark');
|
||||
detectPalette().then(applyPalette);
|
||||
})();
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user