Compare commits

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

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

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

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

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

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

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

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

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

* docs: tag cleanup (#618)

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

* Fix subfolders API missing include_ancestors param

* refactor: move api code into promptmanager_core package

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

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

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

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

* Close test databases before unlinking temp files

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

* Ignore local tracking state and prebackfill database backup

* style: restore black formatting after 3.6.0 merge

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

No behaviour change.

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The address now stays #/library?tag=a&tag=b&tag_mode=any|untagged, in one
canonical spelling. It is the truth for Tags and Tag match: Reload, Back and
Forward restore the filter, a change in Refine replaces the address without
a history entry, and #/library (the sidebar link, the old dashboard URL)
always means no tag filter. Search, category, folder, sort and the archived
shelf stay out of the address. The way back from a prompt's page and Browse
on Tags & categories go to the filtered address. A saved view keeps its own
address.
2026-11-21 12:50:35 -08:00
Vito 6375be1a92 chore: release 3.7.2 (#661) 2026-11-21 09:49:30 -08:00
Vito 6f02277a1c fix: small cleanup from the audit true-up (#662) (#665)
* refactor(api): one bounded JSON body reader for the API and images.py (#662)

images.py kept its own copy of the chunked, capped JSON object reader.
Both now use py/api/json_body.py; images.py keeps its 1 MiB cap and its
raising form for the thumbnail job.

* fix(api): refuse malformed bodies on the legacy prompt routes with a 400 (#662)

PUT /prompts/{id}, PUT /prompts/{id}/rating, POST and DELETE
/prompts/{id}/tags, POST /prompts/tags, PUT /tags/{tag}, POST /tags/merge
and POST /bulk/delete|tags|category read the body with the bounded JSON
reader /save uses and check field types, so a body that is not a JSON
object, or a field such as {"text": 123}, is a 400 instead of a 500.
A prompt id may still be a number or its text, as the legacy page sends
it; a boolean is refused (prompt_ids [true] deleted prompt 1).
POST /jobs/image-tags refuses a mode that is no text instead of a 500.

* refactor(inspect): both resolvers read PROVEN_VALUE_CATEGORIES (#662)

proves_value hard-coded the four tables in Python and in the browser.
Semantics.proves_value now reads the constant (class-keyed categories by
class, the rest by output slot), the browser resolver loops over its
mirrored copy in local-resolver-support.mjs, and
tests/test_proven_value_parity.py fails when that copy drifts. A test
patches the constant to show the resolver follows it.

* refactor: remove the write-only preview batch count and the test-only node search (#662)

AutoThumbnailWorker set self._batch in four places and never read it.
PromptManagerBase._search_prompts had no caller but its own tests: the
node UIs search through GET /prompt_manager/search. Prompt search itself
stays covered by the database and route tests.

* fix(tools): open libraries through the shared read-only URI helper (#662)

review_image_links, repair_foreign_links (twice) and workflow_text_digests
built their own file: URIs, which SQLite refuses for a library on a
Windows network share (file://server/share/...). They now use
database/sqlite_uri.readonly_uri; repair_foreign_links opens its own
read-write backup by path. The guard in tests/test_sqlite_uri.py scans
tools/ too and also catches a conditional ?mode=ro suffix.

* ci: bound the publish and Viewer.js update jobs by measured limits (#662)

publish.yml and viewerjs-update.yml had no timeout-minutes, and the
workflow guard listed only four workflows. The guard now reads every
workflow and recomputes both new limits from their comments: publish
5 min from its last three green runs; the Viewer.js update 18 min, from
an estimate of its never-run update path (the three measured nightly
runs found no release and give the 5-minute floor).

* docs: correct the redesign plan's CI and PR rules, renumber the second D205 (#662)

docs/application-redesign.md named a Python 3.10-3.13 matrix with macOS,
asked for PR screenshots and said Overview links the legacy metadata
page. It now names the 3.12 floor and the current Linux/Windows split,
asks for visual changes in words, and says the metadata page is reached
by address or from the legacy admin page. TESTING.md used D205 for both
#431 (saved instructions) and #620 (Library sorts); #620's entry is
D206 now.
2026-11-21 09:46:31 -08:00
Vito 8aad090c09 test(send): wait for discovery's chosen node instead of expecting Apply disabled (#663) (#664) 2026-11-21 08:41:05 -08:00
Vito 3d32e9183a ci: one single-pass gate on the pull request, the rest nightly (#666) (#667)
* ci: one single-pass gate on the pull request, the rest nightly (#666)

A change was tested twice: on the pull request and again in the merge
queue, which added Firefox, WebKit, Python 3.13/3.14 and real ComfyUI.
Of the last 50 queue entries 9 failed, none because of the change.

- ci.yml is the gate, on pull_request and workflow_dispatch only: the
  Python 3.12 suite once under the 85% coverage gate, black/flake8,
  bandit, frontend modules, tooling tests and pins, desktop Chromium
  page workflows with frontend coverage, and one required context,
  gate, that fails unless every job did what the change class asks.
- nightly.yml runs Firefox, WebKit, touch, Python 3.13/3.14, Windows,
  native trash, real ComfyUI and the perf budget, and reports by issue:
  one per failing job, closed by the next green run.
- No workflow has a merge_group trigger; a push to main starts only
  publish.yml, which now has a time limit.
- Change classes: docs and inert run only the classifier and gate; a
  release (only the version line of pyproject.toml) runs the
  package-content check; everything else runs the gate.
- @quarantine: left out of the gate, still run nightly. No retries in
  the gate; nightly retries once and lists flaky tests in the summary.
- Frontend coverage is measured with Chromium alone; every floor holds.
- branch-protection.json requires gate, strict.

test.yml, viewerjs-check.yml, portability.yml and code-quality.yml are
deleted.

* style(ci): make the nightly report's joined sentence one explicit item (#666)
2026-11-21 08:31:13 -08:00
Vito a1f744708e fix: resolve rgthree Any Switch, show shared roles, choose ambiguous prompts in Inspect (#660)
* test(inspect): use a neutral unknown class in the pass-through fixtures

The #381 fixtures used rgthree's Any Switch as their example of an unknown
node. The table is about to describe that class (#657), so the stand-in
becomes PMTest Unknown Multi and any_switch_graph becomes
unknown_multi_graph. Resolver results are unchanged.

* feat(inspect): resolve rgthree Any Switch by its first proven input (#657)

rgthree's Any Switch outputs the first any_* input that is not None. The
inspection resolver treated it as an unknown node, so the model-compare
sweep (PromptManagerText into any_01, the same text joined after a LoRA
trigger into any_02) was ambiguous in Inspect.

The table gains a first-present selector strategy and lists the switch
under it. The resolver takes the first participating input when it is a
literal or its traced path proves a value (every node is a PromptManager,
code-traced, default-adapter or encoders/strings/conditioning/composites
class). Otherwise each input is one choice, unless all of them trace to
one text; limits and upstream divergences propagate, and no PromptManager
path is preferred. A missing or null input does not take part. The
browser resolver and its table compiler follow the same rules, with the
same strict entry check as the server.

Only graphs holding the class change their class projection, so only
their pending inspection items move; INSPECTION_RESOLVER_VERSION stays 2.

* fix(inspect): list a repeated Any Switch outcome once (#657)

A switch with three or more inputs can offer one text through two of
them (a, b, a). Each input was its own candidate, so one text read as a
choice between two, and two equal resolved candidates beside a failed
one would count as reviewable. Like an unknown node passing several
texts, a first-present divergence now collapses equal outcomes. The
browser resolver does the same. The table compiler test also checks the
128-character prefix bound in code points, as Python counts it.

* feat(inspect): show a role every candidate shares (#658)

An ambiguous file used to withhold both roles, even when every candidate
had the same negative. Inspect now judges each role on its own: a role is
shown resolved when every candidate is resolved with the same text,
stored recipe and left-out parts for it, using the first candidate's
text and source. A role that differs, or any unresolved candidate, keeps
the ambiguous line, and resolution.state stays ambiguous, so Send pair,
ingestion and Needs review behave as before. The browser-local resolver
applies the same rule; the footer Send to ComfyUI still needs both roles.

A multistage detailer run whose stages share one negative (fixture f19)
now shows that negative.

* feat(monitor): ask the ladder for PromptManager runs nothing else links

A PromptManager output whose metadata and tracked run cannot name its
prompt now takes the ladder path foreign outputs use: decided at settle
under the monitor policy, or after its run is sealed through the ladder
wait. Wait entries carry their run kind; the kind selects the settings
gate (SAVE_FOREIGN_RUNS for foreign entries, MONITORING_ENABLED for
PromptManager ones) and the marks of a created prompt. Keyless images,
placeholder batch entries and unreadable metadata never enter the wait.
Every final unlinked outcome hands the file to the review recorder.

Refs #659

* test(monitor): pin the final unlinked outcomes that reach Needs review

The sweep, joined-text and shared-prefix graphs move to a shared fixture
module. New tests pin when the monitor hands a file to its review
recorder: after the sealed re-check, a settle lookup that found the run's
record, a file outside ComfyUI's output folder and the keyless
re-check; never before the run is sealed, and never for a linked file.
A PromptManager output waiting for its run now logs that at INFO.

Refs #659

* feat(review): offer inspection choices for default-unresolved files

Decision.default_unresolved marks a file the default profile itself
calls unresolved (a blank positive does not count). With inspection on,
record_ambiguous_file now sends such a captured file with a prompt graph
straight to the inspection-profile branch: a reviewable ambiguous or
saver-anchored result is recorded, anything else is untraced. Apply is
unchanged; it re-resolves with the item's recorded profile.

Refs #659

* feat(review): one review dispatch and a review worker for monitor outputs

review_dispatch holds the scan's per-file Needs review decision and is
now also used by the monitor. The scan replaces its inline dispatch with
it (and offers default-unresolved files their inspection choices).

record_review_file runs the scan's per-file steps for one file, read
only: the scan-policy ladder with the sealed history and the recorded-run
check. A file the scan would link is skipped; otherwise the dispatch's
record outcome is the answer. The monitor queues paths through
queue_review_file onto one daemon worker (pm-review-recorder) with a
bounded queue that coalesces by path and a bounded deferred set it
replays once no job blocker remains. The package teardown stops it
right after the monitor and reports it as part review once started.

Refs #659

* docs(testing): the monitor queues what the scan would (#659)

Rewrite the Needs review paragraph for the 2026-11-19 decision: the
final-outcome points, the review worker and its bounds, the deferred
replay and the default-unresolved rule. Document the PromptManager-run
ladder path, the review step of the package teardown and the proven-value
allowlist every future semantics table entry must keep.

Refs #659

* fix(review): lock the untraced memory the scan and review worker share

Refs #659

* feat(inspect): name the file's Needs review item in the inspection responses

Inspect and the run-history current-file inspection gain a review field:
{"state": "pending", "item_id": ...} for the newest pending item at the
stat the inspection took, {"state": "decided"} once its item was decided,
and null otherwise. It is read only when a role is ambiguous and the file
is unlinked, by locator and stat (review_item_at), so Inspect never hashes
the file. A LoRA root, a failed read and any malformed value give null.

Refs #659

* feat(review): a single-item mode for the review controller and a shared option list

createReviewController({api, itemId}) holds one named item: it never reads
the queue, loads that item's detail, ends in phase decided (decided: true)
after a recorded decision or for an item already decided, and re-reads the
detail after a review-conflict, review-missing or restore refusal. The queue
mode is unchanged.

The Sampler context option list moves into renderReviewOptions
(review-options.mjs, re-exported by review.mjs), so Needs review and the
Inspect picker render the same options without Inspect importing the Needs
review page.

Refs #659

* feat(inspect): choose the prompt of an ambiguous file in Inspect

When the inspection names the file's pending Needs review item, the
inspector shows a Choose prompt section after its prompt blocks (Images
panel, viewer details, recorded run current file). It reads the item's
detail through the review controller's single-item mode: one Sampler
context option per candidate (unusable ones disabled with their reason),
the chosen option's prompt blocks with Copy and Send, Use this prompt and
Leave unresolved over the Needs review apply flow. A recorded decision
shows Needs review's toast and re-reads the inspection, so the file shows
its link; an item with nothing to choose offers Open in Needs review.

Refs #659

* fix(inspect): read the history review item only when Inspect asks

The run-history reader locates the file under the scan roots inside the
read, so an unambiguous or linked file costs no realpath of the output
folders. The docstring names the linked-subfolder limit, and the newest
pending item test pins the rowid tie-break.

Refs #659

* fix(inspect): end Choose prompt on another read and on a decision made elsewhere

The inspector disposes the section when it reads another file, fails or
defers, so a decision in flight never re-reads the next file. A decided
item hides the section and re-reads the inspection once, also when it was
decided in another tab or in Needs review.

Refs #659

* test(inspect): the rooted inspect shape gains the review facet

Refs #659

* docs(testing): first-present candidates and per-role results (#657, #658)

* test(review): keep the review cases ambiguous now that Any Switch resolves

Part 1 resolves rgthree's Any Switch, so the sweep fixture links. The
review and monitor tests that need a default-unresolved,
inspection-ambiguous file now use ambiguous_sweep_graph(): Part A's
any_switch_sweep_graph() with its switch class replaced by the
never-listed PMTest Unknown Multi (one sweep graph instead of two). A new
test pins that the real sweep links at settle from the inspector.

Refs #657 #659

* fix(review): start the review worker again after an unexpected error

* fix(inspect): pass the inspection refresh to Choose prompt by reference

* feat(review): queue an ambiguous file with one readable choice (#657)

An ambiguous result is reviewable when at least one candidate carries a
resolved prompt (MIN_CHOOSABLE = 1). The sweep with an LLM enhancer on
Any Switch any_01 now records an item, by the scan and the monitor, with
the run-time branch listed beside the readable one. A file with no
choosable candidate still records nothing.

* feat(review): collapse too many candidates into the most used prompts (#657)

More than 16 distinct candidates no longer make a limited item without
choices. The choosable ones are grouped by their positive and negative
texts, ordered by group size then first appearance, and the first 16
are kept, one real candidate each. The evidence names
collapsed: {shown, total, paths} and the item detail returns it.
Limited stays for evidence that cannot be projected or is over 8 MiB.

REVIEW_EVIDENCE_VERSION is folded into every item version (default items
now carry RESOLVER_VERSION + 1, inspection items fold it into their
seed), so the next scan supersedes pending, undecided items of the old
shape; decided items are kept. RESOLVER_VERSION, the ingestion's
provenance version, is unchanged.

* feat(inspect): record the Needs review item when Inspect finds none (#657)

When Inspect asks for the review facet (an ambiguous role, an unlinked
file under an output root) and no item exists at the inspected stat, the
images and History current-file inspections run record_review_file, the
review worker's own per-file path, in the executor and read the item
again. A file the scan would link or that offers nothing to choose
records nothing; a deferred or failed recording leaves review null and
a failure is logged, never failing the response.

* docs(testing): one readable choice, collapsed candidates, Inspect records (#657)

* feat(review): say when a file's prompts were shortened to the most used (#657)

The item detail now passes the stored evidence's optional `collapsed`
counts ({shown, total, paths}) through to the page, null when absent,
malformed, or when the detail was capped for size. Needs review and
Inspect's Choose prompt show one line under Sampler context:
"Showing the n most used of t prompts in this file."

* feat(review): list the image's own prompts first in Link to a prompt (#657)

With an empty search the dialog now lists the item's choosable
candidates under "From this image" (positive / negative, one per prompt
pair), then the Library's prompts under "Library". Choosing one of the
image's prompts and pressing Link image applies that candidate by its
hash, the same decision as Apply association (new
controller.applyCandidate); no negative is asked for, the candidate
carries its own. Typing searches the Library only. Items with no
choosable candidate show the dialog as before. A refusal stays in the
dialog with the server's sentence.

* feat(review): load more of the queue on scroll (#657)

The Needs review continuation now works like the Images page: an
IntersectionObserver (250 px ahead) loads the next page when the end of
the queue scrolls into view, and the line reads "40 of 45 images · more
load as you scroll" without a button. Nothing loads behind an open
dialog or the viewer; when one closes, focus returning to the page
checks again. A failed page shows the failure line and a Retry button.
Without IntersectionObserver the Load more images button stays.

* fix(review): ask the inspection profile when the default choice is partial (#657)

With one readable choice enough, a default result with one choice beside
unresolved branches was recorded as is, so the inspection profile, which
may read those branches (a Qwen image-edit sampler), was never asked and a
rescan replaced older inspection items with the poorer default ones. Such a
partial result now yields to the inspection result when that offers more
choosable candidates.

* fix(review): collapse only too many prompts, and apply any offered one (#657)

Collapsing triggered on more than 16 distinct candidates, sampler ids
included, so twenty samplers sharing three texts lost their run-time
branches behind a collapsed note. Now only more than 16 choosable texts
collapse; otherwise one candidate per text is kept and the branches
without a prompt fill the remaining places, as an ordinary item.

Apply's still-offered check compared the chosen hash with a fresh
collapse, so a reorder that changed the representatives refused Apply.
It now checks every projected, de-duplicated candidate hash
(candidate_hashes).

* fix(inspect): keep Inspect's recording quiet, bounded and current (#657)

A busy capture store (the worker copying a fresh output) is an expected
outcome: Inspect logs it at debug level and reads the item once more,
also after a failed recording. A file Inspect found unrecordable (the
scan would link it, or it offers nothing to choose) is remembered by its
locator, stat and review versions, at most 4,096 files, so a repeated
Inspect does not copy it again. A pending item of an older item version
is recorded again, so the current record supersedes it.

* docs(testing): partial default choices, bounded candidates, Inspect recording (#657)

* fix(review): Link to a prompt drops an image choice it no longer shows (#657)

Typing in the search box hid the "From this image" list but kept its
chosen prompt, so Link image applied a candidate the reviewer could no
longer see. Typing now drops that choice; Link image waits for a Library
prompt and sends a Library link. Emptying the box lists the image's
prompts again, none chosen.

When the item's detail is read again while the dialog is open, the list
follows what it offers now; a chosen prompt no longer offered is dropped
with "This prompt is no longer offered for this file. Choose again."
applyCandidate says the same when the hash cannot be chosen, and an
unanswered apply from the dialog asks to press Link image again.

* fix(review): keep the panel in place when Info brings it into view at one column (#657)

At one column, Info scrolls the panel into view past the queue, which
could bring the continuation into view and load the next page, pushing
the panel away. As on the Images page, loading now waits for the
reader's next wheel, touch move or key press.

* docs(review): say why the review worker's recorder is a lambda

* test(review): open the dialog of the D5 dialog test beside the queue (#657)

At one column (touch) the review panel follows the queue just above the
continuation, so scrolling Link to a prompt… into view brings the
continuation within the observer's 250 px margin. The next page then
loads before the dialog opens whenever the observer's callback runs
first (CI shard 4/4, touch), and the test found no continuation to
scroll to. That load is the page working as designed: the reader has
reached the end of the queue.

The test is about loading behind an open dialog, so it now runs at two
columns, where Link sits in the sticky panel beside the queue, and it
checks that the continuation is out of range before the dialog opens.
2026-11-21 03:07:38 +00:00
Vito b3bb55f2dc chore: release 3.7.1 (#655) 2026-11-19 14:26:54 +00:00
LacklusterOpsec fa31644c4c fix(node): give prepend_text and append_text their empty default (#651)
Both inputs are optional STRINGs that the node already treats as empty
(`encode_prompt` defaults them to ""), but INPUT_TYPES left "default"
out, so `/object_info` and the v3 schema answer null for them while
category, tags and search_text answer "". PromptManagerFocused already
forces "default": "" on the same two inputs, so the plain node was the
only one without it; Focused, Split and Pair inherit the fix.

The test asserts every optional STRING of PromptManager starts empty.
2026-11-19 11:35:37 +00:00
Vito 0c023c7ec9 test(inspect): wait for the held video's revoke instead of checking once (#653) (#654)
On WebKit a replaced video that is still starting, inline or in the
viewer the selection opened, keeps its URL until it settles or 15 s
pass. The test checked the revoke once, right after the new preview
showed, so it failed when the viewer's video settled later.
2026-11-19 11:35:36 +00:00
LacklusterOpsecandVito Sansevero 9943a61619 fix(images): link WebP images to their prompts (#650)
* fix(images): link WebP and AVIF images to their prompts

ComfyUI writes the workflow and the prompt into PNG text chunks, and the
library read only those. SaveAnimatedWEBP writes the same records as EXIF
instead: `prompt:{json}` at tag 0x0110, then `workflow:{json}` and every
other `extra_pnginfo` key from 0x010F down; the AVIF writer uses that
layout. Pillow answers them only through `getexif()`, so an animated WebP
or an AVIF scanned into the library matched no prompt and stayed unlinked.

`utils/exif_text.py` answers the `png_text` shape from those tags, and
both metadata readers (the scan's `_extract_comfyui_metadata` and the
monitor's `extract_metadata`) ask it when a file has no text chunks. Only a
value shaped like a record counts, so camera EXIF stays out. PNG is
unchanged: its records are text chunks and `exif_text` answers `{}`.

The tests write real still and animated WebP, AVIF (where Pillow has it) and
JPEG files in ComfyUI's layout, and hold both readers to them.

* docs(images): AVIF is read but not yet collected (#652)

The EXIF reader handles ComfyUI's AVIF files, verified against files
written by ComfyUI's own _save_avif. No scan, monitor or gallery list
collects .avif yet, so say so and point at #652.

---------

Co-authored-by: Vito Sansevero <vito.sansevero@gmail.com>
2026-11-19 01:00:17 +00:00
Vito 1d509c885e chore: release 3.7.0 (refuse permanent delete off Linux/BSD, #644) (#645)
* fix(images): refuse permanent delete where the review does not offer it (#644)

The apply accepted mode "permanent" on every OS; only the workspace hid
the option. A direct call on Windows or macOS unlinked files although the
README says Windows can only remove images from the library. The apply now
answers 400 unless the Freedesktop trash backend is in use, before any
backup or file change. The review and the apply share one check.

The README describes the new option and its limit.

* chore: release 3.7.0
2026-11-17 22:02:44 +00:00
251 changed files with 13322 additions and 16100 deletions
-1
View File
@@ -13,7 +13,6 @@
# Development files
/TESTING.md
/Makefile
/requirements-dev.txt
/.coveragerc
/.flake8
+2 -9
View File
@@ -1,15 +1,8 @@
{
"required_status_checks": {
"strict": false,
"strict": true,
"contexts": [
"py3.12 on ubuntu-latest",
"coverage gate (85%)",
"black and flake8",
"frontend modules",
"all tests",
"viewerjs",
"real ComfyUI compatibility",
"bandit (high severity)"
"gate"
]
},
"enforce_admins": true,
@@ -1,58 +1,58 @@
name: Viewer.js vendor and compatibility
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
name: CI
permissions:
contents: read
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
# The gate (#666): everything a change must pass runs once, here, on the pull request. Nothing runs
# again in a merge queue or on main; branch protection requires the one context "gate" on a branch
# that is up to date with main, so the commit that was tested is the commit that merges. What only
# other browsers, other Pythons, Windows or a real ComfyUI can catch runs in nightly.yml.
on:
pull_request:
branches: [main]
workflow_dispatch:
# A newer push to a pull request cancels the older run. A manual run is never cancelled.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Timeouts are the measured job time plus at least 50%, and never under 20 minutes for a browser job,
# because runner speed varies. Before sharding (main 2cecfcf, one worker): frontend coverage 32m10s,
# page workflows firefox 18m59s, webkit 19m26s. First sharded run (PR #274 run 39712909047, 3 workers,
# no npm cache, where npm ci stalled for 5m in six of eight jobs): coverage shards 11m19s/10m47s/10m49s
# (tests 5m20s/4m42s/4m46s), merge 5m52s (report and check 4s), firefox shards 7m53s/9m27s (tests
# 4m41s/3m29s), webkit shards 12m25s+ (cancelled at the old 12-minute limit after its 267 tests passed in
# 6m29s) and 4m53s (tests 3m08s). With the npm cache hit (run 39725176320 at cbc8a61, npm ci 0-2s):
# coverage shards 7m34s/6m04s/5m22s (tests 6m38s/4m53s/4m04s), merge 54s, firefox 7m57s/5m21s (tests
# 7m08s/4m34s), webkit 8m16s/5m03s (tests 7m26s/3m58s); a cache miss adds up to 5m to npm ci, which
# the 20-minute limits absorb.
# Hangs (#425): a job killed at its limit keeps no log and skips its upload steps, so each browser
# test step has its own timeout-minutes (18) below the job's 20. At the step limit, SIGTERM makes
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time. The 3 minutes leave room for the Python runner's watchdog
# (120 s, tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes
# only with new measurements written here (TESTING.md "Time limits and hangs"). A job with no three
# green runs yet has an "estimate" line; replace it with its measurement after three green runs.
# tests/vendor/ci-workflow.test.mjs recomputes every limit from these lines.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python: 7m20s / 7m36s / 7m58s -> 15 min
# lint: 0m27s / 0m52s / 0m49s -> 5 min
# js-test: 0m27s / 0m35s / 0m36s -> 5 min
# changes: 0m10s / 0m06s / 0m07s -> 5 min
# Measured 2026-11-21 on runs 44861123782 (a1f7447), 44547399248 (b3bb55f), 44519472003 (fa31644):
# security: 0m22s / 0m20s / 0m24s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# frontend-coverage-merge: 0m53s / 0m57s / 0m51s -> 5 min
# gate: 0m02s / 0m06s / 0m03s -> 5 min
# estimate package: one stdlib test module without an install, under 1 minute -> 5 min
# estimate tooling: the pip and npm installs of a browser shard (about 1 minute) and 2 minutes of tests -> 8 min
# estimate frontend-coverage: the same four shards ran Chromium and touch together in 7m55s-16m48s;
# Chromium alone is about half of that, 9 minutes at most -> 17 min
#
# Browser jobs (#425): a job killed at its limit keeps no log and skips its upload steps, so the page
# test step has its own timeout-minutes, 2 below the job's. At the step limit, SIGTERM makes
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
# interrupt, which writes the blob report; the always() uploads then run.
# Measured on main (runs 40725289094, 40719375442, 40700439399): setup before the test step <= 52s,
# uploads <= 35s; test steps up to 14m42s (webkit shard 1/2) and 13m05s for coverage (shard 1/3:
# 12m53s, node units and the viewer suite before 11.8m of workflows), so coverage is the tight one
# in its 18 minutes. This holds only when the npm cache hits: a cold cache adds up to 5m to npm ci,
# and then the job limit can still end the job before the step limit does.
# #473: firefox/webkit shard 1/2 reached its 18-minute step limit (queue run 40866252975: webkit 622 tests
# passed in 17m56s, 48.5 worker-minutes vs 28.0 in shard 2/2; recent shard 1/2 jobs 13.7m-18.9m, shard 2/2
# 7.3m-12.2m), because --shard splits by test count and the slow concept specs sort into shard 1. The page
# workflows now run in three shards per browser with the limits unchanged; the per-shard times are
# re-measured after three green main runs.
# #563: coverage shards reached their 18-minute step limit three times on 2026-10-31 with no failing
# test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564
# shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the
# limits unchanged; the per-shard times are re-measured after three green main runs.
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor of test.yml).
# interrupt, which writes the blob report; the always() uploads then run. The limits assume the npm
# cache hits: a cold cache adds up to 5 minutes to npm ci.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "viewerjs" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" and "docs"
# (nothing here can break), "release" (only the version line of pyproject.toml), or "code" (anything
# else, and every case of doubt). The jobs below run for one class only, and "gate" fails unless
# this job succeeded and each job did what the class asks. The clone has every commit but no file
# contents (blob:none): the script compares file names, and reads pyproject.toml only when it is
# the one file that changed.
changes:
name: change class
runs-on: ubuntu-latest
@@ -69,15 +69,162 @@ jobs:
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
# The suite runs once, under coverage: the same run proves the tests pass and the 85% floor holds.
python:
name: python 3.12 with coverage (85%)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run the suite under coverage
run: python -m coverage run -m tests.run_suite -v
- name: Coverage gate
run: |
python -m coverage combine
python -m coverage report --fail-under=85
# A release (only the version line changed) cannot break a test, but it is what the Registry
# publishes, so the package-content rules are checked. Standard library only: nothing to install.
package:
name: package contents
needs: changes
if: ${{ needs.changes.outputs.class == 'release' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- run: python -m unittest -v tests.test_package_contents
lint:
name: black and flake8
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
security:
name: bandit (high severity)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
js-test:
name: frontend modules
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The vendor pins and the tooling tests (tests/vendor). Same image and Python as the browser shards:
# some tooling tests start the browser test server.
tooling:
name: tooling tests and pins
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 8
steps:
- uses: actions/checkout@v7
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- run: npm run --prefix tools/vendor check
- run: npm run --prefix tools/vendor test
frontend-coverage:
name: frontend coverage (shard ${{ matrix.shard }}/4)
# Code changes only (#639): no browser test reads a docs or inert file.
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
@@ -85,7 +232,7 @@ jobs:
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 20
timeout-minutes: 17
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
@@ -120,14 +267,10 @@ jobs:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Shard 1 also runs the node units and the viewer suite, so the vendor pins and the tooling tests
# run on the lightest shard instead.
- if: matrix.shard == 4
run: npm run --prefix tools/vendor check
- if: matrix.shard == 4
run: npm run --prefix tools/vendor test
# Desktop Chromium only, without tests tagged @quarantine (tools/vendor/frontend-coverage.mjs).
# Shard 1 also runs the node units and the viewer suite.
- name: Page workflows with coverage, shard ${{ matrix.shard }}/4
timeout-minutes: 18
timeout-minutes: 15
run: npm run --prefix tools/vendor test:coverage:shard -- ${{ matrix.shard }}/4
- name: Upload raw coverage
uses: actions/upload-artifact@v7
@@ -137,7 +280,7 @@ jobs:
if-no-files-found: error
retention-days: 3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload Chromium and touch traces
- name: Upload Chromium traces
if: always()
uses: actions/upload-artifact@v7
with:
@@ -147,14 +290,15 @@ jobs:
frontend-coverage-merge:
name: frontend coverage (merge)
# Runs only when every shard succeeded (the implicit success() check).
needs: [changes, frontend-coverage]
if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 10
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- run: node --version && node --version | grep -q '^v24\.'
@@ -214,97 +358,50 @@ jobs:
!coverage/js/raw/**
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Merge queue, main and manual runs only (#420); pull requests run the Chromium/touch coverage shards.
# Code changes only (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 20
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 18
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# Branch protection requires the exact context "viewerjs". This job keeps that
# name and fails unless every coverage shard and the coverage merge succeeded and
# the browser shards succeeded, or, on a pull request only, were skipped (#420).
# Any failure, cancellation or other skip fails it. For a docs or inert change (#639) all three
# must be skipped. The classifier itself must succeed, and a class it does not print fails the gate.
viewerjs:
needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows]
# The one required context. Branch protection names only "gate", so renaming or adding a job above
# never strands a pull request. It passes only when the classifier succeeded and every job did what
# the class asks: for "code" every test job succeeded and the release check was skipped; for
# "release" only the package check ran, and it succeeded; for "docs" and "inert" everything was
# skipped. A failed, cancelled or wrongly skipped job fails it, and so does a class the classifier
# does not print.
gate:
needs: [changes, python, package, lint, security, js-test, tooling, frontend-coverage, frontend-coverage-merge]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every frontend job to succeed
- name: Require every job the change class asks for
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
CHANGES_RESULT: ${{ needs.changes.result }}
PYTHON_RESULT: ${{ needs.python.result }}
PACKAGE_RESULT: ${{ needs.package.result }}
LINT_RESULT: ${{ needs.lint.result }}
SECURITY_RESULT: ${{ needs.security.result }}
JS_RESULT: ${{ needs.js-test.result }}
TOOLING_RESULT: ${{ needs.tooling.result }}
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }}
run: |
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
code) code=success; release=skipped ;;
release) code=skipped; release=success ;;
docs|inert) code=skipped; release=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_only)"
echo "frontend-coverage: $COVERAGE_RESULT"
echo "frontend-coverage-merge: $MERGE_RESULT"
echo "browser-workflows: $WORKFLOWS_RESULT"
test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only"
failed=0
require() {
echo "$1: $2 (must be $3)"
if [ "$2" != "$3" ]; then echo "::error::$1 is $2, must be $3"; failed=1; fi
}
require python "$PYTHON_RESULT" "$code"
require lint "$LINT_RESULT" "$code"
require security "$SECURITY_RESULT" "$code"
require js-test "$JS_RESULT" "$code"
require tooling "$TOOLING_RESULT" "$code"
require frontend-coverage "$COVERAGE_RESULT" "$code"
require frontend-coverage-merge "$MERGE_RESULT" "$code"
require package "$PACKAGE_RESULT" "$release"
exit "$failed"
-71
View File
@@ -1,71 +0,0 @@
name: Code Quality
permissions:
contents: read
on:
merge_group:
push:
branches: [main]
pull_request:
branches: [main]
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required context still reports. This workflow has no gate job, so the scan runs whenever the
# class is not "docs" or "inert": a classifier that fails or prints nothing means a full scan. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
security:
name: bandit (high severity)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665,
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. change class (#639): 5 min, the floor.
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python 3.12
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
+359
View File
@@ -0,0 +1,359 @@
name: Nightly
permissions:
contents: read
# Everything that is not in the gate (#666): other browsers, the phone-size project, other Pythons,
# Windows, a real mount, a real ComfyUI and the wall-clock budget. It never runs on a pull request or
# a merge and no context here is required. A failing job opens or updates one issue
# ("nightly: <job> failing"); the next green run closes it. To try a branch before it merges:
# gh workflow run nightly.yml --ref <branch> (a branch run files no issues).
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time; a matrix job takes its slowest leg. A job with no three
# green runs yet has an "estimate" line. tests/vendor/ci-workflow.test.mjs recomputes every limit.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python-linux: 6m12s / 5m14s / 5m37s -> 13 min
# comfyui: 20m21s / 20m39s / 21m06s -> 35 min
# perf-budget: 0m23s / 0m29s / 0m28s -> 5 min
# Measured 2026-11-21 on runs 44730775403 (b3bb55f), 44518136123 (9943a61), 44298521973 (1d509c8):
# python-windows: 8m04s / 8m41s / 9m27s -> 18 min
# native-trash-linux: 0m29s / 0m19s / 0m29s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# browser-workflows: 12m44s / 15m55s / 14m55s -> 27 min
# (the Firefox and WebKit legs; touch ran inside the coverage shards until #666 and has no
# measurement of its own: about half of a 7m55s-16m48s shard)
# estimate report: one script and a few API calls, under 1 minute -> 5 min
#
# Browser jobs (#425): the page test step has its own timeout-minutes, 2 below the job's, so a hang
# ends inside the step and the log, the blob report and the traces survive (see ci.yml).
jobs:
python-linux:
name: py${{ matrix.python-version }} on ubuntu-latest
runs-on: ubuntu-latest
timeout-minutes: 13
strategy:
fail-fast: false
matrix:
python-version: ["3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
run: python -m tests.run_suite -v
python-windows:
name: py${{ matrix.python-version }} on windows-latest
runs-on: windows-latest
timeout-minutes: 18
strategy:
fail-fast: false
matrix:
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 3
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets"). Shared-runner timing
# varies, so it never gates a pull request. A red run means fix the code.
name: perf budget
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
comfyui:
name: real ComfyUI compatibility
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 35
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Firefox, WebKit and touch (phone-size Chromium): not first-class, so they report here instead of
# blocking a merge. Quarantined tests (@quarantine) run here too. One retry: a test that fails
# and then passes is listed as flaky in the job summary (tools/vendor/flaky-tests-reporter.mjs)
# instead of failing the job.
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 27
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit, touch]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 25
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3 --retries 1
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# One issue per job (tools/ci/nightly_report.py): a job with a failed leg opens "nightly: <job>
# failing" or comments on the open one; a job whose legs all passed closes its open issue. Shards
# of one browser count as one job. Only runs of main report: a manual run of a branch changes no
# issue.
report:
name: report by issue
needs: [python-linux, python-windows, native-trash-linux, perf-budget, comfyui, browser-workflows]
if: ${{ always() && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
contents: read
issues: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Open, update or close one issue per job
env:
GH_TOKEN: ${{ github.token }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: python3 tools/ci/nightly_report.py
-117
View File
@@ -1,117 +0,0 @@
name: Windows
permissions:
contents: read
# Non-blocking Windows runs (#420; macOS dropped from CI in #571): never on pull requests or in the merge queue, and no context
# here is a required check. A red run is fixed at its cause before the workspace cutover (#334).
on:
push:
branches: [main]
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in test.yml: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5, timed as whole-job wall time. One matrix job, so the slowest leg of each
# run counts (tests/vendor/ci-workflow.test.mjs recomputes it, #493).
# Measured 2026-10-29 on main runs 40935337099 (dd247e3), 40938407252 (dd247e3), 40941240624 (dd247e3):
# slowest leg: 7m24s (py3.12 windows) / 7m31s (py3.13 windows) / 7m32s (py3.14 windows) -> 15 min
# (windows 4m56s-7m32s)
# native-trash-linux (#543) has no green main runs yet: it installs the dev requirements and runs
# one test module, about 1 minute by the same estimate, so ceil(1.5 x 2) + 3 gives it 6 minutes.
# Recalibrate after three green runs.
jobs:
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [windows-latest]
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 6
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 4
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
+6
View File
@@ -11,10 +11,16 @@ on:
permissions:
issues: write
# The only workflow a push to main starts (#666): the pull request's gate already tested the commit.
# It runs when pyproject.toml changed, and the action publishes when the version is new.
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
# Measured 2026-11-21 on runs 44547398738 (b3bb55f), 44189688689 (1d509c8), 41519786847 (71b55bc):
# publish-node: 0m33s / 0m31s / 1m16s -> 5 min
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
timeout-minutes: 5
if: ${{ github.repository_owner == 'ComfyAssets' }}
steps:
- name: Check out code
-354
View File
@@ -1,354 +0,0 @@
name: Tests
permissions:
contents: read
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5. The 3 minutes leave room for the Python runner's watchdog (120 s, see
# tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes only
# with new measurements written here (TESTING.md "Time limits and hangs").
# Measured 2026-10-26 on runs 40257217681 (3be0ada), 40240706568 (fb9134f), 40228167328 (f9835aa):
# py matrix, slowest py3.10 on windows-latest: 12m43s / 15m54s / 14m53s -> 27 min
# (ubuntu 5m27s-6m27s, macos 6m14s-8m30s, windows 11m42s-15m54s)
# 3.10 and 3.11 left the matrix and 3.14 joined it in #356; re-measure after three green main runs.
# Windows moved to portability.yml (#420; macOS left CI in #571), which has its own measured limit (#493);
# this Linux-only matrix keeps 27 minutes until it is re-measured.
# real ComfyUI compatibility: 13m32s / 8m55s / 11m46s -> 24 min
# coverage gate (85%): 7m26s / 7m22s / 7m54s -> 15 min
# perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s,
# frontend modules 23s / 19s / 29s -> 5 min (the floor)
# all tests: a result check without setup, 5 min (the floor)
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor)
#
# Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend
# modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on
# Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set.
# Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "all tests" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
# A skipped matrix job reports under its unexpanded name, which would leave the required context
# "py3.12 on ubuntu-latest" waiting for ever. So this job always runs: a docs change gets the 3.12
# leg only, and for an inert change the leg starts and its steps are skipped (#639).
needs: changes
if: ${{ !cancelled() }}
runs-on: ${{ matrix.os }}
timeout-minutes: 27
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ${{ (github.event_name == 'pull_request' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
steps:
- uses: actions/checkout@v7
if: needs.changes.outputs.class != 'inert'
- name: Set up Python ${{ matrix.python-version }}
if: needs.changes.outputs.class != 'inert'
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
if: needs.changes.outputs.class != 'inert'
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
if: needs.changes.outputs.class != 'inert'
run: python -m tests.run_suite -v
- name: Nothing to test
if: needs.changes.outputs.class == 'inert'
run: echo "Only inert files changed (tools/ci/change_class.py); no test can be affected."
comfyui:
name: real ComfyUI compatibility
# Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else
# for a code change. Docs and inert changes skip it everywhere (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 24
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
coverage:
name: coverage gate (85%)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Measure coverage
run: |
python -m coverage run -m tests.run_suite
python -m coverage combine
python -m coverage report --fail-under=85
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets").
# Shared-runner timing varies, so it never gates a pull request: it runs on
# each push to main and on demand. A red run on main means fix the code.
name: perf budget
needs: changes
if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
lint:
name: black and flake8
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
js-test:
name: frontend modules
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The required context "all tests". A dropped matrix leg never reports a check at all, so the eight
# legs that pull requests skip cannot be required by name; this gate requires them instead. Every
# job must succeed; real ComfyUI must be skipped on a pull request and succeed on every other event.
# For a docs or inert change (#639) the test matrix must still succeed and every other job must be
# skipped. The classifier itself must succeed, and a class it does not print fails the gate.
all-tests:
name: all tests
needs: [changes, test, comfyui, coverage, lint, js-test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every test job for this event
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
TEST_RESULT: ${{ needs.test.result }}
COMFYUI_RESULT: ${{ needs.comfyui.result }}
COVERAGE_RESULT: ${{ needs.coverage.result }}
LINT_RESULT: ${{ needs.lint.result }}
JS_RESULT: ${{ needs.js-test.result }}
run: |
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_only)"
echo "test matrix: $TEST_RESULT"
echo "comfyui: $COMFYUI_RESULT"
echo "coverage: $COVERAGE_RESULT"
echo "lint: $LINT_RESULT"
echo "js-test: $JS_RESULT"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only"
+9
View File
@@ -17,9 +17,18 @@ concurrency:
group: viewerjs-update
cancel-in-progress: false
# Time limit rule as in ci.yml (#662): ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
# Measured 2026-11-21 on runs 44771628562 (b3bb55f), 44568715421 (b3bb55f), 44349316383 (1d509c8):
# these nightly runs found no new release and took 0m09s / 0m13s / 0m12s, the 5-minute floor. None of
# the 35 green runs since 2026-10-17 took the update path (tests, Chromium, the PR), so it is estimated
# from its parts until three green update runs can be measured:
# estimate update: npm ci on a cold cache up to 5m (as recorded for the browser jobs), Playwright
# Chromium with its system packages about 2m, the pin check, tooling and unit tests about 1m, the
# viewer suite (38s locally, 2 workers) and setup about 2m: 10 min, ceil(1.5 x 10) + 3 -> 18 min
jobs:
update:
runs-on: ubuntu-latest
timeout-minutes: 18
permissions:
contents: write
pull-requests: write
-3
View File
@@ -1,6 +1,3 @@
# Tailwind standalone CLI (downloaded by `make css-setup`)
tailwindcss
# AI tooling / local config
.claude/
.playwright-mcp/
+3 -2
View File
@@ -13,7 +13,7 @@ repos:
language: system
types: [python]
# Fails at the severity CI enforces (code-quality.yml: -lll, high only), never stricter.
# Fails at the severity CI enforces (ci.yml: -lll, high only), never stricter.
# pre-commit appends the staged files, so no shell wrapper can drop the first one.
- id: bandit
name: bandit
@@ -22,7 +22,8 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
# Skipped for an inert push; a docs push runs only the two tests that read the docs
# (tools/ci/change_class.py, #639, #679).
- id: tests
name: tests
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
+258
View File
@@ -0,0 +1,258 @@
# Changelog
What changed in each release of ComfyUI Prompt Manager, newest first. Full notes for each version are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
Thank you to everyone whose pull requests are part of these releases. They are named beside their changes and listed under [Contributors](#contributors).
## v3.8.0 (Old pages removed, Tag cleanup, AVIF)
- **🧹 Tag cleanup**: System › Maintenance finds tags that are whole comma lists and tags used nowhere. You review them and remove only what you tick; a safety backup is always taken first. Later cleanups will be added to the same place ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🏷️ LoRA import tags**: a LoRA's trained words become a tag only when they are one short phrase. Lists and sentences are no longer saved as tags, and the import review says how many were left out ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🖼️ AVIF images**: collected, thumbnailed and linked to their prompts like PNG and WebP, where your Pillow can read AVIF. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673), [#652](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/652))
- **🗑️ Old pages removed**: the old Dashboard, Gallery and Metadata viewer are gone, after the notice in 3.5.1. Their addresses open the matching workspace page, and old tag bookmarks open the Prompt library with that filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🔗 Tag filters in the address**: `#/library?tag=cats&tag=dogs&tag_mode=any` can be bookmarked and shared; Reload, Back and Forward keep the filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🐛 LoRA import label**: an import that had already saved when ComfyUI closed is shown as finished, not cancelled. By [@aryankalantri](https://github.com/aryankalantri) ([#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672), [#619](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/619))
- **🪟 Windows**: two installs writing one shared thumbnail folder at the same moment no longer fail with "Permission denied" ([#674](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/674))
- **⚠️ Known limit**: Inspect shows a WebP or AVIF file but not its embedded prompt yet; the image still links to its prompt ([#656](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/656))
## v3.7.2 (Always a way to choose the prompt)
- **🎯 Choose prompt in Inspect**: an image with several possible prompts shows a Choose prompt section; Inspect creates the Needs review item itself, also for older images ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **📥 Needs review without a scan**: the live monitor queues an ambiguous output as soon as its run ends ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **🔢 Big workflows**: a file with more than 16 different prompts offers the 16 most used instead of none
- **🔗 Link to a prompt** lists the image's own prompts first; the Needs review queue loads as you scroll
- **🐛 rgthree Any Switch** no longer makes a decided prompt look ambiguous ([#657](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/657)); a role every candidate agrees on shows as resolved ([#658](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/658))
- **🧪 CI**: every change is tested once, on its pull request; other browsers, Python versions and Windows run nightly ([#666](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/666))
## v3.7.1 (WebP linking)
- **🖼️ WebP images link to their prompts**: ComfyUI's Save Animated WEBP stores the prompt in EXIF, which is now read. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650))
- **🐛 Prepend and append text** start empty instead of `null`. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651))
## v3.7.0 (Permanent delete, new logo)
- **🗑️ Permanent delete** for images on Linux and BSD servers, beside remove-from-library and trash. By [@k98kurz](https://github.com/k98kurz) ([#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643))
- **🎨 New logo** in the README, the Comfy Registry and the browser tabs ([#632](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/632))
- **🐛 Folders with a backslash in their name** work on Linux and macOS; one odd file no longer stops the viewer opening ([#646](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/646))
## v3.6.0 (Library sorts)
- **↕️ Three more Prompt library sorts**: Recently used, Most used and Name Z–A
- **🐛 Windows network shares**: backup checks, restore, Move library and history reads open a library on a network path ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
- **🐛 Unloading a tagging model** no longer freezes the server ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
## v3.5.1 (Smaller download)
- **📦 Smaller package**: the Registry download drops from 17.4 MB to about 3.9 MB ([#615](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/615))
- **📣 Notice**: the old pages say they will be removed
## v3.5.0 (Thumbnail location, Send to all, Skipped tags)
- **📁 Thumbnail location**: keep thumbnails inside each source or in one folder of your choice, with a reviewed move ([#320](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/320))
- **📤 Send to every node**: Send to ComfyUI offers all eligible nodes of a window at once ([#542](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/542))
- **🚫 Skipped tags** and **saved tagging instructions** for auto-tagging ([#431](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/431))
- **🔧 Pair category and tags repair** in System › Maintenance ([#550](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/550))
- **⚡ Less memory** for scans and image work ([#523](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/523))
- **🐛 Prompt Search List** text is no longer saved as a prompt ([#548](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/548))
## v3.4.1 (Fix release)
- **🪟 Windows**: ComfyUI could hang on exit with watchdog 7.0.0
- **🔒 LoRA import errors** no longer show server details
## v3.4.0 (The workspace)
- **✨ Rebuilt around one page**, the workspace: Images, Prompt library, Tags & categories, Collections, Favorites, Needs review, Inspect a file, Activity and System
- **🖼️ Viewer** with keyboard shortcuts, zoom, rotate and slideshow; **Send to ComfyUI** from any prompt
- **🏷️ Per-image tags and auto-tagging** with WD14 or JoyCaption
- **🧩 Nodes**: Focused, Split and Prompt Manager (+/-) join Classic, Text and Search List; all run in Classic and Nodes 2.0
- **📁 Library outside the node folder**: new installs keep the library in `ComfyUI/user/__promptmanager/`; an existing library moves only when you choose
- **🗜️ Smaller database**: each workflow and prompt graph is stored once, compressed
- **⚠️ Requires Python 3.12 or newer**; downgrading is not supported
## Earlier versions
Releases from before the workspace, as they were written at the time.
## v3.3.1 (Proxy Routing Fix)
- **🌐 Proxy support**: the dashboard, gallery, tag page and metadata viewer now work when ComfyUI is reached through a proxy mount such as SwarmUI's `/ComfyBackendDirect/`. Scripts, images, API calls, progress streams and gallery folder filters stay under the mount, and the canvas node's buttons use ComfyUI's `fileURL()`. Direct ComfyUI URLs are unchanged. Thanks to @ghosttigerllc-bit ([#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164))
- **📦 Dependencies**: the runtime minimums stay at `Pillow>=8.0.0` and `watchdog>=2.1.0`, so updating Prompt Manager never forces upgrades in the shared ComfyUI environment
## v3.3.0 (Hardening, Background Jobs & Worker Threads)
- **🔒 Security**: gallery roots restricted to ComfyUI directories and validated wherever they are read; media-only, fail-closed image serving; Windows path escape in static routes closed; quote-safe HTML escaping with inline handlers moved to data attributes; the CivitAI key is never returned and only sent to HTTPS CivitAI hosts; auto-tag paths contained; side-effect routes are POST-only; backups include the WAL and restores are size-capped, integrity-checked and applied through SQLite's online backup API
- **🧵 Worker Threads**: a Settings slider (default half the cores) used by the image rescan, thumbnail generation and duplicate detection. Measured: a 1 GB sample scanned in 2.5 s instead of 18 s at 8 threads
- **🔁 Background Jobs**: the image rescan and the duplicate scan run on the server, stream progress, survive a closed tab, minimize to a progress pill and re-attach after a reload
- **🎬 Video Prompts**: the scan reads the prompt ComfyUI's video savers embed in MP4/MOV/WebM containers (needs `ffprobe`)
- **🖼️ Thumbnails**: written atomically and served under versioned URLs so a regenerated thumbnail never shows a stale cached copy; the per-run cap applies only to thumbnails that still need generating and the gallery says how many remain
- **🏷️ Tag Autocomplete**: the dashboard tag box suggests tags, narrowed to those that co-occur with the tags already typed
- **♾️ Infinite Scrolling**: optional in the gallery and the dashboard list (saved default plus a session toggle)
- **⚙️ Gallery Settings** now apply at load; grid columns, media info and the Rescan button work as labelled
- **🐛 Correctness**: run counts increment when ComfyUI dequeues a prompt; negative prompts are never traced; per-thread SQLite connections and idempotent migrations (an old rebuild could delete every image row); `truncate_logs` no longer rolls the log over; the ComfyUI canvas loads only the canvas extension; Windows console banners are ASCII-safe; subfolders use `/` on every platform
- **🧪 Tests & CI**: 1,460 Python and 142 JavaScript tests (from 510 and 26), coverage 96% with an 85% gate, CI on Linux, Windows and macOS for Python 3.10–3.12, flake8 clean
- **⚠️ API changes**: image paths in responses are relative to the ComfyUI tree (use `url`); `autotag/download`, `autotag/start` and the thumbnail progress stream are POST-only; `lora/status` returns `has_civitai_api_key` instead of the key; `/search` is paginated
## v3.2.4 (Recently Used Sorting & Queue-Time Run Counts)
- **🕒 Recently Used Sort**: sort the dashboard by last use, most used or rating, server-side across pages
- **🔢 Run Counts**: `run_count` and `last_used_at` are recorded through the ComfyUI queue hook, so cached nodes still count
- **🔗 Positive-Prompt Image Linking**: generated images link to the positive prompt traced through the queued graph
## v3.2.1 (LoRA Manager Integration)
- **🔗 LoRA Manager Integration**: Import LoRA metadata, trigger words, and CivitAI example images from [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) into your prompt database
- **💉 Auto-Inject Trigger Words**: Optionally append LoRA trigger words when `<lora:name:weight>` is detected in prompts during encoding
- **🔑 CivitAI API Key Support**: Authenticate with CivitAI to download NSFW preview images
- **📥 Import Progress Modal**: Real-time SSE streaming progress during LoRA import with per-model status
> **Note:** LoRA Manager support is a WIP — this was a highly requested feature. Please [open issues](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues) for any bugs or feature requests.
## v3.2.0 (Folder Filter & QoL Improvements)
- **📁 Folder Filter**: New folder dropdown in the search panel to filter prompts by output subdirectory
- **📂 Multi-Directory Gallery Scan**: Configure multiple output directories and browse them all in one gallery
- **🖼️ Filmstrip Prompt Display**: Show prompt text and copy button in the filmstrip image viewer
- **🖱️ Click-to-Close Viewer**: Click outside the image viewer to close it
- **🐛 Bug Fixes**: Fixed database path config, UnboundLocalError in text inputs, node caching skip, diagnostics singleton lifecycle
## v3.1.0 (WD14 Tagger, Tailwind v4 & Major Refactors)
- **🏷️ WD14 Tagger Support**: Added WD14 SwinV2 and WD14 ViT as new auto-tag model options — fast ONNX-based classifiers (~400MB) that output Danbooru tags with confidence scores, no prompt needed
- **🎚️ Threshold Controls**: Adjustable general tag (default 0.35) and character tag (default 0.85) confidence thresholds for WD14 models via UI sliders
- **🎨 Tailwind v4 Migration**: Complete frontend redesign with ComfyUI theme token system (`--pm-*` design tokens) that adapts to ComfyUI's color palette
- **🏗️ API Refactor**: Split monolithic `api.py` into domain-specific route modules for better maintainability
- **🗃️ Junction Table Tags**: Migrated tag storage from JSON column to normalized junction tables with proper foreign keys
- **📄 Tags Page**: Dedicated tag management page with search, rename, merge, and delete operations
- **🔍 Load More Button**: Progressive prompt loading instead of traditional pagination
- **🔒 Security Hardening**: Resolved 15 GitHub code scanning alerts, prevented stack trace exposure in SSE errors
- **🧪 Test Coverage**: Added comprehensive unit tests for validators, hashing, metadata, config, and prompt tracker; API integration tests; database tests with CI pipeline
- **⚙️ CI/CD Improvements**: Added code quality scanning, security scanning, Dependabot, and pre-commit hooks with Black formatting
- **🐛 Bug Fixes**: Fixed custom image scan directory config (#108), gallery crash on thumbnail linking, broken imports after API refactor, widget value sync issues, and prepend/append metadata tag filtering in auto-tagger
## v3.0.26 (Top Bar Button)
- **🔘 Top Bar PM Button**: Added a "PM" button to the ComfyUI top bar for quick access to the admin dashboard
- **🚀 No Node Required**: Open PromptManager without having to add the node to your workflow first
- **🎨 Teal Button Design**: Distinctive teal-colored button positioned before the settings gear
- **🔄 Frontend Compatibility**: Works with both new ComfyUI frontend (v1.3.1+) and legacy versions
## v3.0.25 (Film Strip & QoL Improvements)
- **🎞️ Film Strip Preview**: Backported from V2 - thumbnail strip under each prompt showing linked images
- **🖼️ Quick Image Viewer**: Click any filmstrip thumbnail to open full-size image viewer
- **📸 Smart Thumbnails**: Automatically uses generated thumbnails for faster loading, falls back to full images
- **⬆️ Auto-Scroll on Pagination**: Page navigation now smoothly scrolls to top after loading
## v3.0.24 (Manual Prompt Creation)
- **➕ Add Prompt Button**: New "Add Prompt" button in the admin dashboard Bulk Actions bar
- **📝 Direct Prompt Creation**: Create prompts directly from the UI without generating images
- **🛡️ Protection from Pruning**: New prompts are automatically protected from orphan cleanup by default
- **🏷️ Full Metadata Support**: Set category, tags, rating, and notes when creating prompts
- **🔒 Orphan Protection Toggle**: Option to protect or unprotect prompts from maintenance cleanup
## v3.0.23 (AI AutoTag Release)
- **🏷️ AI AutoTag**: Automatically tag your entire image collection using JoyCaption vision models
- **🤖 Dual Model Support**: Choose between JoyCaption Beta One FP16 (high quality) or GGUF FP8 (lower VRAM)
- **📋 Two Tagging Modes**: Batch mode for bulk tagging, Review mode for one-by-one approval
- **⚙️ Smart Tag Handling**: Skip already-tagged images or re-tag all - respects your existing work
- **✏️ Customizable Prompts**: Adjust the system prompt to match your collection style and tag vocabulary
- **🔄 Real-time Progress**: SSE-based streaming progress updates during batch operations
- **📦 Tag Accordion UI**: Collapsible tag display shows first row with expandable section for large tag sets
- **🎯 Review Confirmation**: Prompts before overwriting existing tags in review mode
## v3.0.10 (Batch Processing Node)
- **📋 PromptSearchList Node**: New node that searches the prompt database and outputs results as a list
- **🔗 Batch Processing Support**: Uses `OUTPUT_IS_LIST` for native ComfyUI batch processing compatibility
- **🔍 Full Search Capabilities**: Search by text, category, tags, minimum rating, and result limit
- **⚡ Lightweight Operation**: Read-only search with no database writes
- **🎯 Workflow Integration**: Connect directly to batch processing nodes like String OutputList
## v3.0.9 (Output-Wide Gallery & Video Support)
- **📁 Output-Wide Gallery Mode**: Complete gallery redesign to show ALL content from ComfyUI output directory
- **🎬 Full Video Support**: Native video playback with HTML5 player for .mp4, .webm, .avi, .mov, .mkv, .m4v, .wmv formats
- **🖼️ Video Thumbnail Generation**: Automatic video thumbnails using OpenCV, ffmpeg, or placeholder fallback
- **⚙️ Video Settings Panel**: Configurable autoplay, mute, and loop settings with persistent preferences
- **🎮 Video Navigation**: Seamless navigation between videos with keyboard shortcuts and custom controls
- **📊 Video Metadata Display**: Show duration, resolution, aspect ratio, and detailed file information
- **🔄 Mixed Media Integration**: Videos and images seamlessly integrated in the same gallery interface
- **⚡ Enhanced Performance**: Optimized thumbnail generation for both images and videos
- **🎛️ Advanced Gallery Settings**: Comprehensive settings panel with video controls and performance options
- **🖱️ Improved Click Handling**: Fixed thumbnail failures to preserve click functionality
- **📱 Mobile Compatibility**: Enhanced responsive design for video playback on all devices
## v3.0.5 (Text-Only Node Release)
- **📝 PromptManagerText Node**: New text-only variant that outputs STRING instead of CONDITIONING
- **🔗 Text Concatenation**: Built-in prepend/append functionality for dynamic text assembly
- **⚡ Lightweight Processing**: No CLIP encoding overhead for pure text workflows
- **🔄 Dual Node Architecture**: Choose between CLIP encoding (PromptManager) or text-only (PromptManagerText)
- **🏷️ Shared Metadata System**: Both nodes use the same database and metadata features
- **🖼️ Unified Gallery**: Images from both node types appear in the same gallery system
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
## v3.0.3 (ViewerJS Integration & Enhanced Gallery)
- **🖼️ Professional Image Viewer**: Complete gallery redesign with [ViewerJS](https://github.com/fengyuanchen/viewerjs) integration
- **⚡ Advanced Image Navigation**: Zoom, rotation, slideshow, and professional viewing controls
- **🎨 Dark Theme Integration**: Seamless ViewerJS styling that matches the admin interface
- **🔬 Enhanced Metadata Parsing**: Improved ComfyUI workflow parameter extraction with targeted parsing
- **📊 Real-time Parameter Display**: Live CFG, steps, sampler, and seed extraction from workflow nodes
- **📋 Integrated Copy Functionality**: One-click copying of prompts and generation parameters
- **🛠️ Robust Value Detection**: Smart parsing that targets specific node types and validates parameters
- **⌨️ Keyboard Navigation**: Full keyboard support for gallery navigation and viewer controls
- **📱 Responsive Design**: Enhanced mobile and tablet compatibility
## v3.0.0 (Metadata Analysis Release)
- **🔬 PNG Metadata Analysis**: Advanced ComfyUI workflow extraction from PNG images
- **📋 Standalone Metadata Viewer**: Dedicated tool at `/web/metadata.html` for analyzing any ComfyUI image
- **🖼️ Integrated Metadata Panel**: Real-time workflow analysis in the image viewer
- **📸 Bulk Image Scanning**: Mass import and analysis of existing ComfyUI output directories
- **🛠️ System Management Suite**: Complete backup, restore, maintenance, and diagnostic tools
- **🚮 Orphaned Prompt Cleanup**: Remove prompts that have no linked images for database optimization
- **📋 Advanced Logging**: Comprehensive logging system with web-based log viewer
- **🎨 Enhanced Admin Dashboard**: Modern dark theme with improved UX and management tools
- **🔧 Robust Error Handling**: Advanced PNG parsing with NaN value cleaning and error recovery
- **📁 File Path Integration**: Direct file path display and system integration
- **⚡ Performance Optimizations**: Improved metadata extraction and database operations
## v2.0.0 (Gallery Release)
- **🖼️ Automatic Image Gallery**: Complete image tracking and gallery system
- **🌐 Advanced Web Interface**: Comprehensive admin dashboard with responsive design
- **📱 Image Viewer**: Full-screen modal with navigation and keyboard shortcuts
- **🔍 Enhanced Search**: Real-time search with advanced filtering options
- **⚡ Performance Improvements**: Optimized database operations
- **🛠️ Basic Diagnostics**: Initial system diagnostics and health monitoring
- **📊 Bulk Operations**: Multi-select prompt editing and management
## v1.0.0 (Initial Release)
- Core text encoding with database storage
- Search and filtering functionality
- Metadata support (categories, tags, ratings, notes)
- Hash-based deduplication
- SQLite backend with optimized schema
- Basic web interface
- Export functionality
## Contributors
Pull requests from the community that were merged into Prompt Manager:
| Contributor | Pull requests |
| --- | --- |
| [@LacklusterOpsec](https://github.com/LacklusterOpsec) | [#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673) AVIF as a media type · [#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650) WebP images link to their prompts · [#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651) prepend/append defaults |
| [@aryankalantri](https://github.com/aryankalantri) | [#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672) LoRA import finishes when it saved at exit |
| [@k98kurz](https://github.com/k98kurz) | [#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643) permanent delete for images (Linux/BSD) |
| [@ghosttigerllc-bit](https://github.com/ghosttigerllc-bit) | [#165](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/165) A1111/Forge generation parameters · [#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164) routing behind a ComfyUI proxy · [#140](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/140) recursive subfolder filtering and gallery tree |
| [@develop1st](https://github.com/develop1st) | [#141](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/141) collapsible sidebar setting and mobile overlap fix |
| [@logicalor](https://github.com/logicalor) | [#87](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/87) thumbnails in subfolders |
| [@x0x0b](https://github.com/x0x0b) | [#73](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/73) star icon alignment |
| [@robinjhuang](https://github.com/robinjhuang) | [#2](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/2) Registry publishing action · [#1](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/1) `pyproject.toml` for the Registry |
-43
View File
@@ -1,43 +0,0 @@
TAILWIND_VERSION := 4.1.18
TAILWIND_CLI := ./tailwindcss
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_S),Darwin)
ifeq ($(UNAME_M),arm64)
TAILWIND_PLATFORM := tailwindcss-macos-arm64
else
TAILWIND_PLATFORM := tailwindcss-macos-x64
endif
else
ifeq ($(UNAME_M),aarch64)
TAILWIND_PLATFORM := tailwindcss-linux-arm64
else
TAILWIND_PLATFORM := tailwindcss-linux-x64
endif
endif
TAILWIND_URL := https://github.com/tailwindlabs/tailwindcss/releases/download/v$(TAILWIND_VERSION)/$(TAILWIND_PLATFORM)
.PHONY: css css-watch css-setup clean-css
## Download Tailwind standalone CLI (dev only, not committed)
css-setup:
@if [ ! -f $(TAILWIND_CLI) ]; then \
echo "Downloading Tailwind CSS v$(TAILWIND_VERSION) CLI..."; \
curl -sLo $(TAILWIND_CLI) $(TAILWIND_URL) && chmod +x $(TAILWIND_CLI); \
else \
echo "Tailwind CLI already present"; \
fi
## Rebuild compiled CSS (run after changing Tailwind classes in HTML/JS)
css: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --minify
## Watch mode for development
css-watch: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --watch
## Remove downloaded CLI binary
clean-css:
rm -f $(TAILWIND_CLI)
+5 -6
View File
@@ -1,12 +1,11 @@
> **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
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![ComfyUI](https://img.shields.io/badge/ComfyUI-compatible-green.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
![Code Quality](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Code%20Quality/badge.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
A comprehensive ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, automatic image gallery system, folder-based organization, LoRA Manager integration, and powerful ComfyUI workflow metadata analysis using SQLite.
@@ -254,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
@@ -329,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**
+72 -53
View File
@@ -8,24 +8,24 @@
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
Prompt Manager saves your prompts as you generate, links each image back to the prompt that made it, and gives you one page to browse, tag, compare and reuse all of it. Your library is a local SQLite database on your own machine.
Prompt Manager saves your prompts as you generate and links each image to the prompt that made it. One page, the workspace, lets you browse, tag, compare and reuse them. Your library is a local SQLite database on your own machine.
## What's new: rebuilt from the ground up
## What's new
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages.
- **A new UI.** The workspace replaces the separate dashboard, gallery and metadata pages.
- **Classic and Nodes 2.0.** The nodes work in both ComfyUI renderers. CI starts a real ComfyUI and checks both.
- **Tested end to end.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Automated tests.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Linux and Windows.** The Python suite runs on both, on Python 3.12, 3.13 and 3.14. macOS should work but is not tested.
## See it
All images on this page were generated and recorded through Prompt Manager in a clean demo library.
### Your whole output folder, finally browsable
### Browse your whole output folder
Masonry, grid or list, with search, categories, filters and saved views. Images and videos sit side by side, and selecting one shows its prompts and settings without leaving the page.
The Images page shows your output as masonry, a grid or a list. Search, categories, filters and saved views narrow it. Images and videos appear together, and selecting one shows its prompts and settings on the same page.
![Images page in grid layout](assets/readme/images-grid.webp)
@@ -35,63 +35,63 @@ The viewer shows the positive and negative prompts, tags, seed, steps, CFG, samp
![The viewer with an image on the left and its prompts and generation settings on the right](assets/readme/viewer.webp)
### Keep your hands on the keyboard
### Keyboard shortcuts
The viewer has shortcuts for moving between files, the slideshow, zoom, rotate, flip, full screen, details, download and delete. Press `?` to see them all.
![The viewer's keyboard shortcuts overlay](assets/readme/viewer-shortcuts.webp)
### Long libraries stay easy to work in
### Select and act while you scroll
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from anywhere. Back to top appears once you've scrolled down the page.
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from any position on the page. A Back to top button appears once you scroll down.
![Images page scrolled down, with the selection bar pinned at the top and a Back to top button](assets/readme/pinned-bar.webp)
### One positive prompt, many experiments
The Prompt library groups everything by positive prompt, so repeat runs and negative variants stay together instead of filling your list with near-duplicates.
The Prompt library groups everything by positive prompt. Repeat runs and negative variants stay with their positive prompt and don't add near-duplicate entries to your list.
![Prompt library cards showing each prompt's images, negative variants, runs and tags](assets/readme/library.webp)
### Watch your negatives branch on a timeline
### See negative variants on a timeline
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative made. Small dots mark repeat runs.
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative variant made. Small dots mark repeat runs.
![Clicking through negative variants on the timeline filters the gallery below](assets/readme/timeline.anim.webp)
### Compare negatives term by term
Compare negatives shows two variants side by side and lists the terms one adds, so you can see what actually changed between runs.
Compare negatives shows two negative variants side by side and lists the terms one adds, so you can see what changed between runs.
![Two negative prompts side by side with the added terms highlighted](assets/readme/compare-negatives.webp)
### Auto-tag your images, and approve what sticks
### Auto-tag your images and approve the suggestions
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before anything is saved. Auto-tags belong to the image, so they never change your prompts.
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before Prompt Manager saves anything. Auto-tags belong to the image, so they never change your prompts.
![Tag image dialog with WD14 suggestions and their confidence scores](assets/readme/autotag.webp)
### Keep your vocabulary tidy
### Manage tags and categories
Tags & categories lists every tag and category with how often it's used. Rename, merge and delete tags, and preview a category change before you apply it.
Tags & categories lists every tag and category with how often you use it. Rename, merge and delete tags, and preview a category change before you apply it.
![Tags and categories page](assets/readme/tags.webp)
### Group images your own way
Collections are hand-picked sets of images, on top of favorites and saved views. Add from the selection bar and they appear in the sidebar.
Collections are sets of images you pick by hand. They are separate from favorites and saved views. Add images from the selection bar and the collection appears in the sidebar.
![A collection called Book cover ideas open in the workspace](assets/readme/collections.webp)
### Nothing gets guessed
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link it to any prompt in your library, or leave it unresolved.
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link the file to any prompt in your library, or leave it unresolved.
![Link to a prompt dialog searching the library from Needs review](assets/readme/needs-review.webp)
### Inspect any file, without importing it
### Inspect any file without importing it
Pick an image or video from your computer to read its prompts, settings and workflow. The file is read in your browser. It isn't uploaded or added to your library.
Pick an image or video from your computer to read its prompts, settings and workflow. Your browser reads the file. Prompt Manager doesn't upload it or add it to your library.
![Inspecting a local file in the viewer](assets/readme/inspect.webp)
@@ -103,7 +103,13 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
### Deletes you can review
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
Before Prompt Manager removes anything, you choose what happens to the files:
- **Remove from the library.** The file stays on disk. This is the only choice on Windows.
- **Move to the system trash.** Linux and macOS only.
- **Delete permanently.** Linux and BSD servers only. This is for headless servers, where a trash fills the disk. You can't recover these files.
A safety backup of the database is on by default, and you can bring removed images back.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -117,17 +123,17 @@ System holds settings, image sources, auto-tag models, integrations, maintenance
### Works on your phone too
The workspace adapts to narrow screens, and touch is part of the browser test suite.
The workspace adapts to narrow screens, and the browser test suite includes touch.
![Images page and viewer at phone width](assets/readme/phone.webp)
## The nodes
Six nodes, under **ComfyAssets > Prompts** in the Add Node menu. Pick the one that suits your workflow; they all share one library. Every screenshot below is a small real workflow that ran.
The six nodes are under **ComfyAssets > Prompts** in the Add Node menu. They all share one library. Every screenshot below is a small real workflow that ran.
### Prompt Manager (Classic)
The drop-in replacement for CLIP Text Encode: same CLIP input, same CONDITIONING output, with the prompt saved as it runs. It also outputs the text as a STRING.
This node replaces CLIP Text Encode. It has the same CLIP input and the same CONDITIONING output, and it saves the prompt as it runs. It also outputs the text as a STRING.
![Prompt Manager Classic node in a workflow, Classic renderer](assets/readme/node-classic.webp)
@@ -137,19 +143,19 @@ The same workflow in Nodes 2.0:
### Prompt Manager (Focused)
An editor-first layout. Composition and metadata fold away, and **Browse library** lets you search, preview and use a saved prompt right on the node.
This node puts the editor first. Composition and metadata collapse, and **Browse library** lets you search, preview and use a saved prompt on the node.
![Prompt Manager Focused node in a workflow](assets/readme/node-focused.webp)
### Prompt Manager (Split)
The same editor with the library always visible. Wide nodes put them side by side; narrow nodes stack them.
This node has the same editor with the library always visible. A wide node shows them side by side. A narrow node stacks them.
![Prompt Manager Split node in a workflow](assets/readme/node-split.webp)
### Prompt Manager (+/-)
Positive and negative in one node, saved as a pair. This is the node that feeds the negative-variant timeline. It outputs CONDITIONING and STRING for both sides.
This node holds the positive and the negative prompt and saves them as a pair. The timeline's negative variants come from this node. It outputs CONDITIONING and STRING for both sides.
![Prompt Manager plus/minus node in a workflow](assets/readme/node-pair.webp)
@@ -159,23 +165,23 @@ The same workflow in Nodes 2.0:
### Prompt Manager Text
Saves the prompt and outputs a STRING instead of CONDITIONING, for workflows that send text to another node. Prepend and append inputs let you build the final text.
This node saves the prompt and outputs a STRING, not CONDITIONING. Use it in workflows that send text to another node. Prepend and append inputs let you build the final text.
![Prompt Manager Text node feeding a CLIP Text Encode node](assets/readme/node-text.webp)
### Prompt Search List
Searches your library by text, category, tags and minimum rating, then outputs the matches as a list so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
This node searches your library by text, category, tags and minimum rating. It outputs the matches as a list, so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
![Prompt Search List node producing three images](assets/readme/node-search.webp)
To get the images of a Search List batch linked to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked: the search text is never saved as a prompt.
To link the images of a Search List batch to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked, because nothing saves the search text as a prompt.
## Install
**Requirements:** ComfyUI and Python 3.12 or newer. `watchdog` and `Pillow` are the only dependencies of their own; the rest comes with ComfyUI.
Prompt Manager requires ComfyUI and Python 3.12 or newer. Its only dependencies of its own are `watchdog` and `Pillow`. The rest comes with ComfyUI.
Install from the Comfy Registry or ComfyUI-Manager (search for Prompt Manager), or by hand:
Install from the Comfy Registry or ComfyUI-Manager by searching for Prompt Manager, or install by hand:
```bash
cd ComfyUI/custom_nodes/
@@ -185,7 +191,7 @@ pip install -r ComfyUI_PromptManager/requirements.txt
Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `http://localhost:8188/prompt_manager/workspace`.
**Optional extras.** Nothing here is installed for you:
**Optional extras.** Prompt Manager installs none of these for you:
| To use | You need |
| --- | --- |
@@ -193,7 +199,7 @@ Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `
| GGUF JoyCaption (about 4.5 GB) | `llama-cpp-python` |
| HuggingFace JoyCaption (about 16 GB) | `transformers`, `accelerate`, `bitsandbytes` |
| Prompts embedded in videos | `ffprobe` on PATH |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed; turn it on in System > Integrations |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed. Turn the import on in System > Integrations. |
Download or unload tagging models in System > Auto-tagging.
@@ -210,31 +216,40 @@ Set `PROMPT_MANAGER_DATA_DIR` to an absolute folder to keep the library somewher
## Upgrading from an earlier version
- **Python 3.12 or newer is now required.**
- **Your library stays where it is** until you choose. The workspace offers **Move library**, which makes a verified copy in `user/__promptmanager/` and renames the old files instead of deleting them, or **Keep it here**.
- **Older images:** a one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Workflows are now stored once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
- **Your library stays where it is until you choose.** The workspace offers two choices. **Move library** makes a verified copy in `user/__promptmanager/` and renames the old files without deleting them. **Keep it here** leaves the library in place.
- **Older images.** A one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Prompt Manager now stores each workflow once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
## The old pages will be removed
## The old pages are gone
They still work at their URLs for now and will be removed in a future release. Everything they do is moving to the workspace.
This version removes the dashboard, tags page, gallery and metadata viewer. The workspace does everything they did. Their URLs and bookmarks still work, and each one opens the matching workspace page.
| Page | URL |
| Old URL | Opens |
| --- | --- |
| Dashboard | `/prompt_manager/admin` |
| Tags | `/prompt_manager/admin#/tags` |
| Gallery | `/prompt_manager/gallery` |
| Metadata viewer | `/prompt_manager/gallery.html` |
| `/prompt_manager/admin` | Prompt library |
| `/prompt_manager/admin#/tags` | Tags & categories |
| `/prompt_manager/admin#/tags/cats,dogs?mode=or` | Prompt library, filtered to prompts tagged `cats` or `dogs` |
| `/prompt_manager/gallery` | Images |
| `/prompt_manager/gallery.html` | Inspect a file |
The documentation for those pages is in [README-legacy.md](README-legacy.md).
A tag bookmark opens the Prompt library with that filter, and the filter stays in the address: `/prompt_manager/workspace#/library?tag=cats&tag=dogs&tag_mode=any`.
- Reload, Back and Forward keep the filter.
- The address follows the tags you set in **Filters**.
- You can bookmark such a link or write one yourself. Leave out `tag_mode` to match all the tags. `tag_mode=untagged` lists prompts without a tag.
- The sidebar's Prompt library link always shows the whole library.
- Search, category and sort aren't part of the address. **Save view** keeps those.
[README-legacy.md](README-legacy.md) still describes the old pages, for reference.
## Known limits
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists the reason for each file.
- **Permanent delete is Linux and BSD only.** You can't undo it. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, which may not be the machine with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
- **Leave unresolved is permanent.** A file you leave unresolved in Needs review isn't offered again unless its bytes change.
- **Leave unresolved is permanent.** Needs review doesn't offer the file again unless its bytes change.
- **Pair prompts saved by earlier versions** stay Uncategorized. You can set the category with Edit metadata.
## How it's tested
@@ -246,8 +261,12 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
| Browser | Over 60 Playwright spec files in Chromium, Firefox, WebKit and touch emulation |
| Real ComfyUI | A pinned CPU ComfyUI, started in Classic and Nodes 2.0, running real workflows |
Linux runs on every pull request and in the merge queue. Windows runs on every push to main and nightly. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. Nothing tests macOS. It should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## Changelog
[CHANGELOG.md](CHANGELOG.md) lists what changed in each release and the contributors whose pull requests are part of it. Full notes are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
## License
MIT. See [LICENSE](LICENSE).
The license is MIT. See [LICENSE](LICENSE).
+607 -285
View File
File diff suppressed because it is too large Load Diff
+39 -13
View File
@@ -156,12 +156,13 @@ try:
_global_prompt_tracker = get_prompt_tracker(_global_db)
_global_image_monitor = get_image_monitor(_global_db, _global_prompt_tracker)
# The Needs review pass for ambiguous new outputs runs through the API's
# capture store (the one the scan and the Tag dialog use): a linked output
# is never queued and its pending items leave the queue. The package
# teardown detaches it before that store is closed at shutdown.
# The Needs review pass runs on the API's review worker (#659), through
# the capture store the scan and the Tag dialog use: an output the
# monitor leaves unlinked at its final outcome is queued as a scan would
# queue it, and a linked one's pending items leave the queue. The package
# teardown detaches it and stops the worker before that store is closed.
if api is not None:
_global_image_monitor.set_review_recorder(api.record_review_file)
_global_image_monitor.set_review_recorder(api.queue_review_file)
# Every settled output's preview is queued for the API's background
# worker (#249): the workspace never asks to generate thumbnails.
_global_image_monitor.set_thumbnail_queue(api.queue_capture_thumbnail)
@@ -292,15 +293,26 @@ def _teardown_logger():
return logging.getLogger("prompt_manager.init")
def _stop_background_work():
"""Stop the image monitor, the preview worker, the job worker threads
and the prompt cleanup thread against one TEARDOWN_SECONDS deadline, once.
def _review_worker_started(api_object):
"""Whether the API's Needs review worker ever started (False without
one, or when the check fails)."""
try:
return bool(api_object is not None and api_object.review_worker_started())
except Exception:
return False
Returns ``{"monitor", "thumbnails", "workers", "tracker"}`` booleans
(True: it stopped), leaving out parts that never started. Later calls return a
copy of the first result. A Ctrl+C inside a step is logged and the
step is False; one between steps is re-raised after the result (parts
not reached are False) is stored and the ``atexit`` entry removed.
def _stop_background_work():
"""Stop the image monitor, the Needs review worker, the preview worker,
the job worker threads and the prompt cleanup thread against one
TEARDOWN_SECONDS deadline, once.
Returns ``{"monitor", "review", "thumbnails", "workers", "tracker"}``
booleans (True: it stopped), leaving out parts that never started.
Later calls return a copy of the first result. A Ctrl+C inside a step is
logged and the step is False; one between steps is re-raised after the
result (parts not reached are False) is stored and the ``atexit`` entry
removed.
"""
global _background_work_result
with _background_work_lock:
@@ -315,8 +327,10 @@ def _stop_background_work():
# A part whose global is set has started; False until its step says
# otherwise, so an interrupt between steps leaves an honest result.
reviews = thumbnails # the API also owns the review worker (#659)
started = (
("monitor", monitor),
("review", _review_worker_started(reviews) or None),
("thumbnails", thumbnails),
("workers", parallel.job_pool_started() or None),
("tracker", tracker),
@@ -349,6 +363,18 @@ def _stop_background_work():
result["monitor"] = _teardown_step(
"the image monitor", stop_monitor, logger
)
if reviews is not None:
def stop_reviews():
from .py.api.review_recording import REVIEW_STOP_SECONDS
return reviews.stop_review_worker(left(REVIEW_STOP_SECONDS))
# Always stopped, so no later output starts it; reported
# only when it ran (an image in hand may have started it).
stopped = _teardown_step("the review worker", stop_reviews, logger)
if "review" in result or _review_worker_started(reviews):
result["review"] = stopped
if thumbnails is not None:
def close_previews():
+17
View File
@@ -19,6 +19,10 @@ Pair prompts' empty category and tags, live in their own modules):
It also forgets the removal marks (#480) that hide nothing any more: the
file is gone or changed, under a readable source (#501, ``_stale_marks``).
#618's ``tag_cleanup`` (``database/tag_cleanup.py``) is planned from a tag
search's findings, never previewed here; its apply rechecks each target and
keeps the ones that changed instead of refusing the whole plan.
``preview_maintenance`` reads one snapshot on its own ``mode=ro`` connection
(``health.readonly_uri``) and closes it in ``finally``; files are looked at
after the snapshot ended. It returns a ``MaintenanceDraft``: the public plan
@@ -64,6 +68,9 @@ MAINTENANCE_OPERATIONS = (
# #550: fill old Pair prompts' empty category and tags
# (database/pair_metadata_repair.py).
"pair_metadata",
# #618: tags to clean up, found by a job and planned from its findings
# (database/tag_cleanup.py); never previewed without them.
"tag_cleanup",
)
MAX_DETAILS = 50 # detail rows a plan lists
MAX_RESULT_ROWS = 200 # changed records an apply describes (the job lists 200)
@@ -574,6 +581,9 @@ class MaintenanceOperations:
"""
if operation not in MAINTENANCE_OPERATIONS:
raise ValueError(f"Unknown maintenance operation {operation!r}")
if operation == "tag_cleanup":
# Planned from a find's findings (tag_cleanup.plan_tag_cleanup).
raise ValueError("tag_cleanup is planned from a tag search")
roots = [str(root) for root in roots]
if operation == "optimize":
return self._plan_optimize()
@@ -867,6 +877,8 @@ class MaintenanceOperations:
prompt operations also return ``kept``: every prompt the plan keeps,
``{prompt_id, reasons}`` in the review's wording (#550, #586); the
links a missing-links plan keeps are read by ``kept_links``.
``tag_cleanup`` (#618) does not compare the fingerprint: it rechecks
each target and returns every deleted and kept tag, uncapped.
"""
if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage":
raise ValueError(f"Unknown maintenance operation {operation!r}")
@@ -885,6 +897,11 @@ class MaintenanceOperations:
from .pair_metadata_repair import apply_pair_metadata
return apply_pair_metadata(conn, fingerprint, targets)
if operation == "tag_cleanup":
# #618: each target is rechecked; a changed one is kept.
from .tag_cleanup import apply_tag_cleanup
return apply_tag_cleanup(conn, targets)
if operation == "missing_links":
return self._apply_missing_links(
conn, fingerprint, targets, roots, list(marks)
+5 -21
View File
@@ -26,7 +26,7 @@ from .review_decisions import ReviewDecisionOperations
from .saved_views import SavedViewOperations
from .library_commands import LibraryCommandOperations
from .library_archive import LibraryArchiveOperations, delete_prompt_rows
from .vocabulary import VocabularyOperations
from .vocabulary import VocabularyOperations, bump_image_tag_bytes
from .execution_history import ExecutionHistoryOperations
from .execution_contexts import ExecutionContextOperations
from .execution_outputs import ExecutionOutputOperations
@@ -1262,26 +1262,10 @@ class PromptDatabase(
"has_more": (offset + limit) < total,
}
@staticmethod
def _bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads
as, so a Tag dialog opened before the change must see ``tag-conflict``
on Save instead of recreating the old name. Bumps the image index
revision once when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
# Vocabulary rename, merge and delete bump image tag revisions through
# the connection-level helper (database/vocabulary.py, shared with #618's
# tag cleanup).
_bump_image_tag_bytes = staticmethod(bump_image_tag_bytes)
@classmethod
def _move_tag_links(
+23 -1
View File
@@ -114,6 +114,10 @@ _PENDING_AT_STAT = (
f"JOIN {ITEMS_TABLE} i ON i.byte_id=b.id "
"WHERE f.locator=? AND b.size=? AND b.mtime_ns=? AND i.state='pending'"
)
# The newest pending item of the bytes verified at one stat (Inspect, #659).
_NEWEST_PENDING_AT_STAT = (
_PENDING_AT_STAT + " ORDER BY i.created_at DESC, i.rowid DESC LIMIT 1"
)
# Pending items of one file: the candidates a link settles.
_PENDING_OF_LOCATOR = (
f"SELECT i.id FROM {FILES_TABLE} f " # nosec B608
@@ -459,6 +463,24 @@ class ReviewOperations:
)
return row is not None
def review_item_at(self, locator: str, size: int, mtime_ns: int) -> dict | None:
"""Inspect's ``review`` facet of the bytes verified at this stat (#659).
``{"state": "pending", "item_id": ...}`` names the newest pending item
(any version); otherwise ``{"state": "decided"}`` when such bytes carry
a decided item; else None. Two indexed reads, no file access.
"""
_validate_locator(locator)
conn = self.model.get_connection()
row = conn.execute(
_NEWEST_PENDING_AT_STAT, (locator, size, mtime_ns)
).fetchone()
if row is not None:
return {"state": "pending", "item_id": row[0]}
if conn.execute(_DECIDED_AT, (locator, size, mtime_ns)).fetchone() is not None:
return {"state": "decided"}
return None
def review_file_linked(self, spellings) -> bool:
"""True when a saved row links the file under any of ``spellings``."""
with self._annotation_read() as conn:
@@ -536,7 +558,7 @@ class ReviewOperations:
"""Remove the pending, undecided items that offer nothing to choose.
``locators`` are files the caller found ambiguous without a choice
(fewer than two candidates carry a prompt). Of their items, one leaves
(no candidate carries a prompt). Of their items, one leaves
the queue only when its own stored evidence offers no choice either
(``evidence_offers_choice``) and it is still ``pending`` at revision 0
with no decision row, the same safe delete as
+10 -8
View File
@@ -215,22 +215,24 @@ def choosable(candidate: Any) -> bool:
# An item is worth a decision only when at least this many candidates offer
# a prompt; with fewer there is nothing to choose between (maintainer test of
# #284/#288: 39 items whose candidates were all "unresolved").
MIN_CHOOSABLE = 2
# a prompt; with none there is nothing to choose (maintainer test of
# #284/#288: 39 items whose candidates were all "unresolved"). One is enough
# (#657 addendum D1, 2026-11-20): the other branches stay listed, disabled,
# and the user may still leave the file unresolved.
MIN_CHOOSABLE = 1
def evidence_offers_choice(evidence: Any) -> bool:
"""False when stored evidence provably offers nothing to choose.
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates. A
limited item stores none, only ``candidate_total``; it may offer a choice
(more than ``MAX_CANDIDATES`` prompts) unless that total is too small.
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates (the
saver anchor's one pair, #390, counts like any other). A limited item
stores none, only ``candidate_total``; it may offer a choice unless that
total is too small.
"""
if not isinstance(evidence, dict):
return False
# The saver anchor's one pair (#390) is a suggestion to confirm.
needed = 1 if evidence.get("anchor") == "saver" else MIN_CHOOSABLE
needed = MIN_CHOOSABLE
if evidence.get("limited"):
total = evidence.get("candidate_total")
return type(total) is int and total >= needed
+440
View File
@@ -0,0 +1,440 @@
"""Tag cleanup: a registry of rules over the tag registry (#618).
Each ``TagRule`` finds tag ids on a read-only connection, rechecks one
reviewed target on the write connection and applies it there. ``RULES`` is
the registry; its order is the review's order and decides ownership: a tag
belongs to the first rule that finds it and is listed only there. Two rules
ship:
- ``comma``: tags whose name holds an ASCII or a fullwidth comma (a whole
list saved as one tag, usually from a LoRA's trained words). A tag whose
name starts with ``lora:`` is never one: it is the LoRA import's identity
tag, which the next import makes again (maintainer ruling, 2026-11-22).
Applying removes the tag from its prompts, pairs and images and deletes it.
- ``unused``: tags no prompt, saved pair or image carries. Deleted.
``find_tag_cleanup`` reads one ``mode=ro`` snapshot and returns every rule's
findings (at most ``MAX_FINDINGS`` held per rule, totals exact).
``plan_tag_cleanup`` re-reads the selected findings on another snapshot; one
whose fingerprint ``(tag_id, name, links)`` changed since the find is
protected, not planned. ``links`` hashes the sorted prompt ids, pair ids and
``(byte_id, position)`` rows carrying the tag, so a tag moved from one prompt
to another is seen. ``apply_tag_cleanup`` runs inside the caller's ``BEGIN
IMMEDIATE`` and rechecks each target: one that changed is kept with its
reason and the rest still apply (one edited tag must not block hundreds).
Saved views are never rewritten; a finding says how many name it. The
auto-tag marks (``media_image_autotags``) are never read or written.
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass
from typing import Callable, Optional
from .maintenance import (
MAX_DETAILS,
MaintenanceDraft,
_Fingerprint,
_plural,
_read_snapshot,
)
from .vocabulary import VocabularyOperations, _delete_tag
OPERATION = "tag_cleanup"
MAX_FINDINGS = 2000 # findings a find holds and lists per rule
COMMAS = (",", ",")
LORA_PREFIX = "lora:"
CHANGED_SINCE_SEARCH = "changed since the search"
NO_FILES = "No files are removed"
# Findings are listed by name (case-insensitive), then id.
_COMMA_SQL = (
"SELECT id FROM tags WHERE (instr(name, ?) > 0 OR instr(name, ?) > 0) "
"AND substr(name, 1, ?) != ? ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_WITH_IMAGES_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM media_image_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_ANNOTATION_TABLES = ("media_image_tags", "media_annotation_bytes")
@dataclass(frozen=True)
class TagRule:
"""One cleanup rule: its copy and its three functions."""
id: str
title: str
explanation: str
action_label: str
find: Callable[[sqlite3.Connection], list]
recheck: Callable[[sqlite3.Connection, dict], Optional[str]]
apply: Callable[[sqlite3.Connection, dict], None]
def _has_image_links(conn):
"""Whether the image annotation tables exist (else images link nothing)."""
found = conn.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
_ANNOTATION_TABLES,
).fetchone()[0]
return found == len(_ANNOTATION_TABLES)
def _links(conn, tag_id):
"""sha256 of the link rows carrying ``tag_id``: prompts, pairs, images."""
prompts = [
r[0]
for r in conn.execute(
"SELECT prompt_id FROM prompt_tags WHERE tag_id=? ORDER BY 1", (tag_id,)
)
]
pairs = [
r[0]
for r in conn.execute(
"SELECT pair_id FROM prompt_pair_tags WHERE tag_id=? ORDER BY 1",
(tag_id,),
)
]
images = []
if _has_image_links(conn):
images = [
[r[0], r[1]]
for r in conn.execute(
"SELECT byte_id, position FROM media_image_tags WHERE tag_id=? "
"ORDER BY 1, 2",
(tag_id,),
)
]
return _hash_links(prompts, pairs, images)
def _hash_links(prompts, pairs, images):
encoded = json.dumps([prompts, pairs, images], separators=(",", ":"))
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
NO_LINKS = _hash_links([], [], [])
def _find_comma(conn):
params = (*COMMAS, len(LORA_PREFIX), LORA_PREFIX)
return [row[0] for row in conn.execute(_COMMA_SQL, params)]
def _find_unused(conn):
sql = _UNUSED_WITH_IMAGES_SQL if _has_image_links(conn) else _UNUSED_SQL
return [row[0] for row in conn.execute(sql)]
def _identity_reason(conn, target):
"""``already deleted`` or ``renamed since the review``, else None."""
row = conn.execute("SELECT name FROM tags WHERE id=?", (target["tag_id"],))
row = row.fetchone()
if row is None:
return "already deleted"
if row[0] != target["name"]:
return "renamed since the review"
return None
def _recheck_comma(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "its links changed since the review"
return reason
def _recheck_unused(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "it is used now"
return reason
def _delete_target(conn, target):
"""Both shipped rules' apply: delete the tag; its links cascade."""
_delete_tag(conn, target["tag_id"])
def _apply_target(conn, target):
# Looked up at call time, so a test can stand in for the delete.
_delete_target(conn, target)
RULES = (
TagRule(
id="comma",
title="Tags containing a comma",
explanation=(
"A whole list saved as one tag, usually from a LoRA's trained words."
),
action_label=(
"Removes the tag from its prompts, pairs and images and deletes it."
),
find=_find_comma,
recheck=_recheck_comma,
apply=_apply_target,
),
TagRule(
id="unused",
title="Tags with no links",
explanation="No prompt, saved pair or image carries the tag.",
action_label="Deletes the tag.",
find=_find_unused,
recheck=_recheck_unused,
apply=_apply_target,
),
)
RULE_IDS = tuple(rule.id for rule in RULES)
_BY_ID = {rule.id: rule for rule in RULES}
def rule(rule_id):
"""The registered rule ``rule_id`` (KeyError when there is none)."""
return _BY_ID[rule_id]
def _saved_view_names(conn):
"""``{tag name: views naming it}`` from every saved view's state."""
exists = conn.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='saved_views'"
).fetchone()
if not exists:
return {}
counts = {}
for (state,) in conn.execute("SELECT state FROM saved_views"):
try:
tags = json.loads(state).get("tags") or []
except (TypeError, ValueError, AttributeError):
continue
for name in {tag for tag in tags if isinstance(tag, str)}:
counts[name] = counts.get(name, 0) + 1
return counts
def _finding(conn, rule_id, tag_id, views):
row = conn.execute("SELECT name FROM tags WHERE id=?", (tag_id,)).fetchone()
if row is None:
return None
counts = (
VocabularyOperations._tag_owner_counts(conn, tag_id)
if _has_image_links(conn)
else _counts_without_images(conn, tag_id)
)
return {
"rule": rule_id,
"tag_id": tag_id,
"name": row[0],
"prompts": counts["components_changed"],
"pairs": counts["pairs_changed"],
"images": counts["images_changed"],
"saved_views": views.get(row[0], 0),
"links": _links(conn, tag_id),
}
def _counts_without_images(conn, tag_id):
prompts = conn.execute(
"SELECT COUNT(DISTINCT prompt_id) FROM prompt_tags WHERE tag_id=?", (tag_id,)
).fetchone()[0]
pairs = conn.execute(
"SELECT COUNT(DISTINCT pair_id) FROM prompt_pair_tags WHERE tag_id=?",
(tag_id,),
).fetchone()[0]
return {"components_changed": prompts, "pairs_changed": pairs, "images_changed": 0}
def _owners_text(finding):
parts = [
_plural(finding[key], noun)
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if finding[key]
]
return " · ".join(parts)
def finding_detail(finding):
"""The server's line for a finding: ``3 prompts · 1 pair``, ``no links``,
with `` · in 1 saved view`` when a saved view names it."""
detail = _owners_text(finding) or "no links"
views = finding.get("saved_views", 0)
if views:
detail += f" · in {_plural(views, 'saved view')}"
return detail
def find_tag_cleanup(db_path):
"""Every rule's findings on one ``mode=ro`` snapshot (blocking, read-only).
``{"rules": {rule_id: [finding, ...]}, "totals": {rule_id: int}}``:
findings by name (case-insensitive), then id; at most ``MAX_FINDINGS``
held per rule, totals exact. A tag is listed under the first rule that
finds it only.
"""
def read(conn):
owned = set()
views = _saved_view_names(conn)
rules, totals = {}, {}
for item in RULES:
ids = [tag_id for tag_id in item.find(conn) if tag_id not in owned]
owned.update(ids)
totals[item.id] = len(ids)
findings = []
for tag_id in ids[:MAX_FINDINGS]:
finding = _finding(conn, item.id, tag_id, views)
if finding is not None:
findings.append(finding)
rules[item.id] = findings
return {"rules": rules, "totals": totals}
return _read_snapshot(db_path, read)
def _target(finding):
return {
key: finding[key]
for key in (
"rule",
"tag_id",
"name",
"prompts",
"pairs",
"images",
"saved_views",
"links",
)
}
def _scope_label(targets):
if not targets:
return "No tags to delete"
prompts = sum(t["prompts"] for t in targets)
pairs = sum(t["pairs"] for t in targets)
images = sum(t["images"] for t in targets)
return (
f"Delete {_plural(len(targets), 'tag')} (removed from "
f"{_plural(prompts, 'prompt')}, {_plural(pairs, 'pair')} and "
f"{_plural(images, 'image')})"
)
def plan_tag_cleanup(db_path, held, tag_ids_by_rule):
"""The reviewed plan for the selected findings (blocking, read-only).
``held`` is a ``find_tag_cleanup`` result and ``tag_ids_by_rule``
``{rule_id: [tag_id, ...]}`` of its findings (the caller validated
both). Each selected finding is read again on one snapshot; one whose
``(tag_id, name, links)`` changed since the find is protected
(``changed since the search``), not planned. Targets follow the
registry's order, then the find's.
"""
reviewed = {
(finding["rule"], finding["tag_id"]): finding
for findings in held["rules"].values()
for finding in findings
}
def read(conn):
views = _saved_view_names(conn)
targets, protected = [], []
for item in RULES:
for tag_id in tag_ids_by_rule.get(item.id, ()):
before = reviewed[(item.id, tag_id)]
now = _finding(conn, item.id, tag_id, views)
same = now is not None and (now["name"], now["links"]) == (
before["name"],
before["links"],
)
if same:
targets.append(_target(now))
else:
protected.append(
{**_target(before), "reason": CHANGED_SINCE_SEARCH}
)
return targets, protected
targets, protected = _read_snapshot(db_path, read)
fingerprint = _Fingerprint(OPERATION)
for target in targets:
fingerprint.add([target["rule"], target["tag_id"], target["name"]])
fingerprint.add(target["links"])
reasons = (
[f"{_plural(len(protected), 'tag')} {CHANGED_SINCE_SEARCH}"]
if protected
else []
)
draft = MaintenanceDraft(
operation=OPERATION,
fingerprint=fingerprint.hexdigest(),
targets=targets,
scope={"count": len(targets), "label": _scope_label(targets)},
protected={"count": len(protected), "reasons": reasons},
media={"deletes_files": False, "label": NO_FILES},
details=[
{
"label": target["name"],
"detail": f"{rule(target['rule']).title} · {finding_detail(target)}",
}
for target in targets[:MAX_DETAILS]
],
)
draft.held = protected
return draft
def held_rows(draft):
"""The findings a plan protected, each with its reason."""
return list(getattr(draft, "held", ()))
def _empties_legacy_tags(conn):
"""Whether deleting one more tag would empty ``tags`` while a prompt still
holds legacy JSON tags: the start-up migration would then bring every
legacy tag and link back (``models._migrate_json_tags_to_junction``)."""
if conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0] > 1:
return False
legacy = conn.execute(
"SELECT 1 FROM prompts WHERE tags IS NOT NULL AND tags != '' "
"AND tags != '[]' LIMIT 1"
).fetchone()
return legacy is not None
LAST_TAG = "kept so the old tag migration does not run again"
def apply_tag_cleanup(conn, targets):
"""Apply the reviewed targets in the caller's transaction (blocking).
Each target's rule rechecks it on ``conn``; one that changed is kept with
its reason and the rest still apply. ``{"changed": n, "rows": [every
deleted target], "kept": [{...target, "reason"}]}``. Any exception
propagates, so the caller's transaction rolls back as a whole.
"""
changed, rows, kept = 0, [], []
for target in targets:
item = rule(target["rule"])
reason = item.recheck(conn, target)
if reason is None and _empties_legacy_tags(conn):
reason = LAST_TAG
if reason is not None:
kept.append({**target, "reason": reason})
continue
item.apply(conn, target)
changed += 1
rows.append(dict(target))
return {"changed": changed, "rows": rows, "kept": kept}
+33 -2
View File
@@ -295,6 +295,38 @@ def _category_after(after: object) -> tuple[int, str] | None:
return after[0], after[1]
def bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads as,
so a Tag dialog opened before the change must see ``tag-conflict`` on Save
instead of recreating the old name. Bumps the image index revision once
when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
def _delete_tag(conn: sqlite3.Connection, tag_id: int) -> None:
"""Delete the registry row *tag_id* in the caller's transaction.
Image sets carrying it get a new tag revision first; its component, pair
and image links cascade. Shared by ``delete_vocabulary_tag`` and the tag
cleanup rules (#618, ``database/tag_cleanup.py``).
"""
bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
class VocabularyOperations:
"""Vocabulary reads and tag commands.
@@ -405,8 +437,7 @@ class VocabularyOperations:
epoch = self._library_epoch(conn, expected_epoch)
self._vocabulary_identity(conn, epoch, tag_id, name)
counts = self._tag_owner_counts(conn, tag_id)
self._bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
_delete_tag(conn, tag_id)
return {"library_epoch": epoch, "deleted": True, **counts}
def vocabulary_tag_impact(self, tag_id: int) -> dict | None:
+8 -6
View File
@@ -12,7 +12,7 @@ code. This plan proposes implementation order and acceptance gates.
- The native Prompt Library merged in [#210](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/210) for [#208](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/208): one positive parent, saved negative variants, full selected text and a shared filtered image gallery. It does not invent chronological runs from counters or scan dates.
- [Durable history storage](prompt-history-storage.md) records job attempts and outcomes from [#212](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/212), frozen prompt contexts from [#213](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/213), and observed run-owned output locators from [#214](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/214). Those locators do not verify file bytes or establish gallery-image associations. That association contract and the chronological execution timeline remain pending under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209).
- [#215](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/215) brings the shell, Images and natural-height Prompt Library presentation into the approved geometry and themes while retaining their existing operations. [#216](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/216) adds the shared current-file inspector with exact generation facts, scoped provenance, raw/download evidence and loaded-collection viewer controls, including a slideshow that pauses at native video. This delivery does not establish whole-application parity, change the default entry point or constitute a release. Recorded chronological run/context browsing continues under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209); image tagging/review, System consolidation and remaining organization capabilities continue under #196.
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable from Overview; 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
@@ -69,14 +69,16 @@ regression coverage with mockup-only tests.
## GitHub and release gates
Extend existing required workflows: the Python 3.10–3.13 matrix on Linux,
Windows and macOS; 85% Python coverage; formatting; frontend units and per-file
coverage floors; vendor checks; browser workflows; real ComfyUI compatibility.
Extend existing required workflows: the Python suite on Linux (3.12 on a pull
request, 3.12–3.14 in the merge queue; Windows 3.12–3.14 runs in `portability.yml`
and does not gate a merge; macOS is not tested in CI, #571); 85% Python coverage;
formatting; frontend units and per-file coverage floors; vendor checks; browser
workflows; real ComfyUI compatibility. Python 3.12 is the floor.
Publish traces, screenshots, logs and coverage artifacts on failures. See
[TESTING.md](../TESTING.md) for commands and fixture isolation requirements.
Every PR must map acceptance criteria to tests, report relevant checks and include
screenshots for visual changes. All required checks must pass before merging.
Every PR must map acceptance criteria to tests, report relevant checks and describe
visual changes in words; never attach screenshots or other images to a PR. All required checks must pass before merging.
Use maintainer live review at meaningful visual and host-integration milestones;
capture discovered regressions in automated tests. Notify the maintainer when
Python changes require a ComfyUI restart.
+4 -2
View File
@@ -99,19 +99,21 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
"prepend_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to prepend to the main prompt (connected STRING "
"nodes will be added before the main text)"
)
),
},
),
"append_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to append to the main prompt (connected STRING "
"nodes will be added after the main text)"
)
),
},
),
"save_to_library": SAVE_TO_LIBRARY_INPUT,
+1 -35
View File
@@ -7,7 +7,7 @@ duplicate code in prompt_manager.py and prompt_manager_text.py.
"""
import os
from typing import Any, Dict, List, Optional
from typing import Any, Dict, Optional
try:
from .utils.logging_config import get_logger
@@ -396,40 +396,6 @@ class PromptManagerBase:
tags = [tag.strip() for tag in tags_string.split(",") if tag.strip()]
return tags if tags else None
def _search_prompts(self, search_text: str = "") -> List[Dict[str, Any]]:
"""Search for past prompts by text content.
Args:
search_text: Text to search for in prompt database
Returns:
List of matching prompt dictionaries with metadata
"""
try:
if not search_text or not search_text.strip():
return []
try:
from .py.config import PromptManagerConfig
max_results = PromptManagerConfig.MAX_SEARCH_RESULTS
except Exception:
max_results = 100
results = self.db.search_prompts(
text=search_text.strip(),
category=None,
tags=None,
rating_min=None,
limit=max_results,
)
return results
except Exception as e:
self.logger.error(f"Error searching prompts: {e}")
return []
def _start_gallery_system(self):
"""Initialize and start the gallery monitoring system."""
try:
+45 -50
View File
@@ -23,6 +23,7 @@ Split into domain-specific mixins for maintainability:
- LibraryDeleteRoutesMixin: the Library's Delete… (archive paired) and Restore
- WorkflowStorageRoutesMixin: store each workflow once, then Reclaim space
- DuplicateFilesMixin: duplicate image files as find and removal jobs
- TagCleanupMixin: tag cleanup (#618) as a find job, its findings and a plan
- LoraImportRoutesMixin: the reviewed, staged LoRA reference import job
"""
@@ -30,7 +31,6 @@ import asyncio
import datetime
import functools
import gzip as gzip_module
import json
import math
import ntpath
import os
@@ -41,6 +41,7 @@ from pathlib import Path
from aiohttp import web
from PIL import Image
from . import json_body as _json_body
from .prompts import PromptRoutesMixin
from .revalidation import revalidated_response
from .pairs import PairRoutesMixin
@@ -74,6 +75,7 @@ from .maintenance import MaintenanceRoutesMixin
from .backup_restore import BackupRestoreRoutesMixin
from .workflow_storage import WorkflowStorageRoutesMixin
from .duplicate_files import DuplicateFilesMixin
from .tag_cleanup import TagCleanupMixin
from .maintenance_plans import PlanStore
from .jobs import JobRegistry
from .logging_routes import LoggingRoutesMixin
@@ -89,6 +91,7 @@ from .source_rescope import SourceRescopeMixin
try:
from ...database.operations import PromptDatabase
from ...utils.exif_text import exif_text
from ...utils.logging_config import get_logger
from ...utils.native_memory import release_free_memory
from ...utils.png_text import png_text
@@ -100,6 +103,7 @@ except ImportError:
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
from database.operations import PromptDatabase
from utils.exif_text import exif_text
from utils.logging_config import get_logger
from utils.native_memory import release_free_memory
from utils.png_text import png_text
@@ -212,44 +216,10 @@ def _resolve_static_file(root, filepath, allowed=STATIC_MIME_TYPES):
# ── JSON request bodies ────────────────────────────────────────────────
JSON_BODY_MAX_BYTES = 1_000_000
_JSON_READ_CHUNK = 64 * 1024
def _json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
async def _read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
"""Read and parse a JSON object body of at most ``max_bytes``.
The body is read in chunks so an oversized or chunked upload is refused
as soon as it crosses the cap rather than buffered whole.
Returns:
(data, None) on success, or (None, response) where ``response`` is a
413 (body too large) or 400 (invalid JSON, or not a JSON object).
"""
too_large = _json_error(f"Request body too large (max {max_bytes} bytes)", 413)
declared = request.content_length
if declared is not None and declared > max_bytes:
return None, too_large
chunks = []
size = 0
async for chunk in request.content.iter_chunked(_JSON_READ_CHUNK):
size += len(chunk)
if size > max_bytes:
return None, too_large
chunks.append(chunk)
try:
data = json.loads(b"".join(chunks).decode("utf-8"))
except (UnicodeDecodeError, ValueError):
return None, _json_error("Request body must be valid JSON", 400)
if not isinstance(data, dict):
return None, _json_error("Request body must be a JSON object", 400)
return data, None
# One bounded reader (json_body.py); these names stay for the mixins and tests.
JSON_BODY_MAX_BYTES = _json_body.JSON_BODY_MAX_BYTES
_json_error = _json_body.json_error
_read_json_body = _json_body.read_json_body
# ── Gzip compression middleware ────────────────────────────────────────
@@ -306,6 +276,17 @@ async def _gzip_middleware(request, handler):
return response
def _workspace_redirect(route: str) -> web.Response:
"""Send the browser of a retired page's URL to a workspace route (#668).
The Location is relative to the old URL, so a reverse-proxy mount prefix
in front of ``/prompt_manager/`` is kept, and 302 is not stored for good.
A plain response, not a raised ``HTTPFound``, so the host's middlewares
see it like any other.
"""
return web.Response(status=302, headers={"Location": f"workspace{route}"})
class PromptManagerAPI(
PairRoutesMixin,
LibraryRoutesMixin,
@@ -338,6 +319,7 @@ class PromptManagerAPI(
BackupRestoreRoutesMixin,
WorkflowStorageRoutesMixin,
DuplicateFilesMixin,
TagCleanupMixin,
LoggingRoutesMixin,
LogCleanupMixin,
DiagnosticsReportMixin,
@@ -415,6 +397,9 @@ class PromptManagerAPI(
# Duplicate-file finds by job id, with the groups each one holds for
# review (py/api/duplicate_files.py); the last few only.
self._duplicate_finds = {}
# Tag cleanup finds by job id with the findings each holds (#618,
# py/api/tag_cleanup.py); None while a find runs or after it failed.
self._tag_cleanup_finds = {}
# The last System health report this session and the database
# generation it describes, bumped when a restore replaces self.db
# (py/api/system.py).
@@ -653,17 +638,24 @@ class PromptManagerAPI(
async def serve_web_ui(request):
return self._serve_html_page(request, "index.html", "Web UI", cache=False)
@routes.get("/prompt_manager/gallery.html")
async def serve_gallery_ui(request):
return self._serve_html_page(request, "metadata.html", "Gallery")
# The old admin, gallery and metadata pages are gone (#668, D207); their
# URLs stay and lead into the workspace.
@routes.get("/prompt_manager/admin")
async def serve_admin_ui(request):
return self._serve_html_page(request, "admin.html", "Admin UI")
@routes.get("/prompt_manager/gallery.html")
async def redirect_old_metadata_page(request):
return _workspace_redirect("#/inspect")
@routes.get("/prompt_manager/gallery")
async def serve_gallery_admin_ui(request):
return self._serve_html_page(request, "gallery.html", "Gallery")
async def redirect_old_gallery_page(request):
return _workspace_redirect("#/images")
# The dashboard's tag bookmarks (admin#/tags/a,b?mode=or) live in the
# hash, which only the browser sees: this page maps it and moves on.
@routes.get("/prompt_manager/admin")
async def serve_old_admin_redirect(request):
return self._serve_html_page(
request, "admin-redirect.html", "Workspace redirect"
)
# ── Static file serving ───────────────────────────────────────
@@ -705,6 +697,7 @@ class PromptManagerAPI(
self._register_maintenance_routes(routes)
self._register_backup_restore_routes(routes)
self._register_duplicate_routes(routes)
self._register_tag_cleanup_routes(routes)
self._register_logging_routes(routes)
self._register_autotag_routes(routes)
self._register_lora_routes(routes)
@@ -1018,9 +1011,11 @@ class PromptManagerAPI(
return []
def _extract_comfyui_metadata(self, image_path):
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
PNG text is read without decoding the pixels (``utils.png_text``, #523).
PNG text is read without decoding the pixels (``utils.png_text``, #523);
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
``utils.exif_text``.
Videos go through ffprobe (see utils/video_metadata). Unreadable files
are a warning, not an error: a scan over a large output tree meets
@@ -1030,7 +1025,7 @@ class PromptManagerAPI(
return read_video_metadata(image_path)
try:
with Image.open(image_path) as img:
return png_text(img)
return png_text(img) or exif_text(img)
except Exception as e:
self.logger.warning(
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
+18 -27
View File
@@ -43,6 +43,7 @@ try:
in_trash_folder,
is_skipped_folder,
)
from ...utils.media_formats import collectable
except ImportError:
from utils import exit_signal
from utils.media_folders import (
@@ -50,6 +51,7 @@ except ImportError:
in_trash_folder,
is_skipped_folder,
)
from utils.media_formats import collectable
try:
from ...database.image_removal import mark_hides
@@ -100,7 +102,7 @@ try:
except ImportError:
from database.library import display_title
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff")
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".avif")
VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v", ".wmv")
SCAN_BATCH_SIZE = 50 # Files per executor call during the output scan
# '<db>.backup_*' files kept next to the live database: one pool for the
@@ -156,7 +158,9 @@ def _collect_media_files(output_dirs, extensions):
and not os.path.islink(os.path.join(current, d))
)
for name in sorted(filenames):
if os.path.splitext(name)[1].lower() not in wanted:
suffix = os.path.splitext(name)[1].lower()
# #652: AVIF is listed but only collected where Pillow reads it.
if suffix not in wanted or not collectable(suffix):
continue
full = os.path.join(current, name)
if os.path.islink(full) or not os.path.isfile(full):
@@ -1699,7 +1703,8 @@ class AdminRoutesMixin:
review (best effort, counted in ``review`` when given); one a saved
row already links is reported ``unchanged`` and never queued. An
ambiguous file with nothing to choose is reported ``unresolved`` and
its pending items without a choice leave the queue.
its pending items without a choice leave the queue. The decision is
``review_dispatch``'s, shared with the monitor's review worker (#659).
"""
counts = dict.fromkeys(SCAN_COUNT_KEYS, 0)
@@ -1713,14 +1718,12 @@ class AdminRoutesMixin:
if self._scan_job and self._scan_job.cancelled:
break
counts["processed"] += 1
ambiguous, untraced, records = [], [], {}
records = {}
try:
outcome = self._ingest_scanned_file(
media_file,
metadata,
detailed=True,
ambiguous=ambiguous,
untraced=untraced,
records=records,
history=history,
)
@@ -1729,24 +1732,9 @@ class AdminRoutesMixin:
counts["failed"] += 1
note(media_file, "error")
continue
if ambiguous and outcome == "ambiguous":
if self._review_file_linked(media_file, roots):
outcome = "unchanged" # already linked: not a review case
else:
# The records name the item versions that count; the
# saver anchor (#390) is checked on the captured bytes.
self._record_scanned_review(
media_file,
roots,
review,
scanned=(records.get("canonical"), None),
)
elif untraced and outcome == "unresolved":
# Untraced by the default profile: the inspection profile may
# still offer a choice (queued for review, never linked).
outcome = self._untraced_scan_outcome(
media_file, roots, records.get("canonical"), review
)
outcome, _recorded = self.review_dispatch(
media_file, roots, records.get("decision"), outcome, review
)
if outcome is None:
note(media_file, None)
continue
@@ -1783,11 +1771,12 @@ class AdminRoutesMixin:
``ambiguous`` is a list, ``media_file`` is appended to it; only a file
that then returns ``"ambiguous"`` (nothing linked it) is a Needs
review case. An ambiguous result with nothing to choose
(``reviewable`` is False: fewer than two candidates carry a prompt)
(``reviewable`` is False: no candidate carries a prompt)
goes to ``untraced`` instead and returns ``"unresolved"`` when nothing
links it. The parsed records of either ambiguous file go to
``records["canonical"]`` when ``records`` is a dict. ``history`` is
the batch's lazy recorded-history lookup.
``records["canonical"]`` when ``records`` is a dict, and the ladder's
``Decision`` to ``records["decision"]`` (``review_dispatch``'s input).
``history`` is the batch's lazy recorded-history lookup.
"""
path = str(media_file)
if history is None: # one file: history is still asked once
@@ -1800,6 +1789,8 @@ class AdminRoutesMixin:
lookup=functools.partial(history.recorded, path),
policy=Policy.SCAN,
)
if records is not None:
records["decision"] = decision
if decision.kind in (NOT_SAVED, NOT_SAVED_WIRED):
# Save to library off (#90): no write, recorded-run fallback or
# Needs review item
+1
View File
@@ -91,6 +91,7 @@ _PREVIEW_TYPES = {
".bmp": "image/bmp",
".tiff": "image/tiff",
".tif": "image/tiff",
".avif": "image/avif", # #652
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
+8 -3
View File
@@ -25,8 +25,10 @@ from .. import model_gate
try:
from ...utils.media_folders import in_trash_below_roots, is_skipped_folder
from ...utils.media_formats import collectable
except ImportError:
from utils.media_folders import in_trash_below_roots, is_skipped_folder
from utils.media_formats import collectable
from aiohttp import web
@@ -156,8 +158,9 @@ def public_models(status: dict, loaded_type: Optional[str]) -> dict:
# Only these may be handed to the tagging engine or listed by the scanner.
# #652: AVIF is listed and skipped where Pillow cannot read it (collectable).
_MEDIA_EXTENSIONS = frozenset(
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif"}
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif", ".avif"}
)
# Bounds for scan_output_dir: a runaway output tree must not pin the server.
_SCAN_MAX_FILES = 50_000
@@ -945,7 +948,8 @@ class AutotagRoutesMixin:
def _resolve_allowed_image_path(self, raw_path: str) -> Optional[str]:
"""Return the real path when it is a media file inside an output directory."""
if Path(str(raw_path)).suffix.lower() not in _MEDIA_EXTENSIONS:
suffix = Path(str(raw_path)).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
return None
roots = list(self._get_all_output_dirs())
for output_dir in roots:
@@ -1449,7 +1453,8 @@ class AutotagRoutesMixin:
if not is_skipped_folder(name) and depth + 1 <= _SCAN_MAX_DEPTH
)
for name in sorted(filenames):
if Path(name).suffix.lower() not in _MEDIA_EXTENSIONS:
suffix = Path(name).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
continue
candidate = Path(dirpath) / name
if candidate.is_symlink():
+35 -1
View File
@@ -3,7 +3,7 @@
import asyncio
import base64
import binascii
from functools import wraps
from functools import partial, wraps
import json
import os
import re
@@ -31,7 +31,9 @@ from .inspection_service import (
CurrentFileChanged,
image_tags_reader,
inspect_current_file,
review_reader,
)
from .admin import _scan_roots
from .images import image_category_key
try:
@@ -717,6 +719,37 @@ class HistoryRoutesMixin:
)
return OWN_CATEGORY_UNREAD
def _history_review(self, target) -> Callable:
"""The ``review`` reader of a reported current file (#659, C4).
Located as the scan locates it (``_review_location`` over the scan
roots, resolved like the canonical target), only when the inspector
asks; a file under no scan root reads None. A file reached through a
linked subfolder is keyed by its resolved path here, so an item the
scan stored under the linked spelling is not found (None, no choice).
A file without an item is recorded first through the review worker's
path (#657 addendum D2). The read closes its connection, as this
route's other reads do.
"""
def read(size: int, mtime_ns: int) -> dict | None:
roots = _scan_roots(
[os.path.realpath(root) for root in self._get_all_output_dirs()]
)
located = self._review_location(target, roots)
if located is None:
return None
locator = os.path.normcase(located[3])
return review_reader(
self.db,
locator,
self.logger,
close=True,
record=partial(self.inspect_review_file, str(target)),
)(size, mtime_ns)
return read
async def _history_current(
self, request: web.Request, kind: str
) -> web.StreamResponse:
@@ -793,6 +826,7 @@ class HistoryRoutesMixin:
recorded=recorded_output_lookup(
db, close=True, reference=receipt["reference"]
),
review=self._history_review(resolved.canonical_target),
)
_reauthorize_current_target(resolved, scope)
identity = {
+2 -1
View File
@@ -259,7 +259,8 @@ def parse_image_tag_request(data: dict):
``filter`` (a listing query object, parse_listing_filter) may stand in for
``targets``; the start resolves it.
"""
fields = _FIELDS.get(data.get("mode"))
mode = data.get("mode")
fields = _FIELDS.get(mode) if isinstance(mode, str) else None
if fields is None:
return None, bad_request('mode must be "add" or "auto"')
fields = fields | {"filter" if "filter" in data else "targets"}
+43 -29
View File
@@ -25,6 +25,7 @@ from aiohttp import web
from PIL import Image, UnidentifiedImageError
from .jobs import MAX_OUTCOME_ROWS, THUMBNAILS_JOB_KIND
from .json_body import BodyTooLarge, json_error, read_json_object
from . import gallery_listing
from .gallery_listing import (
DISCARDED,
@@ -56,6 +57,7 @@ from .inspection_service import (
VIDEO_EXTENSIONS,
image_tags_reader,
inspect_current_file,
review_reader,
)
try:
@@ -74,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,
@@ -107,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,
@@ -322,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.
@@ -548,7 +555,6 @@ def _thumbnail_is_fresh(src, dst):
MAX_GALLERY_FILES = 50_000
MAX_BULK_LIMIT = 5_000
MAX_JSON_BODY_BYTES = 1024 * 1024
_READ_CHUNK = 64 * 1024
# Guards the first load of an API's workspace keys (#430, _workspace_keys).
@@ -717,36 +723,17 @@ def _workspace_cursor_key(token: str, scope: str, order: str, secret: bytes) ->
raise ValueError("Invalid gallery cursor; refresh the gallery") from None
class _BodyTooLarge(Exception):
"""Raised when a request body exceeds MAX_JSON_BODY_BYTES."""
def _json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
# The shared bounded reader, at this module's own cap.
_BodyTooLarge = BodyTooLarge
_json_error = json_error
async def _read_json_body(request):
"""Read a JSON object body in bounded chunks.
"""The JSON object body, or raise _BodyTooLarge past MAX_JSON_BODY_BYTES.
Raises _BodyTooLarge past MAX_JSON_BODY_BYTES (declared or streamed) and
ValueError when the body is not a JSON object.
Raises ValueError when the body is not a JSON object.
"""
limit = MAX_JSON_BODY_BYTES
if request.content_length is not None and request.content_length > limit:
raise _BodyTooLarge()
chunks, size = [], 0
while True:
chunk = await request.content.read(_READ_CHUNK)
if not chunk:
break
size += len(chunk)
if size > limit:
raise _BodyTooLarge()
chunks.append(chunk)
data = json.loads(b"".join(chunks).decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("JSON body must be an object")
return data
return await read_json_object(request, MAX_JSON_BODY_BYTES)
async def _json_body_or_error(request):
@@ -969,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
@@ -1002,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
@@ -4149,6 +4139,9 @@ class ImageRoutesMixin:
roots[index], Path(relative).parts
),
recorded=recorded_output_lookup(self.db),
review=self._inspection_review(
index, outputs, roots[index], Path(relative).parts
),
)
except CurrentFileChanged:
return None
@@ -4193,6 +4186,27 @@ class ImageRoutesMixin:
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
return image_tags_reader(self.db, locator, self.logger)
def _inspection_review(
self, index: int, outputs: list, root: Path, parts: tuple
) -> Callable | None:
"""The inspector's ``review`` reader for one rooted file (#659, C4).
Keyed as review items are (the normcased realpath of the root joined
with the relative path). Only an output root is a scan root; a root
past the output folders (a LoRA root) gives None. A file without an
item is recorded first through the review worker's path (#657 D2).
"""
if index >= len(outputs):
return None
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
path = os.path.join(str(root), *parts)
return review_reader(
self.db,
locator,
self.logger,
record=functools.partial(self.inspect_review_file, path),
)
def _read_own_category(self, sources, path):
"""One file's own category, None, or OWN_CATEGORY_UNREAD (blocking).
+73
View File
@@ -42,6 +42,8 @@ IMAGE_EXTENSIONS = frozenset(
".bmp",
".tiff",
".tif",
# #652: served and inspected; the scan collects it where Pillow reads it
".avif",
".mp4",
".webm",
".mov",
@@ -122,6 +124,67 @@ def image_tags_reader(
return read
def review_reader(
db: Any,
locator: str,
logger: Any,
*,
close: bool = False,
record: Callable[[dict | None], Any] | None = None,
) -> Callable[[int, int], dict | None]:
"""The inspector's ``review`` reader for one file *locator* (#659, C4).
The returned function takes the inspection's own stable stat and answers
the file's Needs review item at exactly that ``(size, mtime_ns)``
(``review_item_at``): pending with its id, decided, or None. A failed
read is None, never an error. ``close`` closes the calling thread's
connection afterwards, for routes that close theirs (History).
*record*, when given, is called with the found facet when there is no
item at that stat or a pending one (#657 addendum D2: Inspect records the
item, or records a stale one again, through the review worker's own
per-file path; the caller decides whether anything needs doing). The
item is then read once more, also after a failed recording (the worker
may have recorded it meanwhile). A recording error is logged.
"""
def read(size: int, mtime_ns: int) -> dict | None:
try:
found = db.review_item_at(locator, size, mtime_ns)
if record is not None and (found is None or found["state"] == "pending"):
_record(record, found, logger)
found = db.review_item_at(locator, size, mtime_ns)
return found
except Exception:
logger.warning("Inspection review item could not be read", exc_info=True)
return None
finally:
if close:
db.model.close()
return read
def _record(record: Callable[[dict | None], Any], found, logger: Any) -> None:
"""Run *record* for the *found* facet; an error is logged, not raised."""
try:
record(found)
except Exception:
logger.warning(
"Inspection could not add the file to Needs review", exc_info=True
)
def _asks_review(evidence: dict, library: dict) -> bool:
"""Whether Inspect may offer a choice: an ambiguous role, an unlinked file."""
prompts = evidence.get("prompts") or {}
ambiguous = any(
isinstance(side, dict) and side.get("status") == "ambiguous"
for side in prompts.values()
)
return ambiguous and isinstance(library, dict) and library.get("status") == "none"
def inspect_current_file(
path: Path,
*,
@@ -130,6 +193,7 @@ def inspect_current_file(
library: dict,
image_tags: Callable[[int, int], dict] | None = None,
recorded: Callable[[Path], Any] | None = None,
review: Callable[[int, int], dict | None] | None = None,
) -> dict:
"""Current-file evidence read between two equal stats of *path*.
@@ -139,6 +203,9 @@ def inspect_current_file(
*recorded*, when given, is asked within the same stat window for what
recorded run history knows about *path* (``RecordedOutput`` or None: the
save node that wrote it and the texts PromptManager recorded, #386).
*review*, when given, is called with the same stat only when a role is
ambiguous and ``library["status"]`` is ``none``; its answer (or None) is
returned as ``review`` (#659).
"""
before = _current_file_facts(path)
try:
@@ -173,6 +240,12 @@ def inspect_current_file(
recorded_saver_id=run.saver_id if run is not None else None,
recorded_texts=run.texts if run is not None else None,
)
if review is not None:
facets["review"] = (
review(before.st_size, before.st_mtime_ns)
if _asks_review(evidence, library)
else None
)
return {
"file": {
"observation": "current-file",
+4
View File
@@ -124,6 +124,10 @@ MODEL_DOWNLOAD_JOB_KIND = "model_download"
DUPLICATES_JOB_KIND = "duplicates"
DUPLICATE_GROUP_NAMES = ("groups_found",)
DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors")
# Tag cleanup (#618, py/api/tag_cleanup.py): the find is a ``read`` job that
# holds its findings; the reviewed apply is a ``maintenance`` job.
TAG_CLEANUP_JOB_KIND = "tag_cleanup"
TAG_CLEANUP_GROUP_NAMES = ("found",)
# The workspace Library's Delete… (#443, py/api/library_delete.py): a
# ``records`` hold around its safety backup and write.
PROMPT_DELETE_JOB_KIND = "prompt_delete"
+60
View File
@@ -0,0 +1,60 @@
"""The one bounded reader for JSON object request bodies.
The body is read in chunks, so an oversized or chunked upload is refused as
soon as it crosses the cap rather than buffered whole. ``read_json_object``
raises; ``read_json_body`` answers with the API's ``{"success": false}``
envelope.
"""
import json
from aiohttp import web
JSON_BODY_MAX_BYTES = 1_000_000
_READ_CHUNK = 64 * 1024
INVALID_JSON = "Request body must be valid JSON"
NOT_AN_OBJECT = "Request body must be a JSON object"
class BodyTooLarge(Exception):
"""The request body is longer than the reader's ``max_bytes``."""
def json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
async def read_json_object(request, max_bytes=JSON_BODY_MAX_BYTES):
"""The request's JSON object body of at most ``max_bytes``.
Raises:
BodyTooLarge: the declared or streamed body crosses ``max_bytes``.
ValueError: the body is not UTF-8 JSON (``INVALID_JSON``) or not a
JSON object (``NOT_AN_OBJECT``).
"""
declared = request.content_length
if declared is not None and declared > max_bytes:
raise BodyTooLarge()
chunks, size = [], 0
async for chunk in request.content.iter_chunked(_READ_CHUNK):
size += len(chunk)
if size > max_bytes:
raise BodyTooLarge()
chunks.append(chunk)
try:
data = json.loads(b"".join(chunks).decode("utf-8"))
except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
raise ValueError(INVALID_JSON) from None
if not isinstance(data, dict):
raise ValueError(NOT_AN_OBJECT)
return data
async def read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
"""``(data, None)``, or ``(None, response)`` with a 413 or 400 refusal."""
try:
return await read_json_object(request, max_bytes), None
except BodyTooLarge:
return None, json_error(f"Request body too large (max {max_bytes} bytes)", 413)
except ValueError as exc:
return None, json_error(str(exc), 400)
+24 -3
View File
@@ -6,9 +6,12 @@ current imports, those a saved pair uses and the example images an import
would download. It writes nothing and requests nothing. It answers a
``Plan`` (the maintenance plan's shape, ``py/api/maintenance.py``) plus
``{lora_files, with_metadata, skipped, with_local_media, current_imports,
blocked_by_pairs, planned_downloads, network:{planned_downloads, api_key},
layout}`` (#355: ``layout`` says which LoraManager settings file, storage mode
and library the import read, and ``error`` when they cannot be used). A plan
blocked_by_pairs, planned_downloads, trigger_tags, trigger_not_tags,
network:{planned_downloads, api_key}, layout}`` (#355: ``layout`` says which
LoraManager settings file, storage mode and library the import read, and
``error`` when they cannot be used; #618: ``trigger_tags`` and
``trigger_not_tags`` count the trained-words entries that become tags and
those that are lists or sentences, which the job log repeats). A plan
that saved pairs block, or whose layout is unusable, carries no token
(nothing can be applied).
@@ -104,6 +107,13 @@ def _import_line(result, skipped):
return " · ".join(parts)
def not_tags_line(count):
"""The job log's count of trained-words entries not made tags (#618)."""
entries = _count(count, "trained-words entry", "trained-words entries")
verb = "was" if count == 1 else "were"
return f"{entries} {verb} not made tags (lists or sentences)"
def _all_downloads_failed(errors):
"""The warning when every planned download failed (#337)."""
if errors == 1:
@@ -315,6 +325,8 @@ class LoraImportRoutesMixin:
"current_imports": current,
"blocked_by_pairs": blocked,
"planned_downloads": downloads,
"trigger_tags": int(found.get("trigger_tags", 0)),
"trigger_not_tags": int(found.get("trigger_not_tags", 0)),
"scope": {
"count": found["with_metadata"],
"label": (
@@ -441,6 +453,9 @@ class LoraImportRoutesMixin:
self.logger.exception("LoRA import staging failed")
return _fail_job(job, "import-failed", f"{FAILED} {CACHE_NOTE}")
self._count_downloads(job, staged)
not_tags = staged.stats.get("trigger_not_tags", 0)
if not_tags:
job.log_line(not_tags_line(not_tags))
# M4: what staging skipped stays on the job whatever happens next.
job.record_counted(
"skipped",
@@ -466,6 +481,12 @@ class LoraImportRoutesMixin:
return _fail_job(job, "plan-changed", f"{SOURCE_CHANGED} {CACHE_NOTE}")
job.update(status_line="Replacing the LoRA collection", progress=95)
await self._replace_in_job(job, db, plan, staged)
# #619: the replace is one transaction and has committed by now, so
# the import is finished even when ComfyUI is exiting: end it here,
# before the exit signal can relabel it "cancelled" on the way out.
# A failed replace already ended the job "failed"; a second finish
# is a no-op.
job.finish("finished")
return None
def _count_downloads(self, job, staged):
+62 -11
View File
@@ -5,7 +5,9 @@ one operation (``duplicate_prompts``, ``optimize``, ``unused_components``,
``missing_links`` or ``pair_metadata``, #550; ``database/maintenance.py``;
``duplicate_files``,
``py/api/duplicate_files.py``; ``rotated_logs``, the rotated log copies,
``py/api/log_cleanup.py``, which has its own apply job) off the event loop and
``py/api/log_cleanup.py``, which has its own apply job; ``tag_cleanup``,
#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the
event loop and
answers a ``Plan``: ``{success, token, operation, expires_at, scope:{count,
label}, protected:{count, reasons}, backup:{policy, destination_label},
media:{deletes_files, label}, details:[≤50 {label, detail}]}``. The preview
@@ -29,13 +31,17 @@ The token is consumed when the job starts (on the same loop turn, before its
runner runs); a refused start keeps it. The runner:
1. takes a safety backup when the plan was reviewed with the policy on or the
policy (``maintenance.safety_backup``, default on) is on now: SQLite's
policy (``maintenance.safety_backup``, default on) is on now, and always
for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy
``required``): SQLite's
backup API into a temp file beside the database, ``verify_database_file``,
fsync, ``0o600`` on POSIX, then ``os.replace`` onto a unique
``<db>.backup_<YYYYmmdd_HHMMSS_ffffff>[_n]`` name. Any failure removes
what it wrote and ends the job ``backup-failed`` with nothing changed;
2. applies the plan, which first rechecks the reviewed fingerprint inside
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing);
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); ``tag_cleanup``
rechecks each tag instead and keeps, with its reason, each one that
changed, while the rest still apply;
3. counts the changed and protected records, and prunes old safety backups.
The job log names the backup by its file name only, and the job says "No
@@ -87,6 +93,13 @@ MAINTENANCE_PREVIEW_LEASE = "Maintenance preview"
DUPLICATE_PREVIEW_BODY_MAX = 1024 * 1024
DUPLICATE_FILES = "duplicate_files"
WORKFLOW_STORAGE = "workflow_storage" # applied by py/api/workflow_storage.py
# #618: planned from a tag search's findings (py/api/tag_cleanup.py).
TAG_CLEANUP = "tag_cleanup"
# Previews whose options list many ids, read up to the large body cap.
LARGE_PREVIEWS = frozenset({DUPLICATE_FILES, TAG_CLEANUP})
# Always backed up first, whatever the safety-backup setting: Store each
# workflow once (the way back) and Tag cleanup (maintainer ruling, #618).
ALWAYS_BACKED_UP = frozenset({WORKFLOW_STORAGE, TAG_CLEANUP})
# rotated_logs (#329, py/api/log_cleanup.py) reviews log files, not records.
PREVIEW_OPERATIONS = MAINTENANCE_OPERATIONS + (DUPLICATE_FILES, ROTATED_LOGS)
# Room left over beyond what a step writes, so a disk is never filled to 0.
@@ -100,9 +113,12 @@ MAINTENANCE_TITLES = {
"workflow_storage": "Store each workflow once",
# #550, beyond the concept: fills old Pair prompts' empty category and tags.
"pair_metadata": "Pair category and tags",
# #618 (D210), beyond the concept: deletes comma-list and unused tags.
TAG_CLEANUP: "Tag cleanup",
}
# Operations whose job keeps every changed row for its report (#550).
COMPLETE_RECORD = frozenset({"pair_metadata"})
# Operations whose job keeps every changed row for its report (#550; #618:
# the report and the backup are the only record of the deleted tag names).
COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP})
_OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS)
MAINTENANCE_GROUPS = ("changed", "protected", "errors")
MAX_TOKEN_LENGTH = 128
@@ -307,6 +323,8 @@ def _changed_line(operation, count, marks=0, result=None):
return "Optimized the database"
if operation == "pair_metadata":
return _pair_metadata_line(result or {"changed": count})
if operation == TAG_CLEANUP:
return f"Deleted {count:,} {'tag' if count == 1 else 'tags'}"
if operation == "duplicate_prompts":
noun = "duplicate prompt" if count == 1 else "duplicate prompts"
return f"Merged {count:,} {noun}"
@@ -408,7 +426,7 @@ class MaintenanceRoutesMixin:
("operation", "options"),
cap=lambda body: (
DUPLICATE_PREVIEW_BODY_MAX
if body.get("operation") == DUPLICATE_FILES
if body.get("operation") in LARGE_PREVIEWS
else PREVIEW_BODY_MAX
),
)
@@ -420,6 +438,8 @@ class MaintenanceRoutesMixin:
return _invalid(_OPERATION_ERROR)
if operation == DUPLICATE_FILES:
return await self.preview_duplicate_files(options)
if operation == TAG_CLEANUP:
return await self.preview_tag_cleanup(options)
if not isinstance(options, dict) or options:
return _invalid(f"{operation} takes no options")
if operation == ROTATED_LOGS:
@@ -470,10 +490,12 @@ class MaintenanceRoutesMixin:
)
policy = self._safety_backup_policy()
destination = "backup"
if operation == WORKFLOW_STORAGE:
# Always backed up first, whatever the policy (the way back);
# one kept pre-migration backup ever, pooled ones after it.
if operation in ALWAYS_BACKED_UP:
# Always backed up first, whatever the policy.
policy = "required"
if operation == WORKFLOW_STORAGE:
# The way back: one kept pre-migration backup ever, pooled ones
# after it.
kept = await self._run_in_executor(pre_migration_backups, db.model.db_path)
destination = "backup" if kept else PRE_MIGRATION_LABEL
try:
@@ -635,8 +657,8 @@ class MaintenanceRoutesMixin:
Decided once, when the apply starts (the disk check measured it), and
handed to the job.
"""
if plan.operation == WORKFLOW_STORAGE:
return True # never without its pre-migration backup
if plan.operation in ALWAYS_BACKED_UP:
return True # never without its backup (pre-migration, or #618's)
return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on"
async def _safety_backup_step(self, job, db, backup_on):
@@ -746,6 +768,13 @@ class MaintenanceRoutesMixin:
}
)
return rows
if plan.operation == TAG_CLEANUP:
# The findings the review protected, then each target the apply
# kept, every one with its reason (#618).
return [
{"path": "", "detail": f"Kept tag “{item['name']}”: {item['reason']}"}
for item in [*plan.payload.get("held", ()), *result["kept"]]
]
if "kept" not in result:
return None
return [
@@ -775,6 +804,8 @@ class MaintenanceRoutesMixin:
return rows
if operation == "pair_metadata":
return [{"path": "", "detail": _filled_detail(item)} for item in described]
if operation == TAG_CLEANUP:
return [{"path": "", "detail": _deleted_tag_detail(i)} for i in described]
if operation == "duplicate_prompts":
return [
{
@@ -792,6 +823,26 @@ class MaintenanceRoutesMixin:
]
def _deleted_tag_detail(item):
"""``Deleted tag “a, b” (Tags containing a comma) · removed from 3 prompts``."""
from .tag_cleanup import rules
line = f"Deleted tag “{item['name']}” ({rules.rule(item['rule']).title})"
owners = [
f"{item[key]:,} {noun if item[key] == 1 else noun + 's'}"
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if item.get(key)
]
if not owners:
return line
joined = (
owners[0]
if len(owners) == 1
else (", ".join(owners[:-1]) + " and " + owners[-1])
)
return f"{line} · removed from {joined}"
def _filled_detail(item):
"""``Prompt 12: category “portrait”; tags a, b``: one filled prompt (#550)."""
parts = []
+11 -1
View File
@@ -431,12 +431,22 @@ def _marker_lock(folder):
(atomic on local disks and SMB/NFS shares, unlike ``flock``), so installs
sharing the folder change the marker one at a time. A lock older than
MARKER_LOCK_STALE was left by a writer that died and is taken over;
waiting longer than MARKER_LOCK_TIMEOUT raises TimeoutError."""
waiting longer than MARKER_LOCK_TIMEOUT raises TimeoutError.
On Windows a lock another writer just unlinked stays delete-pending while
any handle to it is open, and creating it then answers "access denied"
instead of "exists" (#674). That is waited out like a held lock; a folder
that stays denied until the timeout reports its PermissionError."""
lock = os.path.join(folder, MARKER_LOCK_NAME)
deadline = time.monotonic() + MARKER_LOCK_TIMEOUT
while True:
try:
handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(MARKER_LOCK_POLL)
continue
except FileExistsError:
_break_stale_lock(lock)
if time.monotonic() >= deadline:
+1 -1
View File
@@ -3,7 +3,7 @@
Every mapping between an image source (a "root"), one of its media files and
that file's preview on disk goes through this module. URL text stays in
``thumbnail_settings`` (``thumbnail_rel``: ``thumbnails/<rel>_thumb<ext>``,
the shape the serve route, ``inspection-state.mjs`` and ``admin.js`` share);
the shape the serve route and ``inspection-state.mjs`` share);
this module answers where such a preview is on disk.
The store of a source is where its previews live. With the default location
+76 -38
View File
@@ -64,6 +64,36 @@ def bad_request(message):
return web.json_response({"success": False, "error": message}, status=400)
def legacy_id_error(value, name):
"""A 400 unless *value* is an id as the legacy pages send it (#662).
They send a number or the text they read from the page; SQLite matches
either against an INTEGER column. A boolean, float, list or object is no
id (``True`` would otherwise match prompt 1).
"""
if type(value) is int or isinstance(value, str):
return None
return bad_request(f"{name} must be a prompt id")
def legacy_ids_error(value):
"""A 400 unless *value* is a list of ``legacy_id_error`` ids (#662)."""
if not isinstance(value, list):
return bad_request("prompt_ids must be a list")
for item in value:
error = legacy_id_error(item, "prompt_ids")
if error is not None:
return error
return None
def text_field_error(data, name):
"""A 400 when *name* is present in *data* but is not text (#662)."""
if data.get(name) is not None and not isinstance(data[name], str):
return bad_request(f"{name} must be text")
return None
def tags_error(tags):
"""A 400 response when *tags* fail ``validate_tags``, else None."""
try:
@@ -605,18 +635,15 @@ class PromptRoutesMixin:
{"success": False, "error": "Tag name required"}, status=400
)
try:
body = await request.json()
except Exception:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
body, error = await self._read_json_body(request)
if error is not None:
return error
raw_name = body.get("new_name")
if not raw_name:
return web.json_response(
{"success": False, "error": "New tag name required"}, status=400
)
error = tags_error([raw_name])
error = text_field_error(body, "new_name") or tags_error([raw_name])
if error is not None:
return error
new_name = raw_name.strip()
@@ -678,12 +705,9 @@ class PromptRoutesMixin:
async def merge_tags_endpoint(self, request):
"""Merge source tags into a target tag."""
try:
try:
body = await request.json()
except Exception:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
body, error = await self._read_json_body(request)
if error is not None:
return error
source_tags = body.get("source_tags", [])
raw_target = body.get("target_tag")
@@ -697,7 +721,9 @@ class PromptRoutesMixin:
)
if not isinstance(source_tags, list):
return bad_request("Source tags must be a list")
error = tags_error([*source_tags, raw_target])
error = text_field_error(body, "target_tag") or tags_error(
[*source_tags, raw_target]
)
if error is not None:
return error
target_tag = raw_target.strip()
@@ -851,7 +877,11 @@ class PromptRoutesMixin:
"""Update prompt text."""
try:
prompt_id = int(request.match_info["prompt_id"])
data = await request.json()
data, error = await self._read_json_body(request)
if error is None:
error = text_field_error(data, "text")
if error is not None:
return error
new_text = (data.get("text") or "").strip()
if not new_text:
@@ -905,7 +935,9 @@ class PromptRoutesMixin:
"""Update prompt rating."""
try:
prompt_id = int(request.match_info["prompt_id"])
data = await request.json()
data, error = await self._read_json_body(request)
if error is not None:
return error
rating = data.get("rating")
try:
@@ -945,14 +977,16 @@ class PromptRoutesMixin:
"""Add tag to prompt."""
try:
prompt_id = int(request.match_info["prompt_id"])
data = await request.json()
data, error = await self._read_json_body(request)
if error is not None:
return error
raw_tag = data.get("tag")
if not raw_tag:
return web.json_response(
{"success": False, "error": "Tag cannot be empty"}, status=400
)
error = tags_error([raw_tag])
error = text_field_error(data, "tag") or tags_error([raw_tag])
if error is not None:
return error
new_tag = raw_tag.strip()
@@ -994,7 +1028,9 @@ class PromptRoutesMixin:
async def add_tags_to_prompt(self, request):
"""Add multiple tags to a single prompt."""
try:
data = await request.json()
data, error = await self._read_json_body(request)
if error is not None:
return error
prompt_id = data.get("prompt_id")
new_tags = data.get("tags", [])
@@ -1002,6 +1038,9 @@ class PromptRoutesMixin:
return web.json_response(
{"success": False, "error": "Prompt ID is required"}, status=400
)
error = legacy_id_error(prompt_id, "prompt_id")
if error is not None:
return error
if not new_tags or not isinstance(new_tags, list):
return web.json_response(
@@ -1063,7 +1102,11 @@ class PromptRoutesMixin:
"""Remove tag from prompt."""
try:
prompt_id = int(request.match_info["prompt_id"])
data = await request.json()
data, error = await self._read_json_body(request)
if error is None:
error = text_field_error(data, "tag")
if error is not None:
return error
tag_to_remove = (data.get("tag") or "").strip()
prompt = await self._run_in_executor(self.db.get_prompt_by_id, prompt_id)
@@ -1103,13 +1146,18 @@ class PromptRoutesMixin:
async def bulk_delete_prompts(self, request):
"""Bulk delete prompts."""
try:
data = await request.json()
data, error = await self._read_json_body(request)
if error is not None:
return error
prompt_ids = data.get("prompt_ids", [])
if not prompt_ids:
return web.json_response(
{"success": False, "error": "No prompt IDs provided"}, status=400
)
error = legacy_ids_error(prompt_ids)
if error is not None:
return error
deleted_count = await self._run_in_executor(
self.db.bulk_delete_prompts, prompt_ids
@@ -1138,12 +1186,9 @@ class PromptRoutesMixin:
async def bulk_add_tags(self, request):
"""Bulk add tags to prompts."""
try:
try:
data = await request.json()
except ValueError:
return bad_request("Invalid JSON body")
if not isinstance(data, dict):
return bad_request("Expected a JSON object")
data, error = await self._read_json_body(request)
if error is not None:
return error
if "expected_epoch" in data:
return await self._bulk_library_tags(data)
prompt_ids = data.get("prompt_ids", [])
@@ -1156,7 +1201,7 @@ class PromptRoutesMixin:
)
if not isinstance(new_tags, list):
return bad_request("Tags must be a list")
error = tags_error(new_tags)
error = legacy_ids_error(prompt_ids) or tags_error(new_tags)
if error is not None:
return error
@@ -1185,16 +1230,9 @@ class PromptRoutesMixin:
async def bulk_set_category(self, request):
"""Bulk set category for prompts."""
try:
try:
data = await request.json()
except ValueError:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
if not isinstance(data, dict):
return web.json_response(
{"success": False, "error": "Expected a JSON object"}, status=400
)
data, error = await self._read_json_body(request)
if error is not None:
return error
if "images_filter" in data:
return await self._bulk_category_by_filter(data)
if "expected_epoch" in data:
+25 -7
View File
@@ -45,16 +45,20 @@ try:
from ...database.review_decisions import ReviewCommandError
from ...utils.media_capture import CaptureError
from ...utils.review_capture import (
candidate_hashes,
captured_review,
item_profile,
review_evidence,
)
except ImportError:
from database.library import display_title
from database.library_commands import LibraryCommandError
from database.review_decisions import ReviewCommandError
from utils.media_capture import CaptureError
from utils.review_capture import captured_review, item_profile, review_evidence
from utils.review_capture import (
candidate_hashes,
captured_review,
item_profile,
)
ITEMS_URL = "/prompt_manager/review/items"
DEFAULT_LIMIT = 40
@@ -393,12 +397,13 @@ class ReviewRoutesMixin:
"library_epoch": item["epoch"],
**view,
"candidates": candidates,
"collapsed": self._review_collapsed(item),
"dependency_fingerprint": fingerprint,
"sha256": item["sha256"],
"total": item["total"],
}
if len(json.dumps(detail).encode("utf-8")) > MAX_DETAIL_BYTES:
detail = {**detail, "candidates": [], "limited": True}
detail = {**detail, "candidates": [], "collapsed": None, "limited": True}
return web.json_response(detail, headers=_NO_STORE)
def _review_detail(self, item_id: str):
@@ -413,6 +418,20 @@ class ReviewRoutesMixin:
fingerprint = self.db.review_dependency_fingerprint(image_path, aliases)
return item, view, fingerprint, self._review_candidates(item)
@staticmethod
def _review_collapsed(item: dict):
"""#657 D3: ``{shown, total, paths}`` when the stored list keeps only
the most used prompts of the file, else None."""
collapsed = None if item["limited"] else item["evidence"].get("collapsed")
if not isinstance(collapsed, dict):
return None
counts = {key: collapsed.get(key) for key in ("shown", "total", "paths")}
if not all(
isinstance(n, int) and not isinstance(n, bool) for n in counts.values()
):
return None
return counts
def _review_candidates(self, item: dict) -> list:
"""The detail's candidates: role texts, a label and selectability."""
if item["limited"]:
@@ -749,7 +768,6 @@ def _candidate_still_offered(resolution: dict, choice: str) -> bool:
resolution = {"state": "ambiguous", "candidates": [resolution]}
if not isinstance(resolution, dict) or resolution.get("state") != "ambiguous":
return False
evidence, _count, limited = review_evidence(resolution)
if limited:
return False
return any(c.get("hash") == choice for c in evidence.get("candidates", ()))
# Every candidate the bytes offer, before any bound or collapse: a
# reorder that changes the collapsed representatives still applies.
return choice in candidate_hashes(resolution)
+533 -57
View File
@@ -6,12 +6,22 @@ final outcome is ambiguous and unlinked. The strict resolver must find it
``graph_prompt_text``) must not link it, and no saved row may link it
already. A file the fallback links, an exact pair the ingester stored and an
already linked file are never queued. Neither is an ambiguous file with
nothing to choose: fewer than two of its candidates carry a prompt
nothing to choose: none of its candidates carries a prompt
(``utils.review_capture.reviewable``); the scan reports it unresolved ("could
not be traced") unless the inspection profile finds a choice in it.
not be traced") unless the inspection profile finds a choice in it. A file
the default profile calls unresolved gets the same inspection-profile chance
(#659 C1). ``review_dispatch`` is that one per-file decision.
Only scans add items (maintainer ruling, 2026-10-23). The monitor's pass
records nothing: it only removes the pending items of an output it linked.
The monitor queues what the scan would (maintainer decision 2026-11-19,
#659; it replaces the 2026-10-23 ruling that only scans add items). At a
file's final unlinked outcome, after run history had its say, the monitor
hands the path to ``queue_review_file``. One review worker thread runs
``record_review_file`` for it: the scan's own per-file steps for that file
(the ladder under the scan policy with the sealed history, the recorded-run
check), read only, then ``review_dispatch``. It never links a file, and a
file the scan would link is left to the next scan. The queue coalesces by
path and is bounded; a file deferred by a job blocker is kept and replayed
once no blocker remains.
The queue heals itself: a pending item whose file is now linked (by the
fallback, a later resolution or the monitor) is removed by the next scan
@@ -25,25 +35,38 @@ changed (``settle_linked_review_items``).
The scan records through ``_record_scanned_review`` (best effort: a failure
is logged and counted), which goes through
``utils.review_capture.record_ambiguous_file`` on the API's capture store;
the monitor calls ``record_review_file`` from its worker thread after its
own link. Nothing here links a file.
the review worker calls ``record_review_file``, also for an output the
monitor linked (its pending items leave the queue). Nothing here links a
file.
Recording changes records, so it follows the registry's ``records``
admission (#289). The scan records under its own ``records`` job. The
monitor's pass lasts one file and is not a job: it is refused while a
``records`` or ``guarded`` job runs (``deferred``), and the next scan reads
the file again. Thumbnail work (the job and the gallery's generate and clear
holds, kind ``thumbnails``) is ``guarded`` but only writes and removes preview
files under ``thumbnails/`` and never touches the database, so it does not
defer the recording (#249 S5 M7): a long rebuild no longer holds Needs review
back for its whole run.
``records`` or ``guarded`` job runs (``deferred``); the review worker keeps
the path (at most ``REVIEW_DEFERRED_LIMIT``, in memory) and replays it once
the job registry reports no blocker. Thumbnail work (the job and the
gallery's generate and clear holds, kind ``thumbnails``) is ``guarded`` but
only writes and removes preview files under ``thumbnails/`` and never touches
the database, so it does not defer the recording (#249 S5 M7): a long
rebuild no longer holds Needs review back for its whole run.
"""
import functools
import hashlib
import json
import os
import threading
from collections import OrderedDict
from pathlib import Path
from .admin import SCAN_LOG_PREFIXES, _plural, _scan_location, _scan_roots
from .admin import (
SCAN_LOG_PREFIXES,
_BatchHistory,
_file_size,
_plural,
_scan_location,
_scan_roots,
)
from .jobs import THUMBNAILS_JOB_KIND
# The kind the monitor's recording checks admission under (never registered).
@@ -56,11 +79,30 @@ NEW_OUTCOMES = ("recorded", "limited")
try:
from ...utils import review_capture
from ...utils.file_prompt import NEVER, Policy, decide_file_prompt
from ...utils.media_capture import CaptureCapacity
from ...utils.parallel import note_refusal, refused_at_shutdown
from ...utils.review_capture import record_ambiguous_file
except ImportError:
from utils import review_capture
from utils.file_prompt import NEVER, Policy, decide_file_prompt
from utils.media_capture import CaptureCapacity
from utils.parallel import note_refusal, refused_at_shutdown
from utils.review_capture import record_ambiguous_file
# The review worker (#659 C5): its thread's name, the bound of paths waiting
# for it (the oldest is dropped beyond it), the bound of paths a job blocker
# deferred, how often it asks the job registry again while paths are
# deferred, and how long the package teardown waits for it.
REVIEW_WORKER_NAME = "pm-review-recorder"
REVIEW_QUEUE_LIMIT = 4096
REVIEW_DEFERRED_LIMIT = 1000
REVIEW_RETRY_SECONDS = 5
REVIEW_STOP_SECONDS = 5
_REVIEW_WORKER_LOCK = threading.Lock()
# Guards the untraced memory, which the scan and the review worker share.
_UNTRACED_MEMORY_LOCK = threading.Lock()
# Untraced files remembered per process so a rescan of an unchanged file does
# not run the inspection profile again (oldest forgotten first). A plain dict
# of 16-byte digests (the locator, and its size, mtime_ns and item version):
@@ -78,6 +120,15 @@ def _memory_key(locator: str) -> bytes:
return _digest(locator)
# Files Inspect found it cannot record (#657 review), per process: a 16-byte
# digest of the locator, its stat and the review versions, oldest forgotten
# first. Inspect then does not run the recording again for that state.
MAX_INSPECT_MEMORY = 4096
# record_review_file outcomes that record nothing for the file's current
# state (an expected outcome, not an error): remembered by Inspect.
UNRECORDABLE_OUTCOMES = ("skipped", "untraced")
# The scan log's reason for items that leave the queue with nothing to choose.
NOTHING_TO_CHOOSE = "nothing to choose"
@@ -90,6 +141,7 @@ class ReviewRecordingMixin:
``scanned`` is the scan's ``(metadata, inspection_resolution)``; the
resolution is None when the scan did not run the inspection profile.
Returns the record outcome, None when recording failed.
"""
try:
outcome = self._record_review_sync(
@@ -102,13 +154,13 @@ class ReviewRecordingMixin:
)
if review is not None:
review["errors"] += 1
return
if review is None:
return
if outcome in NEW_OUTCOMES:
review["added"] += 1
if outcome in QUEUED_OUTCOMES:
review["queued"] += 1
return None
if review is not None:
if outcome in NEW_OUTCOMES:
review["added"] += 1
if outcome in QUEUED_OUTCOMES:
review["queued"] += 1
return outcome
def _record_review_sync(
self, media_file, roots, review=None, inspection=False, scanned=None
@@ -137,14 +189,55 @@ class ReviewRecordingMixin:
self._settle_untraced_reviews([media_file], roots, review)
return outcome
def review_dispatch(self, media_file, roots, decision, outcome, review=None):
"""The one per-file Needs review decision (#659): ``(scan_status,
record_outcome)`` for a file the caller stored nothing for in this
pass.
``decision`` is the scan-policy ladder's ``Decision`` (None: nothing
to decide) and ``outcome`` the file's scan status. An ambiguous file
with a choice is recorded unless a saved row links it
(``unchanged``). An untraced file, or one the default profile calls
unresolved that has a prompt graph, gets the inspection profile's
choice and the saver anchor (``_untraced_scan_outcome``). Any other
file keeps its status and records nothing (``record_outcome`` None).
The scan uses ``scan_status``, the review worker ``record_outcome``.
"""
if decision is None:
return outcome, None
if decision.review == "ambiguous" and outcome == "ambiguous":
if self._review_file_linked(media_file, roots):
return "unchanged", None # already linked: not a review case
# The records name the item versions that count; the saver
# anchor (#390) is checked on the captured bytes.
scanned = (decision.canonical, None)
recorded = self._record_scanned_review(
media_file, roots, review, scanned=scanned
)
return outcome, recorded
untraced = decision.review == "untraced"
unreadable = (
decision.review is None
and decision.default_unresolved
and bool(decision.canonical.get("prompt"))
)
if outcome == "unresolved" and (untraced or unreadable):
# The inspection profile may still offer a choice (queued for
# review, never linked).
return self._untraced_scan_outcome(
media_file, roots, decision.canonical, review
)
return outcome, None
def _untraced_scan_outcome(self, media_file, roots, canonical, review=None):
"""The scan status of an unlinked file the default profile left
ambiguous without a choice (blocking).
"""``(scan_status, record_outcome)`` of an unlinked file the default
profile left ambiguous without a choice, or unresolved (blocking).
``ambiguous`` when the inspection profile offers a choice: the file is
recorded for review from that profile (never linked), or ``unchanged``
when a saved row links it already. Otherwise ``unresolved``, and its
pending items without a choice leave the queue. The profile runs at
when a saved row links it already. Otherwise ``unresolved``
(``untraced``), and its pending items without a choice leave the
queue. The profile runs at
most once per file state: not for bytes already queued (or decided)
at the file's current size and ``mtime_ns`` under the version that
its records depend on, and not again for a state it already found
@@ -160,15 +253,17 @@ class ReviewRecordingMixin:
)
if review is not None:
review["errors"] += 1
return "unresolved"
return "unresolved", None
if choice is None:
self._settle_untraced_reviews([media_file], roots, review)
self._settle_stale_reviews(media_file, roots, canonical, review)
return "unresolved"
return "unresolved", "untraced"
if self._review_file_linked(media_file, roots):
return "unchanged"
self._record_scanned_review(media_file, roots, review, scanned=choice)
return "ambiguous"
return "unchanged", None
recorded = self._record_scanned_review(
media_file, roots, review, scanned=choice
)
return "ambiguous", recorded
def _inspection_choice(self, media_file, roots, canonical):
"""``(canonical, resolution_or_None)`` when the file offers a choice.
@@ -198,17 +293,21 @@ class ReviewRecordingMixin:
return canonical, None
memory = self._untraced_memory()
key = _memory_key(locator)
if state is not None and memory.get(key) == state:
return None
# The scan and the review worker (#659) share the memory: every
# read and change holds its lock (the resolve below does not).
with _UNTRACED_MEMORY_LOCK:
if state is not None and memory.get(key) == state:
return None
resolution = review_capture.inspection_choice(canonical, media_file.name)
if resolution is not None:
memory.pop(key, None)
return canonical, resolution
if state is not None:
memory.pop(key, None) # re-inserted last: the newest state
memory[key] = state
while len(memory) > MAX_UNTRACED_MEMORY:
del memory[next(iter(memory))]
with _UNTRACED_MEMORY_LOCK:
if resolution is not None:
memory.pop(key, None)
return canonical, resolution
if state is not None:
memory.pop(key, None) # re-inserted last: the newest state
memory[key] = state
while len(memory) > MAX_UNTRACED_MEMORY:
del memory[next(iter(memory))]
return None
def _settle_stale_reviews(self, media_file, roots, canonical, review=None):
@@ -248,10 +347,11 @@ class ReviewRecordingMixin:
return removed
def _untraced_memory(self):
memory = getattr(self, "_untraced_inspections", None)
if memory is None:
memory = self._untraced_inspections = {}
return memory
with _UNTRACED_MEMORY_LOCK:
memory = getattr(self, "_untraced_inspections", None)
if memory is None:
memory = self._untraced_inspections = {}
return memory
@staticmethod
def _review_location(media_file, roots, real_roots=None):
@@ -310,8 +410,8 @@ class ReviewRecordingMixin:
def _settle_untraced_reviews(self, media_files, roots, review=None):
"""Remove the pending items without a choice of untraced ``media_files``.
``media_files`` are files found ambiguous with fewer than two
candidates that carry a prompt. Blocking; best effort like the linked
``media_files`` are files found ambiguous without a candidate that
carries a prompt. Blocking; best effort like the linked
settle (a failure is logged and counted in ``review["errors"]``).
Returns how many items left.
"""
@@ -335,18 +435,23 @@ class ReviewRecordingMixin:
return removed
def record_review_file(self, image_path):
"""Apply the Needs review rule to one monitor output (its worker thread).
"""Apply the Needs review rule to one monitor output (review worker).
Only scans add items (maintainer ruling, 2026-10-23): the monitor
only clears the items of outputs it links. Maps ``image_path`` to the
gallery root that lists it; a file under no current root is
``skipped``. A linked file's pending items are removed and the answer
is ``linked``. Any other file is ``skipped``: nothing is captured or
recorded, and the next scan reads it. While a job runs that a
``records`` job may not run beside, other than thumbnail work
(``PREVIEW_ONLY_KINDS``), nothing is written and the answer is
``deferred``. Errors propagate: the monitor logs them and keeps its
link.
The monitor queues what the scan would (maintainer decision
2026-11-19, #659): it hands a file over at its final unlinked
outcome, after run history had its say, and after each ambiguous
output it links. Maps ``image_path`` to the gallery root that lists
it; a file under no current root is ``skipped``. A linked file's
pending items are removed and the answer is ``linked``. Any other
file runs the scan's own per-file steps, read only
(``_review_unlinked_file``): a file the scan would link, or that
does not save, is ``skipped`` (the next scan links it); otherwise
the answer is ``review_dispatch``'s record outcome (``recorded``,
``duplicate``, ``decided``, ``untraced``, ``limited``) or ``skipped``.
While a job runs that a ``records`` job may not run beside, other
than thumbnail work (``PREVIEW_ONLY_KINDS``), nothing is written and
the answer is ``deferred`` (the worker replays it). Errors propagate:
the worker logs them and the monitor keeps its link.
"""
busy = self._jobs.blocker(
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
@@ -366,7 +471,166 @@ class ReviewRecordingMixin:
if self._review_file_linked(located, roots):
self._settle_scanned_reviews([located], roots)
return "linked"
return "skipped"
return self._review_unlinked_file(located, roots)
def _review_unlinked_file(self, media_file, roots):
"""The scan's per-file steps for one unlinked file, read only.
The metadata read the scan uses, the ladder under ``Policy.SCAN``
with the file's recorded history, then the recorded-run check; a
file any step would link (or whose prompt does not save) is
``skipped``. Otherwise ``review_dispatch`` decides, and its record
outcome is the answer (``skipped`` when it records nothing).
"""
path = str(media_file)
metadata = self._extract_comfyui_metadata(path)
history = _BatchHistory(self, [media_file])
decision = decide_file_prompt(
metadata,
file_name=media_file.name,
file_size=functools.partial(_file_size, media_file),
in_output=False, # only the monitor policy reads it
lookup=functools.partial(history.recorded, path),
policy=Policy.SCAN,
)
if decision.kind != NEVER:
return "skipped" # it saves nothing, or the next scan links it
if decision.try_recorded_run and history.get(path) is not None:
return "skipped" # the scan's recorded-run step links it
_status, recorded = self.review_dispatch(
media_file, roots, decision, decision.unlinked_status
)
return recorded or "skipped"
def inspect_review_file(self, image_path, found=None):
"""Inspect's recording of one file (#657 addendum D2, blocking).
``found`` is the file's ``review`` facet at the inspected stat (None
or a pending item). A pending item of a current item version needs
nothing (``current``); one of an older version is recorded again, so
the new item supersedes it. Otherwise ``record_review_file`` runs,
unless Inspect already found this state unrecordable (``skipped`` or
``untraced``, remembered in ``MAX_INSPECT_MEMORY`` digests:
``remembered``). A busy capture store (the worker copying a fresh
output) is expected: logged at debug level, ``busy``.
"""
if found is not None and self._review_item_current(
found["item_id"], image_path
):
return "current"
key = self._inspect_memory_key(image_path)
memory = self._inspect_memory()
with _UNTRACED_MEMORY_LOCK:
if key is not None and key in memory:
return "remembered"
try:
outcome = self.record_review_file(image_path)
except CaptureCapacity:
self.logger.debug(
"Inspect left Needs review to the worker: captures are busy"
)
return "busy"
if key is not None and outcome in UNRECORDABLE_OUTCOMES:
with _UNTRACED_MEMORY_LOCK:
memory.pop(key, None)
memory[key] = True
while len(memory) > MAX_INSPECT_MEMORY:
del memory[next(iter(memory))]
return outcome
def _inspected_metadata(self, image_path):
"""The file's metadata with its prompt graph decoded (or None)."""
metadata = self._extract_comfyui_metadata(str(image_path)) or {}
prompt = metadata.get("prompt")
if isinstance(prompt, str):
try:
metadata = {**metadata, "prompt": json.loads(prompt)}
except (ValueError, TypeError, RecursionError):
return None
return metadata if isinstance(metadata.get("prompt"), dict) else None
def _review_item_current(self, item_id, image_path):
"""True when the item's version is one the file is queued under now
(the file's metadata is read only for a non-default version)."""
item = self.db.review_item(item_id)
if item is None:
return False
version = item.get("resolver_version")
if version == review_capture.default_item_version():
return True
metadata = self._inspected_metadata(image_path)
return metadata is not None and version in review_capture.item_versions(
metadata
)
def _inspect_memory_key(self, image_path):
"""The digest of the file's locator, stat and review versions."""
full = os.path.abspath(str(image_path))
located = os.path.join(
os.path.realpath(os.path.dirname(full)), os.path.basename(full)
)
try:
facts = os.lstat(located)
except OSError:
return None
return _digest(
f"{os.path.normcase(located)}:{facts.st_size}:{facts.st_mtime_ns}:"
f"{review_capture.default_item_version()}:"
f"{review_capture.semantics_version()}"
)
def _inspect_memory(self):
with _UNTRACED_MEMORY_LOCK:
memory = getattr(self, "_inspect_unrecordable", None)
if memory is None:
memory = self._inspect_unrecordable = {}
return memory
def _review_worker(self):
"""The API's one review worker, made on first use (no thread yet)."""
worker = getattr(self, "_review_recorder_worker", None)
if worker is None:
with _REVIEW_WORKER_LOCK:
worker = getattr(self, "_review_recorder_worker", None)
if worker is None:
worker = ReviewWorker(
# Late-bound on purpose: a record_review_file
# replaced after the worker exists still runs.
lambda path: self.record_review_file(path),
self._review_admitted,
self.logger,
)
self._review_recorder_worker = worker
return worker
def _review_admitted(self):
"""True while no job blocks Needs review writes (any thread)."""
busy = self._jobs.blocker(
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
)
return busy is None
def queue_review_file(self, image_path):
"""Queue ``image_path`` for the review worker; never blocks.
The monitor's review recorder (#659). Returns ``queued``, or
``stopped`` once the worker was stopped (the next scan reads it).
"""
return self._review_worker().queue(str(image_path))
def review_worker_started(self):
"""Whether the review worker's thread was ever started."""
worker = getattr(self, "_review_recorder_worker", None)
return worker is not None and worker.started
def stop_review_worker(self, timeout=REVIEW_STOP_SECONDS):
"""Stop the review worker for good and join it within ``timeout``.
Queued and deferred paths are dropped (their count is logged; the
next scan covers them) and later ``queue_review_file`` calls are
refused. True when no worker thread is left running.
"""
return self._review_worker().stop(timeout)
@staticmethod
def _log_review_items(job, review):
@@ -398,3 +662,215 @@ class ReviewRecordingMixin:
f"{_plural(review['errors'], 'image')} could not be added to "
"Needs review"
)
class ReviewWorker:
"""One daemon thread that runs ``record(path)`` for queued paths (#659 C5).
The queue coalesces by path (a path queued again while it waits keeps
its place; one queued while it runs runs once more afterwards) and holds
at most ``REVIEW_QUEUE_LIMIT`` paths, dropping the oldest with a log
line, so ``queue`` never blocks the monitor's image worker. One thread
means two recordings of one path never run at once. A ``deferred``
answer keeps the path in a bounded, insertion-ordered set; the thread
waits on its queue with a ``REVIEW_RETRY_SECONDS`` timeout and, on each
wake, replays that set once ``admitted()`` (no job blocker) says so.
Everything lives in memory: a restart drops it and the next scan covers
the files. A failure of ``record`` is logged and the worker goes on.
"""
def __init__(self, record, admitted, logger):
self._record = record
self._admitted = admitted
self._logger = logger
self._changed = threading.Condition()
self._pending = OrderedDict() # key -> path
self._deferred = OrderedDict() # key -> path
self._in_hand = None
self._thread = None
self._ever_started = False
self._stopped = False
@property
def started(self):
return self._ever_started
@staticmethod
def _key(path):
return os.path.normcase(os.path.abspath(path))
def queue(self, path):
"""Queue ``path``: ``queued``, or ``stopped`` after ``stop``."""
key = self._key(path)
with self._changed:
if self._stopped:
return "stopped"
if key in self._pending:
return "queued"
self._pending[key] = path
evicted = None
if len(self._pending) > REVIEW_QUEUE_LIMIT:
evicted = self._pending.popitem(last=False)[1]
if self._thread is None and not self._start():
self._pending.pop(key, None)
return "stopped"
self._changed.notify_all()
if evicted is not None:
self._logger.info(
"Too many outputs wait for Needs review; "
f"{os.path.basename(evicted)} is left to the next scan"
)
return "queued"
def _start(self):
"""Start the thread (``_changed`` held); False when refused at exit."""
thread = threading.Thread(
target=self._run, name=REVIEW_WORKER_NAME, daemon=True
)
try:
thread.start()
except RuntimeError as error:
if not refused_at_shutdown(error):
raise
note_refusal(self._logger, "The review worker")
self._stopped = True
return False
self._thread = thread
self._ever_started = True
return True
def pending_count(self):
with self._changed:
return len(self._pending)
def deferred_count(self):
with self._changed:
return len(self._deferred)
def deferred_paths(self):
with self._changed:
return list(self._deferred.values())
def wait_idle(self, timeout):
"""True once no path waits or is in hand (deferred ones may stay)."""
with self._changed:
return self._changed.wait_for(
lambda: not self._pending and self._in_hand is None, timeout
)
def _run(self):
"""The thread body: an unexpected error ends it with a log line and
clears the handle, so the next queued output starts a new thread
(the paths still waiting stay queued)."""
try:
self._loop()
except Exception:
self._logger.error(
"The review worker stopped on an unexpected error; "
"the next output starts it again",
exc_info=True,
)
finally:
with self._changed:
if self._thread is threading.current_thread():
self._thread = None
self._in_hand = None
self._changed.notify_all()
def _loop(self):
while True:
with self._changed:
path = self._next_locked()
if path is None:
return
self._in_hand = path
outcome = None
try:
outcome = self._run_one(path)
finally:
with self._changed:
self._in_hand = None
if outcome == "deferred":
dropped = self._defer_locked(path)
else:
dropped = None
self._changed.notify_all()
if dropped is not None:
self._logger.info(
"Too many outputs wait for a job to end before Needs review; "
f"{os.path.basename(dropped)} is left to the next scan"
)
def _next_locked(self):
"""The next path to record, waiting for one; None once stopped."""
while not self._stopped:
if self._deferred and self._replay_admitted():
for key, path in self._deferred.items():
self._pending.setdefault(key, path)
self._deferred.clear()
if self._pending:
return self._pending.popitem(last=False)[1]
self._changed.notify_all() # idle: ``wait_idle`` may return
# Deferred paths: ask the job registry again after a while
self._changed.wait(REVIEW_RETRY_SECONDS if self._deferred else None)
return None
def _replay_admitted(self):
try:
return bool(self._admitted())
except Exception:
self._logger.debug("Job registry check failed", exc_info=True)
return False
def _run_one(self, path):
try:
outcome = self._record(path)
except Exception:
self._logger.warning(
f"{os.path.basename(path)} could not be added to Needs review",
exc_info=True,
)
return None
self._logger.debug(f"Needs review {outcome}: {os.path.basename(path)}")
return outcome
def _defer_locked(self, path):
"""Keep a deferred path; returns the path dropped at the cap."""
if self._stopped:
return None
key = self._key(path)
self._deferred.pop(key, None)
self._deferred[key] = path
if len(self._deferred) > REVIEW_DEFERRED_LIMIT:
return self._deferred.popitem(last=False)[1]
return None
def stop(self, timeout):
"""Stop for good, drop waiting paths, join within ``timeout``.
True when no thread is left running. Called on the worker's own
thread, it only signals (False).
"""
with self._changed:
self._stopped = True
dropped = len(self._pending) + len(self._deferred)
self._pending.clear()
self._deferred.clear()
thread = self._thread
self._changed.notify_all()
if dropped:
self._logger.info(
f"{_plural(dropped, 'output')} left for the next scan's Needs review"
)
if thread is None:
return True
if thread is threading.current_thread():
return False
thread.join(max(0.0, timeout))
if thread.is_alive():
self._logger.warning(
f"review worker still running after {timeout} s; "
"it stops after the file in hand"
)
return False
return True
+245
View File
@@ -0,0 +1,245 @@
"""Tag cleanup as a find job, its findings and a reviewed plan (#618).
- ``POST /prompt_manager/jobs/tag_cleanup`` (body ignored) starts the find
(202 ``{job}``): kind ``tag_cleanup``, "Find tags to clean up", admission
``read``, not cancellable (one snapshot read), outcome group ``found``. It
runs every rule of ``database/tag_cleanup.py`` on one read-only snapshot,
holds the result under the job id (the last ``MAX_HELD_FINDS``), records one
``found`` row per tag and writes nothing. 409 ``busy`` while a find or an
exclusive job runs.
- ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers every held
finding at once: ``{success, job:{id, state}, rules:[{id, title,
explanation, action_label, total, findings:[{tag_id, name, detail}]}]}``,
at most ``MAX_FINDINGS`` per rule (``total`` is exact). 404 ``not-found``,
409 ``job-running``, 409 ``no-groups`` (the find failed).
- ``POST /prompt_manager/maintenance/preview {operation:"tag_cleanup",
options:{job_id, select:[{rule, tag_ids}]}}`` reviews the ticked findings
(``preview_tag_cleanup``): each selected tag must be a held finding of that
rule. The plan always takes a safety backup first (policy ``required``,
maintainer ruling 2026-11-22) and its apply, the ``maintenance`` job "Tag
cleanup", rechecks each tag and keeps, with its reason, each one that
changed (``py/api/maintenance.py``).
"""
from aiohttp import web
from .job_routes import busy_response
from .jobs import TAG_CLEANUP_GROUP_NAMES, TAG_CLEANUP_JOB_KIND, JobBusy
from .maintenance import _failure, _invalid
try:
from ...database import tag_cleanup as rules
except ImportError:
from database import tag_cleanup as rules
TAG_CLEANUP = rules.OPERATION
FIND_TITLE = "Find tags to clean up"
FIND_FAILED = "The tag search failed."
MAX_HELD_FINDS = 3 # finds whose findings the server keeps for review
MAX_JOB_ID = 64
def _parse_select(entry, seen):
"""``(rule_id, tag_ids, None)`` for one select entry, else a message."""
if not isinstance(entry, dict) or set(entry) != {"rule", "tag_ids"}:
return None, None, "Each select entry is {rule, tag_ids}"
rule_id, tag_ids = entry["rule"], entry["tag_ids"]
if not isinstance(rule_id, str) or rule_id not in rules.RULE_IDS:
return None, None, "rule must be one of: " + ", ".join(rules.RULE_IDS)
if rule_id in seen:
return None, None, "Each rule is selected once"
limit = rules.MAX_FINDINGS
if not isinstance(tag_ids, list) or not 0 < len(tag_ids) <= limit:
return None, None, f"tag_ids must list 1 to {limit:,} tags"
for tag_id in tag_ids:
if type(tag_id) is not int or tag_id < 1:
return None, None, "tag_ids must be tag ids"
if len(set(tag_ids)) != len(tag_ids):
return None, None, "tag_ids must not repeat a tag"
return rule_id, tag_ids, None
def parse_options(options):
"""``(job_id, {rule_id: [tag_id]}, None)`` or ``(None, None, message)``."""
if not isinstance(options, dict) or set(options) != {"job_id", "select"}:
return None, None, "tag_cleanup takes options {job_id, select}"
job_id, select = options["job_id"], options["select"]
if not isinstance(job_id, str) or not 0 < len(job_id) <= MAX_JOB_ID:
return None, None, "job_id must be a tag search's job id"
if not isinstance(select, list) or not 0 < len(select) <= len(rules.RULES):
return None, None, f"select must list 1 to {len(rules.RULES)} rules"
chosen = {}
for entry in select:
rule_id, tag_ids, message = _parse_select(entry, chosen)
if message:
return None, None, message
chosen[rule_id] = tag_ids
return job_id, chosen, None
def _found_rows(result):
return [
{"path": "", "detail": f"{f['name']} · {rules.rule(rule_id).title}"}
for rule_id in rules.RULE_IDS
for f in result["rules"][rule_id]
]
def _public_rules(result):
return [
{
"id": item.id,
"title": item.title,
"explanation": item.explanation,
"action_label": item.action_label,
"total": result["totals"][item.id],
"findings": [
{
"tag_id": f["tag_id"],
"name": f["name"],
"detail": rules.finding_detail(f),
}
for f in result["rules"][item.id]
],
}
for item in rules.RULES
]
class TagCleanupMixin:
"""Mixin providing the tag cleanup find, its findings and its plan."""
def _register_tag_cleanup_routes(self, routes):
@routes.post("/prompt_manager/jobs/tag_cleanup")
async def start_tag_cleanup_find_route(request):
return await self.start_tag_cleanup_find(request)
@routes.get("/prompt_manager/maintenance/tag_cleanup/{job_id}")
async def tag_cleanup_findings_route(request):
return await self.tag_cleanup_findings(request)
# ── find ──────────────────────────────────────────────────────────
async def start_tag_cleanup_find(self, request):
"""Start the tag search (202), or 409 naming the job in the way."""
db = self.db
try:
job = self._jobs.start(
TAG_CLEANUP_JOB_KIND,
FIND_TITLE,
admission="read",
cancellable=False,
groups=TAG_CLEANUP_GROUP_NAMES,
runner=lambda job: self._run_tag_cleanup_find(job, db),
)
except JobBusy as busy:
return busy_response(busy)
self._remember_tag_cleanup_find(job.id)
return web.json_response({"success": True, "job": job.summary()}, status=202)
def _remember_tag_cleanup_find(self, job_id):
"""Hold a slot for ``job_id`` (None until it found); keep the last few."""
finds = self._tag_cleanup_finds
finds[job_id] = None
for held in list(finds):
if self._jobs.get(held) is None:
del finds[held]
while len(finds) > MAX_HELD_FINDS:
del finds[next(iter(finds))]
async def _run_tag_cleanup_find(self, job, db):
job.update(status_line="Looking for tags to clean up")
try:
result = await self._run_in_executor(
rules.find_tag_cleanup, db.model.db_path
)
except Exception:
self.logger.exception("Tag search failed")
job.update(status_line=FIND_FAILED)
job.log_line(FIND_FAILED)
job.finish("failed")
return
if job.id in self._tag_cleanup_finds:
self._tag_cleanup_finds[job.id] = result
count = sum(result["totals"].values())
job.record_counted("found", count, _found_rows(result))
line = (
f"Found {count:,} {'tag' if count == 1 else 'tags'} to clean up"
if count
else "No tags need cleaning up"
)
job.log_line(line)
job.update(progress=100, status_line=line)
# ── findings ──────────────────────────────────────────────────────
def _held_tag_cleanup(self, job_id):
"""``(result, None)`` for a finished search's findings, else a reply."""
job = self._jobs.get(job_id)
finds = self._tag_cleanup_finds
if job_id not in finds or job is None or job.kind != TAG_CLEANUP_JOB_KIND:
return None, _failure(
"No tag search with this id. Search again.", 404, "not-found"
)
if job.running:
return None, _failure(
"The tag search is still running.", 409, "job-running"
)
if finds[job_id] is None:
return None, _failure(
"This search did not finish. Search again.", 409, "no-groups"
)
return finds[job_id], None
async def tag_cleanup_findings(self, request):
job_id = request.match_info["job_id"]
result, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
job = self._jobs.get(job_id)
return web.json_response(
{
"success": True,
"job": {"id": job.id, "state": job.state},
"rules": _public_rules(result),
},
headers={"Cache-Control": "no-store"},
)
# ── review ────────────────────────────────────────────────────────
async def preview_tag_cleanup(self, options):
"""The ``tag_cleanup`` plan for the ticked findings of one search."""
job_id, chosen, message = parse_options(options)
if message:
return _invalid(message)
held, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
for rule_id, tag_ids in chosen.items():
listed = {f["tag_id"] for f in held["rules"][rule_id]}
if not listed.issuperset(tag_ids):
return _invalid("A selected tag is not a finding of its rule")
db = self.db
identity = self._database_identity(db)
try:
draft = await self._run_in_executor(
rules.plan_tag_cleanup, db.model.db_path, held, chosen
)
except Exception:
self.logger.exception("Tag cleanup review failed")
return _failure("Failed to review maintenance", 500)
return await self._plan_response(
db,
identity,
TAG_CLEANUP,
draft.fingerprint,
draft.public(),
{
"targets": draft.targets,
"roots": [],
"held": rules.held_rows(draft),
"protected": draft.protected["count"],
"rows": len(draft.targets),
},
)
-4
View File
@@ -388,7 +388,6 @@ class AutoThumbnailer:
self._worker_running = False
self._closed = False
self._busy = False
self._batch = 0
@property
def failure_count(self):
@@ -548,7 +547,6 @@ class AutoThumbnailer:
with self._changed:
self._worker_running = False
self._busy = False
self._batch = 0
self._changed.notify_all()
def _drain(self):
@@ -563,7 +561,6 @@ class AutoThumbnailer:
workers = max(1, int(self._workers() or 1))
take = min(len(self._queue), workers)
batch = [self._queue.popleft() for _ in range(take)]
self._batch = len(batch)
self._changed.notify_all()
try:
# The job pool's size is the setting; a smaller batch uses
@@ -571,7 +568,6 @@ class AutoThumbnailer:
map_parallel(self._write_queued, batch, workers)
finally:
with self._changed:
self._batch = 0
for key, *_rest in batch:
self._queued.discard(key)
+4 -1
View File
@@ -43,6 +43,7 @@ CONTENT_TYPES = {
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".avif": "image/avif", # #652: served as itself, never a preview
}
THUMB_SUFFIX = "_thumb"
@@ -133,7 +134,9 @@ def thumbnail_rel(rel_path, extension=None):
# Ruling R2: files sharing a stem share one preview, made from the first
# source in this order: these images, then videos (by extension name).
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif")
# #652: AVIF comes last among the stills, so an existing stack keeps the
# source its preview was made from.
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif")
def source_rank(source_extension):
+47 -2
View File
@@ -38,6 +38,7 @@ from typing import Any, Dict, List, Optional, Tuple # noqa: E402
try:
from ..utils.logging_config import get_logger
from ..utils import library_location
from ..utils.media_formats import AVIF_EXTENSION
except ImportError:
import sys
@@ -45,6 +46,7 @@ except ImportError:
sys.path.insert(0, current_dir)
from utils.logging_config import get_logger
from utils import library_location
from utils.media_formats import AVIF_EXTENSION
# Initialize logger for config operations
config_logger = get_logger("prompt_manager.config")
@@ -195,7 +197,9 @@ class GalleryConfig:
# Read by the monitor for every file, so a save applies without a restart
SAVE_FOREIGN_RUNS = True
MONITORING_DIRECTORIES = [] # Auto-detect if empty
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif"]
# #652: AVIF is named here and skipped at collection when Pillow cannot
# read it (utils.media_formats.collectable).
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif", AVIF_EXTENSION]
PROCESSING_DELAY = 2.0 # Seconds to wait before processing new files
# Prompt tracking settings
@@ -301,7 +305,9 @@ class GalleryConfig:
if directories is not None:
cls.MONITORING_DIRECTORIES = directories
if "extensions" in monitoring:
cls.SUPPORTED_EXTENSIONS = monitoring["extensions"]
extensions = cls._validated_extensions(monitoring["extensions"])
if extensions is not None:
cls.SUPPORTED_EXTENSIONS = extensions
if "processing_delay" in monitoring:
cls.PROCESSING_DELAY = monitoring["processing_delay"]
@@ -355,6 +361,45 @@ class GalleryConfig:
config_logger.warning(f"Ignoring gallery root {label!r}: {reason}")
return kept
@classmethod
def _validated_extensions(cls, extensions: Any) -> Optional[List[str]]:
"""Monitor extensions from a saved config, with AVIF added back (#652).
``gallery.monitoring.extensions`` is saved in each user's config.json
and overrides the default, so an install that saved its settings
before #652 names no ``.avif`` and keeps not collecting AVIF files.
It is appended here, after the user's own entries, so an existing
install gains the new type without losing anything it chose.
A hand-edited config.json is as untrusted as a settings request: a
value that is not a list is ignored entirely (``None`` keeps the
current list), a non-string entry is dropped with a warning, and the
rest is normalised to lowercase dot-extensions.
"""
if not isinstance(extensions, list):
config_logger.warning(
"Ignoring gallery monitoring extensions: expected a list"
)
return None
kept = []
for entry in extensions:
if not isinstance(entry, str):
config_logger.warning(
"Ignoring gallery monitoring extension: expected a string"
)
continue
normalized = entry.strip().lower()
if not normalized:
continue
if not normalized.startswith("."):
normalized = "." + normalized
if normalized not in kept:
kept.append(normalized)
# An empty list is a deliberate "collect nothing", so it stays empty.
if kept and AVIF_EXTENSION not in kept:
kept.append(AVIF_EXTENSION)
return kept
@classmethod
def allowed_gallery_parents(cls) -> List[str]:
"""Canonical directories under which gallery roots may live.
+27 -9
View File
@@ -111,23 +111,29 @@ def preview(
"""The review's counts (blocking; reads only, requests nothing).
``{lora_files, with_metadata, skipped, with_local_media,
planned_downloads, fingerprint, names, layout}``: the metadata files
seen, the kept LoRAs whose sidecar parses, the rest, the LoRAs with a
local image, the CivitAI images an import would download for the LoRAs
without one (not yet in the cache), the first LoRA names and what the
layout says (``layout_summary``).
planned_downloads, trigger_tags, trigger_not_tags, fingerprint, names,
layout}``: the metadata files seen, the kept LoRAs whose sidecar parses,
the rest, the LoRAs with a local image, the CivitAI images an import would
download for the LoRAs without one (not yet in the cache), the trained-words
entries that become tags and those that do not (#618), the first LoRA
names and what the layout says (``layout_summary``).
"""
discovery = discover(lora_manager_path)
layout = discovery.layout
with_metadata = 0
with_local_media = 0
planned = 0
trigger_tags = 0
trigger_not_tags = 0
names = []
for sidecar in discovery.sidecars:
metadata = lora_utils.read_lora_metadata(sidecar.metadata_path)
if not metadata:
continue
with_metadata += 1
words, not_tags = lora_utils.trigger_word_tags(metadata)
trigger_tags += len(words)
trigger_not_tags += not_tags
if local_media(sidecar, metadata, layout, media_extensions):
with_local_media += 1
else:
@@ -142,6 +148,8 @@ def preview(
"skipped": discovery.scanned - with_metadata,
"with_local_media": with_local_media,
"planned_downloads": planned,
"trigger_tags": trigger_tags,
"trigger_not_tags": trigger_not_tags,
"fingerprint": fingerprint(discovery),
"names": names,
"layout": layout_summary(layout, Path.home()),
@@ -149,17 +157,22 @@ def preview(
def build_record(metadata: Dict, path: Path, images: List[str]) -> Dict:
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images."""
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images.
Only the trained words that are one short clean phrase become tags
(#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest.
"""
model_name = lora_utils.get_model_name_from_metadata(metadata)
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
tags = ["lora-manager", f"lora:{model_name}"]
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
words, not_tags = lora_utils.trigger_word_tags(metadata)
tags = ["lora-manager", f"lora:{model_name}", *words]
return {
"name": model_name,
"text": text,
"hash": generate_prompt_hash(text),
"tags": list(dict.fromkeys(tags)),
"images": images,
"trigger_not_tags": not_tags,
}
@@ -171,7 +184,11 @@ class StagedImport:
records: List[Dict] = field(default_factory=list)
skipped: List[str] = field(default_factory=list)
stats: Dict[str, int] = field(
default_factory=lambda: {"downloaded": 0, "download_errors": 0}
default_factory=lambda: {
"downloaded": 0,
"download_errors": 0,
"trigger_not_tags": 0,
}
)
@@ -219,6 +236,7 @@ def stage(
images = list(dict.fromkeys([*local, *remote]))
record = build_record(metadata, path, images)
staged.records.append(record)
staged.stats["trigger_not_tags"] += record["trigger_not_tags"]
except Exception as error: # one LoRA never stops the import
name = lora_utils.get_model_name_from_metadata(metadata)
if logger is not None:
+40
View File
@@ -22,11 +22,13 @@ from urllib.parse import urljoin, urlsplit
try:
from ..utils.logging_config import get_logger
from ..utils.validators import validate_tags
except ImportError:
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.logging_config import get_logger
from utils.validators import validate_tags
from dataclasses import replace
@@ -387,6 +389,44 @@ def get_trigger_words_from_metadata(metadata: Dict) -> List[str]:
return []
# #618: what a prompt weight looks like, ``(masterpiece:1.2)``: an instruction
# to the sampler, never a label.
_PROMPT_WEIGHT = re.compile(r"\([^()]*:\s*-?\d*\.?\d+\s*\)")
# The ASCII and the fullwidth comma: an entry holding either is a list.
_COMMAS = (",", ",")
def is_tag_phrase(entry: object) -> bool:
"""Whether a trained-words entry is one short clean phrase (#618, Option A).
The existing tag rule (``validate_tags``: not empty, at most 50
characters, no control character), and no comma (ASCII or fullwidth), no
``<``/``>`` (``<lora:name:0.8>`` loads a model) and no prompt weight.
Plain parentheses stay allowed (``hatsune miku (vocaloid)``).
"""
if not isinstance(entry, str):
return False
phrase = entry.strip()
try:
validate_tags([phrase])
except ValueError:
return False
if any(comma in phrase for comma in _COMMAS):
return False
if "<" in phrase or ">" in phrase:
return False
return _PROMPT_WEIGHT.search(phrase) is None
def trigger_word_tags(metadata: Dict) -> Tuple[List[str], int]:
"""``(tags, not_tags)``: the trigger words that are tag phrases, stripped
and in order, and how many were not (#618). The trigger-word lookup
(``get_trigger_words_from_metadata``) still sees every entry."""
words = get_trigger_words_from_metadata(metadata)
tags = [word for word in words if is_tag_phrase(word)]
return tags, len(words) - len(tags)
def get_example_prompt_from_metadata(metadata: Dict) -> Optional[str]:
"""Extract an example prompt from civitai image metadata.
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "promptmanager"
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
version = "3.7.0"
version = "3.8.0"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
+2 -3
View File
@@ -8,9 +8,8 @@
// browser that exits abnormally prints one `pm-browser-exit|` line, and a test
// that fails on a closed or crashed target gets that log attached as
// `browser-stderr`.
// The one-time older-images notice (#527) shows above every workspace page and as
// a modal on the admin page until dismissed, so every context starts with it
// dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
// The one-time older-images notice (#527) shows above every workspace page until
// dismissed, so every context starts with it dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
import { test as base, expect } from '../../tools/vendor/node_modules/@playwright/test/index.mjs';
import { attachServerStderr, createServerSupervisor, startBrowserServer } from '../../tools/vendor/start-browser-server.mjs';
import { attachBrowserLogs, createBrowserLogRecorder } from '../../tools/vendor/browser-logs.mjs';
+121
View File
@@ -0,0 +1,121 @@
// #659 (design Part 5): Inspect's Choose prompt. A queued ambiguous file (tests/browser/workspace_review_fixture.py,
// recorded through the scan's recorder) shows its candidates in the Images details panel; choosing one links the file
// and takes it out of Needs review, leaving it unresolved decides it, and an item with nothing to choose sends the user
// to Needs review.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const images = '/prompt_manager/workspace#/images';
const details = page => page.getByRole('complementary', { name: 'Selected image details', exact: true });
const choice = page => details(page).getByRole('region', { name: 'Choose prompt', exact: true });
const context = page => choice(page).getByRole('combobox', { name: 'Sampler context', exact: true });
const toast = page => page.locator('#workspace-toast');
const OPTIONS = ['Sampler 11 · Golden dunes at dusk / Soft negative, blur', 'Sampler 13 · Harbor lights at night / Soft negative, blur'];
async function seed(request, data) {
const response = await request.post('/__test__/review/reset', { data });
await expect(response).toBeOK();
return response.json();
}
const pending = async request => (await (await request.get('/prompt_manager/review/items?limit=1')).json()).total;
const links = async request => (await (await request.get('/__test__/review/links')).json()).links;
/** The Images page with `filename`'s details open (a page may already have selected it). */
async function inspect(page, filename) {
await page.goto(images);
const card = page.locator('article[data-image-key]').filter({ hasText: filename });
await card.getByRole('button', { name: `Inspect ${filename}`, exact: true }).click();
await expect(details(page).locator('.detail-inner > p.small').first()).toHaveText(filename);
}
test.beforeEach(async ({ page, browserName }) => {
await startCoverage(page, browserName);
page.choiceErrors = [];
page.on('pageerror', error => page.choiceErrors.push(error.message));
});
test.afterEach(async ({ page, browserName, request }) => {
await saveCoverage(page, browserName);
expect(page.choiceErrors).toEqual([]);
await request.post('/__test__/jobs/restart');
});
test('choosing a candidate in Inspect links the file and takes it out of Needs review', async ({ page, request }) => {
await seed(request, { items: 1 });
expect(await pending(request)).toBe(1);
await inspect(page, 'review_0000.png');
// The section follows the file's own prompt blocks.
await expect(choice(page)).toBeVisible();
await expect(details(page).locator('.detail-inner > .inspect-choice')).toHaveCount(1);
await expect(context(page).locator('option')).toHaveText(OPTIONS);
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Golden dunes at dusk');
await context(page).selectOption({ label: OPTIONS[1] });
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Harbor lights at night');
await expect(choice(page).locator('.prompt-section.negative .prompt-text')).toHaveText('Soft negative, blur');
await expect(choice(page).getByRole('button', { name: 'Copy chosen positive prompt', exact: true })).toBeVisible();
await expect(choice(page).getByRole('button', { name: 'Send chosen positive prompt to ComfyUI', exact: true })).toBeVisible();
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
const reread = page.waitForResponse(response => response.url().includes('/prompt_manager/images/inspect/') && response.ok());
await choice(page).getByRole('button', { name: 'Use this prompt', exact: true }).click();
expect((await decided).status()).toBe(200);
await reread;
await expect(toast(page)).toHaveText('Association accepted.');
// The inspection is read again: the file is linked, so the section is gone and Prompt history opens its prompt.
await expect(choice(page)).toHaveCount(0);
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toBeVisible();
expect(await pending(request)).toBe(0);
expect((await links(request)).map(row => [row.filename, row.prompt])).toEqual([['review_0000.png', 'Harbor lights at night']]);
await page.goto('/prompt_manager/workspace#/review');
await expect(page.locator('#workspace-main .notice h2')).toHaveText('No images need a decision');
});
test('Leave unresolved in Inspect decides the item and links nothing', async ({ page, request }) => {
await seed(request, { items: 2 });
await inspect(page, 'review_0001.png');
await expect(context(page).locator('option')).toHaveText(OPTIONS);
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
await choice(page).getByRole('button', { name: 'Leave unresolved', exact: true }).click();
expect((await decided).status()).toBe(200);
await expect(toast(page)).toHaveText('Left unresolved.');
// The item is decided: the section is gone and the file stays unlinked.
await expect(choice(page)).toHaveCount(0);
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toHaveCount(0);
expect(await pending(request)).toBe(1);
expect(await links(request)).toEqual([]);
});
test('an item with nothing to choose offers Open in Needs review', async ({ page, request }) => {
await seed(request, { items: 0, limited: true });
await inspect(page, 'limited.png');
await expect(choice(page)).toContainText('None of the possible prompts can be applied here. Decide this image in Needs review.');
await expect(context(page)).toBeHidden();
await expect(choice(page).getByRole('button', { name: 'Use this prompt', exact: true })).toBeHidden();
await choice(page).getByRole('button', { name: 'Open in Needs review', exact: true }).click();
await expect(page).toHaveURL(/#\/review$/);
await expect(page.locator('#workspace-main .notice h2')).toHaveText('1 image needs a decision');
});
test('the viewer details show the same Choose prompt', async ({ page, request }) => {
await seed(request, { items: 1 });
await page.goto(images);
const card = page.locator('article[data-image-key]').filter({ hasText: 'review_0000.png' });
await card.getByRole('button', { name: 'Open review_0000.png', exact: true }).click();
const viewer = page.locator('#viewer-dialog');
await expect(viewer).toBeVisible();
const section = viewer.getByRole('region', { name: 'Choose prompt', exact: true });
await expect(section.getByRole('combobox', { name: 'Sampler context', exact: true }).locator('option')).toHaveText(OPTIONS);
// Open in Needs review is offered only when nothing can be chosen.
await expect(section.getByRole('button', { name: 'Open in Needs review', exact: true })).toBeHidden();
});
test('#657 D3: Choose prompt says when the file\'s prompts were shortened to the most used', async ({ page, request }) => {
await seed(request, { items: 1 });
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
const response = await route.fetch();
await route.fulfill({ response, json: { ...(await response.json()), collapsed: { shown: 2, total: 81, paths: 165 } } });
});
await inspect(page, 'review_0000.png');
await expect(context(page).locator('option')).toHaveText(OPTIONS);
await expect(choice(page).locator('.review-collapsed')).toHaveText('Showing the 2 most used of 81 prompts in this file.');
});
-182
View File
@@ -1,182 +0,0 @@
// #328: the legacy admin and gallery auto-tag batch and review keep working beside System › Auto-tagging. Since #330
// the pages download and unload models only through System (legacy-system-links.spec.mjs); a batch never downloads
// one. The fixture's fake download (`/__test__/tagging/download`) is held so nothing is ever fetched.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
async function downloads(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs.filter(job => job.kind === 'model_download');
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
await post(request, '/__test__/jobs/restart');
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/tagging/models', { unavailable: ['wd14-vit'] });
await post(request, '/__test__/tagging/download', { mode: 'hold' });
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
// Releases a download a failed test left held, and puts the raising default back.
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/jobs/restart');
});
// (wd14-vit is not downloaded in these tests: beforeEach marks it so the download tests can offer it.)
// The gallery's batch reader keyed on `data.status` values the server never sends, so its modal never moved or
// closed (#328 Problem 5). It now reads `type` frames as the admin page does.
async function watchProgress(page) {
await page.evaluate(() => {
window.progressSeen = [];
const node = document.getElementById('autoTagProgressPercent');
// Each change from its own record: frames that land in one task share one
// callback, and the node's text by then is only the last of them.
new MutationObserver(records => {
for (const record of records) {
if (record.type === 'characterData') window.progressSeen.push(record.target.data);
for (const added of record.addedNodes) window.progressSeen.push(added.textContent);
}
}).observe(node, { childList: true, characterData: true, subtree: true });
});
}
async function runGalleryBatch(page) {
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await watchProgress(page);
const done = page.waitForResponse(response => response.url().includes('/prompt_manager/autotag/start'));
await page.locator('#startAutoTagBtn').click();
await done;
await expect(page.locator('#autoTagProgressModal')).toBeHidden();
// #379: the batch counts images, never prompts.
await expect(page.getByText(/^Auto tagging complete! Tagged \d+ images?\.$/)).toBeVisible();
}
const CLOSE_NOTE = 'Closing this window stops tagging. Tags already added are kept. Prompt Manager\'s Activity page shows the '
+ 'time left.';
async function serverJobs(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs;
}
async function runNativeBatch(request) {
const started = await request.post('/prompt_manager/jobs/autotag', { data: { model_type: 'wd14-swinv2', existing: 'skip',
options: { general_threshold: 0.35, character_threshold: 0.85 } } });
expect(started.status()).toBe(202);
const { job } = await started.json();
await expect.poll(async () => (await serverJobs(request)).find(item => item.id === job.id)?.state).toBe('finished');
}
test('gallery batch modal counts progress and closes on complete', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await runGalleryBatch(page);
const seen = await page.evaluate(() => window.progressSeen);
// The phase frames (model 5%, listing 8%) then the per-image frames (from 10%) move the bar.
expect(seen).toContain('8%');
expect(seen.some(value => parseInt(value, 10) >= 10)).toBe(true);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
// The batch ran as the autotag job of the legacy page.
expect((await serverJobs(request)).filter(job => job.kind === 'autotag').map(job => [job.title, job.state]))
.toEqual([['Tag output images (legacy page)', 'finished']]);
expect((await downloads(request)).length).toBe(0);
});
test('admin batch copy names images, not prompts (#379)', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await expect(page.locator('input[name="autoTagMode"][value="skip"] + span')).toHaveText('Skip images already auto-tagged');
await expect(page.getByText('"auto-scanned" is not counted as a real tag')).toHaveCount(0);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
await expect(page.locator('#retagConfirmModal h3')).toHaveText('Image Already Auto-tagged');
await expect(page.locator('#retagConfirmModal')).toContainText('A tagging model already tagged this image. Generate new tags?');
});
test('admin review opens the first image', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
// #379: no image is auto-tagged yet (prompt tags no longer count), so the review opens on the first image.
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewImageName')).not.toHaveText(/^(image_name\.png|Unknown|)$/);
await expect(page.getByText('Failed to start review mode')).toHaveCount(0);
});
/** The admin review lists every row, videos too: Skip any image that is not one until the confirmation shows. */
async function untilAutoTagged(page, confirm) {
// Each image's skip check answers before its confirmation or its error shows.
const failed = page.locator('#reviewTagsVisible .text-pm-error');
for (let tries = 0; tries < 5; tries++) {
await expect.poll(async () => (await confirm.isVisible()) || (await failed.count()) > 0).toBe(true);
if (await confirm.isVisible()) return;
const answered = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#skipReviewBtn').click();
await answered;
}
await expect(confirm).toBeVisible();
}
// #379: the admin review asks before re-tagging an image a model already tagged, and Apply & Next writes that image's
// tags (its bytes, never its prompt).
test('admin review: an auto-tagged image asks first; Re-tag then Apply & Next tags the image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await expect(confirm.locator('#retagExistingTags span').first()).toHaveText('sandstone');
await page.locator('#retagConfirmBtn').click();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewTagsVisible .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(body.prompt_id).toBeUndefined();
expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
expect((await answer).status()).toBe(200);
});
test('admin review: Skip All Tagged passes every auto-tagged image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await page.locator('#retagSkipAllBtn').click();
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.getByText('Review complete!')).toBeVisible();
});
test('gallery review: Apply & Next tags the image by its path and bytes', async ({ page }) => {
await page.goto('/prompt_manager/gallery');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
const suggested = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#startReviewBtn').click();
expect((await suggested).postDataJSON().existing).toBe('merge');
await expect(page.locator('#reviewTagsContainer .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(Object.keys(body).sort()).toEqual(['path', 'root_index', 'sha256', 'tags'].filter(key => key in body).sort());
expect(body.prompt_id).toBeUndefined();
expect((await answer).status()).toBe(200);
});
@@ -1,47 +0,0 @@
// #615: each old page says it will be removed and links to where its job lives now. The page keeps working, and the
// notice takes its own room: nothing is pushed off a page whose layout fills the window.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const PAGES = Object.freeze([
{ path: '/prompt_manager/admin', section: 'library', heading: 'Prompt library' },
{ path: '/prompt_manager/gallery', section: 'images', heading: 'Images' },
{ path: '/prompt_manager/gallery.html', section: 'inspect', heading: 'Inspect a file' },
]);
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset', {})).toBeOK();
await page.addInitScript(() => {
localStorage.setItem('pm_update_notice_dismissed', '3.2.0');
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
});
});
test.afterEach(async ({ page, browserName }) => {
await saveCoverage(page, browserName);
});
for (const { path, section, heading } of PAGES) {
test(`${path} says it will be removed and links to ${section}`, async ({ page }) => {
await page.goto(path);
const notice = page.locator('#legacy-removal-notice');
await expect(notice).toBeVisible();
await expect(notice).toContainText('This page will be removed in a future release.');
await notice.getByRole('link', { name: 'Open the workspace' }).click();
await expect(page).toHaveURL(new RegExp(`/prompt_manager/workspace#/${section}$`));
await expect(page.locator('#workspace-main h1')).toHaveText(heading);
});
}
test('the notice leaves the metadata page filling the window', async ({ page }) => {
await page.goto('/prompt_manager/gallery.html');
await expect(page.locator('#legacy-removal-notice')).toBeVisible();
const { bottom, height, scroll } = await page.locator('#image-area').evaluate(area => ({
bottom: area.getBoundingClientRect().bottom,
height: window.innerHeight,
scroll: document.documentElement.scrollHeight,
}));
expect(bottom).toBeLessThanOrEqual(height);
expect(scroll).toBeLessThanOrEqual(height);
});
-286
View File
@@ -1,286 +0,0 @@
// System S13 (#330): the legacy admin and gallery pages open native System for their System tools. Each replaced
// control is a plain link (`workspace#/system/<id>`, a new tab), and the legacy flows S13 keeps still work.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const PAGES = Object.freeze({ admin: '/prompt_manager/admin', gallery: '/prompt_manager/gallery' });
const LABELS = Object.freeze({
overview: 'Overview',
appearance: 'Appearance',
sources: 'Sources & scans',
integrations: 'Integrations',
tagging: 'Auto-tagging',
maintenance: 'Maintenance',
backups: 'Backup & export',
diagnostics: 'Diagnostics & logs',
});
async function openPageOptions(page) {
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#settingsModal')).toBeVisible();
}
/** The auto-tag modal with its model rows read from /autotag/models. */
async function openAutoTag(page) {
const read = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/models'));
await page.locator('#autoTagBtn').click();
await read;
await expect(page.locator('#autoTagModal')).toBeVisible();
}
const notDownloaded = (page, request) => post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
const modelLoaded = (page, request) => post(request, '/__test__/tagging/loaded', { model: 'wd14-vit' });
// One row per System link of the design's §2 map: the page, the control's label, how to find it, the section it opens
// and what a test must arrange before the control shows.
const LINKS = Object.freeze([
{ page: 'admin', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'overview' },
{ page: 'admin', label: 'Maintenance', locate: page => page.locator('#maintenanceBtn'), section: 'maintenance' },
{ page: 'admin', label: 'Backup DB', locate: page => page.locator('#backupBtn'), section: 'backups' },
{ page: 'admin', label: 'Restore DB', locate: page => page.locator('#restoreBtn'), section: 'backups' },
{ page: 'gallery', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'appearance' },
{ page: 'admin', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (Unload Model)', arrange: modelLoaded, reveal: openAutoTag,
locate: page => page.locator('#unloadModelBtn'), section: 'tagging' },
{ page: 'gallery', label: 'Page options Maintenance', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsMaintenanceLink'), section: 'maintenance' },
{ page: 'gallery', label: 'Page options Sources & scans', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsSourcesLink'), section: 'sources' },
{ page: 'admin', label: 'Diagnostics', locate: page => page.locator('#diagnosticsBtn'), section: 'diagnostics' },
{ page: 'admin', label: 'View Logs', locate: page => page.locator('#logsBtn'), section: 'diagnostics' },
]);
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await post(request, '/__test__/reset');
await post(request, '/__test__/system/reset');
await post(request, '/__test__/tagging/reset');
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
page.legacyErrors = [];
page.on('pageerror', error => page.legacyErrors.push(error.message));
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/system/reset');
expect(page.legacyErrors).toEqual([]);
});
/** Opens the legacy page with the link showing; returns the link. */
async function openLink(page, request, link) {
if (link.arrange) await link.arrange(page, request);
await page.goto(PAGES[link.page]);
if (link.reveal) await link.reveal(page);
const control = link.locate(page);
await expect(control).toBeVisible();
return control;
}
// Each row opens its section in a new tab and sends no request from the legacy page (the design's `a System link sends
// no request from the legacy page`, checked per row so one slow page never times out the whole table).
for (const link of LINKS) {
test(`legacy ${link.page} ${link.label} opens System ${link.section}`, async ({ page, context, request }) => {
// The gallery's thumbnail startup check (K9) reads its status on a timer of its own; it is off here.
await page.addInitScript(() => {
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
});
const control = await openLink(page, request, link);
const legacyUrl = page.url();
await expect(control).toHaveAttribute('href', `workspace#/system/${link.section}`);
await expect(control).toHaveAttribute('target', '_blank');
await expect(control).toHaveAttribute('rel', 'noopener');
// The page's own start-up reads (list, film strips, settings) finish first; then the click must add none.
// Lazy thumbnails may still load whenever the layout changes; they are not the click's.
await page.waitForLoadState('networkidle');
const sent = [];
const record = item => { if (item.resourceType() !== 'image') sent.push(`${item.method()} ${item.url()}`); };
page.on('request', record);
const opened = context.waitForEvent('page');
await control.click();
const system = await opened;
await expect(system).toHaveURL(new RegExp(`/prompt_manager/workspace#/system/${link.section}$`));
page.off('request', record);
expect(sent, 'a System link sends no request from the legacy page').toEqual([]);
// System's page heading is "System"; the open section is the pressed button of its section switcher.
const main = system.locator('#workspace-main');
await expect(main.getByRole('heading', { level: 1, name: 'System', exact: true })).toBeVisible();
await expect(main.getByRole('group', { name: 'System sections', exact: true })
.getByRole('button', { name: LABELS[link.section], exact: true })).toHaveAttribute('aria-pressed', 'true');
expect(page.url()).toBe(legacyUrl);
await system.close();
});
}
test('kept admin flows still work', async ({ page, context }) => {
await page.goto(PAGES.admin);
const texts = page.locator('#resultsList .prompt-text');
await expect(texts.first()).toBeVisible();
// K1: sorting reorders the list.
for (const [value, order] of [['text_asc', 1], ['text_desc', -1]]) {
const listed = page.waitForResponse(item => /\/prompt_manager\/(recent|search)\?/.test(item.url()) && item.url().includes(`sort=${value}`));
await page.locator('#sortBy').selectOption(value);
await listed;
await expect.poll(async () => {
const shown = await texts.allTextContents();
// The server sorts case-insensitively (SQLite NOCASE), not by locale.
const key = text => text.toLowerCase();
const sorted = [...shown].sort((a, b) => order * (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
return shown.length > 1 && shown.join('\n') === sorted.join('\n');
}).toBe(true);
}
// K3: Add Prompt saves a prompt the list then shows.
await page.locator('#addPromptBtn').click();
await page.locator('#addPromptText').fill('Kept flow lighthouse');
const saved = page.waitForResponse(item => item.request().method() === 'POST' && item.url().endsWith('/prompt_manager/save'));
await page.locator('#saveNewPromptBtn').click();
expect((await saved).ok()).toBe(true);
await expect(page.locator('#addPromptModal')).toBeHidden();
await expect(texts.filter({ hasText: 'Kept flow lighthouse' })).toBeVisible();
// K1: a search narrows the list, and a selection enables the bulk buttons.
const all = await texts.allTextContents();
const word = all[0].trim().split(/\s+/)[0];
const searched = page.waitForResponse(item => item.url().includes('/prompt_manager/search?') && item.url().includes('text='));
await page.locator('#searchText').fill(word);
await page.locator('#searchBtn').click();
await searched;
await expect.poll(async () => {
const shown = await texts.allTextContents();
return shown.length > 0 && shown.length < all.length && shown.every(text => text.toLowerCase().includes(word.toLowerCase()));
}).toBe(true);
await expect(page.locator('#bulkDeleteBtn')).toBeDisabled();
await page.locator('#resultsList .prompt-checkbox').first().check();
for (const id of ['#bulkDeleteBtn', '#bulkTagBtn', '#bulkCategoryBtn']) await expect(page.locator(id)).toBeEnabled();
// K4: Stats reads the statistics again; Export downloads the prompts.
const stats = page.waitForResponse(item => item.url().endsWith('/prompt_manager/stats') && item.ok());
await page.locator('#statsBtn').click();
await stats;
await expect(page.getByText('Stats refreshed successfully!')).toBeVisible();
const download = page.waitForEvent('download');
await page.locator('#exportBtn').click();
expect((await download).suggestedFilename()).toMatch(/^prompts-\d{4}-\d{2}-\d{2}\.json$/);
// K5: Scan Images opens its dialog (with the quick backup) without starting a scan.
await page.locator('#scanBtn').click();
await expect(page.locator('#scanModal')).toBeVisible();
await expect(page.locator('#quickBackupBtn')).toBeVisible();
await page.locator('#cancelScan').click();
await expect(page.locator('#scanModal')).toBeHidden();
// K7: Metadata and Gallery open their pages in a new tab.
for (const [id, path] of [['#metadataBtn', '/prompt_manager/gallery.html'], ['#galleryBtn', '/prompt_manager/gallery']]) {
const opened = context.waitForEvent('page');
await page.locator(id).click();
const tab = await opened;
await tab.waitForLoadState('domcontentloaded');
expect(new URL(tab.url()).pathname).toBe(path);
await tab.close();
}
});
test('Page options keeps the page-only settings admin', async ({ page, request }) => {
const before = (await (await request.get('/prompt_manager/settings')).json()).settings;
await page.goto(PAGES.admin);
await expect(page.locator('#resultsList .prompt-text').first()).toBeVisible();
await page.locator('#pageOptionsBtn').click();
const dialog = page.locator('#settingsModal');
await expect(dialog).toBeVisible();
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only setting (G5): the list's Infinite Scrolling default.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id)))
.toEqual(['infiniteScrollDefault']);
await expect(page.locator('#infiniteScrollDefault')).not.toBeChecked();
await page.locator('#infiniteScrollDefault').check();
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith('/prompt_manager/settings'));
await page.locator('#saveSettings').click();
expect((await saved).postDataJSON()).toEqual({ infinite_scroll: true });
await expect(dialog).toBeHidden();
// The list header follows the saved default at once; nothing else changed.
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
const after = (await (await request.get('/prompt_manager/settings')).json()).settings;
expect(after).toEqual({ ...before, infinite_scroll: true });
await page.reload();
// The dialog shows the saved default once the page has read it (the header follows it first).
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#infiniteScrollDefault')).toBeChecked();
});
test('Page options keeps the page-only settings gallery', async ({ page }) => {
// Native Appearance keys and the startup prompt's own keys are in the shared object before the page opens.
const stored = { imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
checkThumbnailsAtStartup: false, defaultViewMode: 'list' };
await page.addInitScript(value => {
if (!sessionStorage.getItem('seeded')) {
sessionStorage.setItem('seeded', '1');
localStorage.setItem('gallerySettings', value);
}
}, JSON.stringify(stored));
const listed = page.waitForResponse(item => item.url().includes('/prompt_manager/images/output?'));
await page.goto(PAGES.gallery);
await listed;
// With no Page options control, a stored default view still opens the page in it.
await expect(page.locator('#listViewBtn')).toHaveClass(/bg-pm-accent/);
await openPageOptions(page);
const dialog = page.locator('#settingsModal');
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only settings (G5); the default view is System › Appearance's Default layout.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id))).toEqual([
'checkThumbnailsAtStartup', 'lazyLoadingToggle', 'defaultLimitSelect', 'gridColumnsSelect',
'infiniteScrollToggle', 'debugModeToggle', 'apiTimeoutInput']);
await expect(dialog.getByText('Default View Mode')).toHaveCount(0);
await page.locator('#defaultLimitSelect').selectOption('50');
await page.locator('#debugModeToggle').check();
await page.locator('#saveSettingsBtn').click();
await expect(dialog).toBeHidden();
const read = () => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings')));
let saved = await read();
expect(saved).toMatchObject({ ...stored, defaultLimit: 50, debugMode: true });
// Reset puts back only the page options' defaults; the Appearance, startup-prompt and default-view keys stay.
await openPageOptions(page);
page.once('dialog', dialog => dialog.accept());
await page.locator('#resetSettingsBtn').click();
await expect(page.getByText('Page options reset to defaults')).toBeVisible();
await expect(page.locator('#defaultLimitSelect')).toHaveValue('100');
saved = await read();
expect(saved).toMatchObject({ defaultViewMode: 'list', imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
defaultLimit: 100, debugMode: false, checkThumbnailsAtStartup: true, lazyLoading: true, gridColumns: 8,
infiniteScroll: false, apiTimeout: 30 });
});
test('the legacy auto-tag modal stays open after Manage in System', async ({ page, context, request }) => {
for (const legacy of ['admin', 'gallery']) {
await post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
const link = page.locator('#ggufModelStatus').getByRole('link', { name: 'Manage in System', exact: true });
await expect(link).toHaveAttribute('title', 'Opens System › Auto-tagging in a new tab');
// A downloaded model keeps its status text.
await expect(page.locator('#wd14VitModelStatus')).toHaveText('\u2713 Downloaded');
const opened = context.waitForEvent('page');
await link.click();
const system = await opened;
await expect(system).toHaveURL(/#\/system\/tagging$/);
await expect(page.locator('#autoTagModal')).toBeVisible();
await system.close();
// Downloaded in System meanwhile: reopening the modal reads the models again (CUJ 4).
await post(request, '/__test__/tagging/models', { unavailable: [] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
await expect(page.locator('#ggufModelStatus')).toHaveText('\u2713 Downloaded');
}
});
+1 -1
View File
@@ -21,7 +21,7 @@ export function mapLibraryConcept(reference) {
// Save view is the concept's own (saved views, #249 D16 retired).
const toolbar={...library.toolbar};
toolbar.items=toolbar.items.map(item=>{
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D205
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D206
// (#620) appends the old Dashboard's three sorts.
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first','Recently used','Most used','Name Z–A']};
// D36: the category list is the Library's real list, sorted alphabetically; the concept lists prompt order.
+97
View File
@@ -0,0 +1,97 @@
// #668 (D207): the old admin, gallery and metadata pages are gone. Their URLs, and the old tag bookmarks, lead into
// the workspace, against the real server.
import {startCoverage,saveCoverage} from '../../tools/vendor/browser-coverage.mjs';
import {test,expect} from './fixtures.mjs';
const cards=page=>page.locator('article[data-prompt-id]');
const card=(page,text)=>cards(page).filter({has:page.getByText(text,{exact:true})});
const filtersButton=page=>page.locator('#workspace-main search.toolbar').getByRole('button',{name:/^Filters(?: · \d)?$/});
const caption=page=>page.locator('#workspace-main .section-caption > span').first();
const heading=page=>page.locator('#workspace-main h1').first();
/** The workspace at exactly this hash. */
const at=hash=>url=>url.pathname.endsWith('/prompt_manager/workspace')&&url.search===''&&url.hash===hash;
test.beforeEach(async({page,request,browserName})=>{
await startCoverage(page,browserName);await expect(await request.post('/__test__/reset',{data:{native_library:true}})).toBeOK();
page.oldUrlErrors=[];page.on('pageerror',error=>page.oldUrlErrors.push(error.message));
// A deleted page asset that is still requested would answer 404.
page.missing=[];page.on('response',response=>{if(response.status()===404)page.missing.push(new URL(response.url()).pathname);});
});
test.afterEach(async({page,browserName})=>{
await saveCoverage(page,browserName);expect(page.oldUrlErrors).toEqual([]);expect(page.missing).toEqual([]);
});
for(const [url,hash,title] of [
['/prompt_manager/admin','#/library','Prompt library'],
['/prompt_manager/admin#/tags','#/tags','Tags & categories'],
['/prompt_manager/admin#/tags/','#/tags','Tags & categories'],
['/prompt_manager/admin#/something-else','#/library','Prompt library'],
['/prompt_manager/gallery','#/images','Images'],
['/prompt_manager/gallery.html','#/inspect','Inspect a file'],
['/prompt_manager/web','#/library','Prompt library'],
]) {
test(`${url} opens the workspace's ${title}`,async({page})=>{
await page.goto(url);
await expect(page).toHaveURL(at(hash));
await expect(heading(page)).toHaveText(title);
});
}
test('an old one-tag bookmark opens the Library filtered by that tag',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats');
await expect(page).toHaveURL(at('#/library?tag=cats'));
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(cards(page)).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 1');
});
test('an old two-tag bookmark matches all of the tags, and any of them with ?mode=or',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats,dogs');
await expect(caption(page)).toHaveText(/^0 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 1');
await page.goto('about:blank');
await page.goto('/prompt_manager/admin#/tags/cats,dogs?mode=or');
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(card(page,'Dog landscape')).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 2');
});
test('an old untagged bookmark asks the Library for the prompts without a tag',async({page})=>{
const listed=page.waitForResponse(item=>{const url=new URL(item.url());return url.pathname==='/prompt_manager/library'&&url.searchParams.get('tag_mode')==='untagged';});
await page.goto('/prompt_manager/admin#/tags/__untagged__');
expect((await (await listed).json()).tag_mode).toBe('untagged');
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));await expect(filtersButton(page)).toHaveText('Filters · 1');
});
test('the old dashboard URL shows the whole Library even after a tag bookmark in the same tab',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats');
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await page.goto('/prompt_manager/admin');
await expect(page).toHaveURL(at('#/library'));
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
});
test('Back from the workspace skips the old URL instead of bouncing through it',async({page})=>{
await page.goto('/prompt_manager/workspace#/overview');
await expect(heading(page)).toHaveText('Overview');
for(const [url,title] of [['/prompt_manager/admin#/tags/cats','Prompt library'],['/prompt_manager/gallery','Images']]) {
await page.goto(url);
await expect(heading(page)).toHaveText(title);
await page.goBack();
await expect(page).toHaveURL(at('#/overview'));
await expect(heading(page)).toHaveText('Overview');
}
});
test('the old pages\' scripts and stylesheet are no longer served',async({request})=>{
for(const asset of ['js/admin.js','js/gallery.js','js/tags-page.js','lib/tailwind/styles.css']) {
expect((await request.get(`/prompt_manager/${asset}`)).status(),asset).toBe(404);
}
});
test('the server itself redirects the two old pages that had no hash routes',async({request})=>{
for(const [url,target] of [['/prompt_manager/gallery','workspace#/images'],['/prompt_manager/gallery.html','workspace#/inspect']]) {
const response=await request.get(url,{maxRedirects:0});
expect([response.status(),response.headers().location]).toEqual([302,target]);
}
});
+7 -2
View File
@@ -102,11 +102,16 @@ test('inspection failures retry and a delayed previous selection cannot replace
release();await expect(role(details(page),'Positive')).toContainText('Dog landscape');
});
test('sender requires explicit destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
test('sender chooses the only destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
const host=await fakeHost(context,page);
try {
await page.goto(workspace);await select(page,'0:shared/same.png');await details(page).getByRole('button',{name:/^Send prompt pair to ComfyUI: /}).click();
const sender=dialog(page);await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeDisabled();
const sender=dialog(page);
// "One eligible node selects that node" (TESTING.md, D173); wait for discovery's
// answer, since Apply is disabled only while the sender is still looking for windows.
await expect(sender).toContainText('Sending to #pair-1 My prompt pair in Test ComfyUI.');
await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeEnabled();
expect(await host.evaluate(()=>window.applied)).toEqual([]);
const chosen=await chooseDestination(page);await chosen.getByRole('button',{name:'Preview changes',exact:true}).click();
for(const text of ['Existing positive','Existing negative','Cat portrait','blurry, watermark','trigger Cat portrait detail'])await expect(chosen).toContainText(text);
expect(await host.evaluate(()=>window.applied)).toEqual([]);
@@ -261,7 +261,8 @@ function measureReview() {
/**
* D107: the server's import plan in the concept's review: "Review LoRA import" with "LoRA reference data" as its `h3`,
* the concept's four rows with the plan's values plus Found and Network, the LoRAs it found (`details`), the hold
* the concept's four rows with the plan's values plus Found, Trigger words (#618, D210) and Network, the LoRAs it
* found (`details`), the hold
* line with the cache sentence in the concept's `p.small`, the D55 backup box, and Cancel / "Start import".
*/
function mapImportConcept(reference, plan) {
@@ -273,6 +274,7 @@ function mapImportConcept(reference, plan) {
heading: { ...reference.heading, text: 'LoRA reference data' },
grid: { ...reference.grid, rows: [['LoraManager', 'environment settings · alongside storage · library default'],
['Scope', plan.scope.label], ['Found', '2 metadata files · 2 LoRAs · 0 with local images'],
['Trigger words', '2 become tags'],
['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 2 example images from CivitAI'],
['Backup', `Create and verify before changes (${plan.backup.destination_label})`],
['Media on disk', 'No files are removed; image links are replaced']] },
@@ -333,9 +335,10 @@ test('LoRA import review comparison detects mutations', async ({ page, request }
const expected = mapImportConcept(concept, plan);
const paths = async () => diffInventory(expected, await page.evaluate(measureReview)).map(item => item.path);
expect(await paths()).toEqual([]);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Downloads'; });
expect(await paths()).toEqual(['grid.rows.4.0']);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Network'; });
// Network is the sixth row (after #618's Trigger words).
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Downloads'; });
expect(await paths()).toEqual(['grid.rows.5.0']);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Network'; });
const undoGrid = await mutate(page, { css: 'dialog#modal dl.meta-grid { column-gap: 3px; }' });
expect(await paths()).toEqual(expect.arrayContaining(['grid.columnGap']));
await undoGrid();
@@ -83,9 +83,29 @@ function mapPairRow(reference) {
};
}
/**
* D210 (#618, beyond the concept): Database adds "Tag cleanup" after "Pair category and tags", shaped like the concept's
* danger row (Unused prompt components') with its own button label, "Find tags".
*/
function mapTagRow(reference) {
return {
...reference,
surfaces: reference.surfaces.map(surface => {
const danger = surface.rows.find(row => row.title === 'Unused prompt components');
const at = surface.rows.findIndex(row => row.title === 'Pair category and tags');
if (!danger || at < 0) return surface;
return { ...surface, tree: [...surface.tree, 'div.operation'], rows: [...surface.rows.slice(0, at + 1),
{ ...danger, title: 'Tag cleanup', description: 'Find tags that are whole comma lists or are used nowhere. ' +
'Review them, then remove only what you tick.',
actions: danger.actions.map(action => ({ ...action, text: 'Find tags' })) },
...surface.rows.slice(at + 1)] };
}),
};
}
/** D102: the Metadata cache row says why its review is unavailable and its button is aria-disabled (D93's dimmed style). */
function mapMaintenanceConcept(reference) {
const mapped = mapPairRow(reference);
const mapped = mapTagRow(mapPairRow(reference));
return {
...mapped,
surfaces: mapped.surfaces.map(surface => ({ ...surface, rows: surface.rows.map(row => row.title !== 'Metadata cache' ? row : {
@@ -229,8 +249,8 @@ test('maintenance comparison detects mutations', async ({ page, request }) => {
const expected = mapMaintenanceConcept(concept);
const production = await productionMaintenance(page, 'dark');
expect(diffInventory(expected, production)).toEqual([]);
// Mapped only for the D192 row, the section differs only on the D102 row.
expect(diffInventory(mapPairRow(concept), production).map(item => item.path).sort()).toEqual([
// Mapped only for the D192 and D210 rows, the section differs only on the D102 row.
expect(diffInventory(mapTagRow(mapPairRow(concept)), production).map(item => item.path).sort()).toEqual([
'surfaces.1.rows.3.actions.0.cursor', 'surfaces.1.rows.3.actions.0.opacity', 'surfaces.1.rows.3.description']);
const measure = () => page.evaluate(measureMaintenance, '#workspace-main');
const paths = async () => diffInventory(expected, await measure()).map(item => item.path);
-280
View File
@@ -1,280 +0,0 @@
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
test.beforeEach(async ({ request, page, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset')).toBeOK();
page.workflowErrors = [];
page.on('pageerror', error => page.workflowErrors.push(error.message));
page.on('response', response => {
if (response.status() >= 500 && response.url().includes('/prompt_manager/')) {
page.workflowErrors.push(`${response.status()} ${response.url()}`);
}
});
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
});
test.afterEach(async ({ page, browserName }) => {
await saveCoverage(page, browserName);
expect(page.workflowErrors).toEqual([]);
});
// #249 S6b: the legacy admin page says where the library lives (the fixture's database is configured explicitly).
test('the admin page names the library location', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await expect(page.locator('#libraryLocation')).toHaveText('Library: browser.db (set in config.json)');
await expect(page.locator('#totalPrompts')).not.toHaveText('-');
});
test('actual gallery form saves a prompt that the admin page can edit and reload', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await page.locator('#addPromptBtn').click();
await page.locator('#addPromptText').fill('Browser saved landscape');
await page.locator('#addPromptCategory').fill('Browser tests');
await page.locator('#addPromptTagInput').fill('browser-tag');
await page.locator('#addPromptTagInput').press('Enter');
await page.locator('#saveNewPromptBtn').click();
await expect(page.locator('#addPromptModal')).toBeHidden();
await page.goto('/prompt_manager/admin');
const text = page.locator('.prompt-text').filter({ hasText: 'Browser saved landscape' });
await expect(text).toBeVisible();
const id = await text.getAttribute('data-id');
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Browser edited portrait');
// The page shows the edit at once and saves it after: reload only once the save answered (a reload that wins the
// race abandons the PUT, as seen on WebKit in CI).
const savedEdit = page.waitForResponse(item => item.request().method() === 'PUT'
&& item.url().endsWith(`/prompt_manager/prompts/${id}`));
await editor.press('Enter');
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
expect((await savedEdit).ok()).toBe(true);
await page.reload();
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
const saved = await request.post('/prompt_manager/save', { data: { text: 'Browser saved landscape' } });
expect((await saved.json()).prompt_id).not.toBe(Number(id));
});
// WebKit fails a fetch that a leaving page starts ("Fetch API cannot load … due to access control checks."), and
// Playwright reports that console error as a page error. A save's follow-up reads must not start once the page hides:
// here the statistics read after an in-place edit is held at the server while the page reloads.
test('an in-place edit whose follow-up reads outlive the page starts no read while it leaves', async ({ page, request }) => {
await page.goto('/prompt_manager/admin');
const text = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
const id = await text.getAttribute('data-id');
await expect(await request.post('/__test__/hold', { data: { path: '/prompt_manager/stats' } })).toBeOK();
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Cat portrait at dusk');
await editor.press('Enter');
const held = async () => (await (await request.get('/__test__/hold')).json()).held['/prompt_manager/stats'];
await expect.poll(held).toBe(1);
await page.reload({ waitUntil: 'commit' });
await expect(await request.post('/__test__/release')).toBeOK();
await expect(page.locator('.prompt-text').filter({ hasText: 'Cat portrait at dusk' })).toBeVisible();
});
// A leave that never happens (a stopped navigation, or one answered with a download) must not leave the list dead.
test('a page whose leave was called off reads its list again on the next input', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await expect(page.locator('.prompt-text').first()).toBeVisible();
await page.evaluate(() => window.dispatchEvent(new Event('beforeunload')));
await page.mouse.click(1, 1);
const reread = page.waitForResponse(response => new URL(response.url()).pathname === '/prompt_manager/recent');
await page.locator('#sortBy').selectOption('created_asc');
expect(new URL((await reread).url()).searchParams.get('sort')).toBe('created_asc');
await expect(page.locator('#resultsTitle')).toHaveText('Recent Prompts');
});
// The gallery's startup thumbnail check runs a second after load. When that second ends while the page is leaving,
// the check must start no read: WebKit fails it with "Fetch API cannot load … due to access control checks." and
// Playwright reports a page error (seen in CI on PR #289). The page clock makes the second end after the leave began.
for (const leave of ['beforeunload', 'pagehide']) {
test(`the gallery startup check starts no read after ${leave}`, async ({ page }) => {
await page.clock.install();
const statusReads = [];
page.on('request', req => { if (req.url().includes('/images/thumbnails/status')) statusReads.push(req.url()); });
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
await page.evaluate(type => window.dispatchEvent(new Event(type)), leave);
await page.clock.runFor(1500);
// A read made after the clock ran is listed, so the listener saw every status read.
await page.evaluate(() => fetch('/prompt_manager/images/thumbnails/status?probe=1'));
expect(statusReads.map(url => new URL(url).search)).toEqual(['?probe=1']);
});
}
// #379: the reviewed tags are that image's own tags; no prompt changes.
test('actual gallery review generates and persists tags for the selected root\'s image', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
await page.locator('#autoTagBtn').click();
const generated = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#startReviewBtn').click();
const generation = await generated;
expect(generation.request().postDataJSON().root_index).toBe(0);
await expect(page.locator('#reviewTagsContainer')).toContainText('sandstone');
const result = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
expect((await (await result).json()).success).toBe(true);
const data = await (await request.get('/prompt_manager/recent?limit=20')).json();
expect(data.results.find(prompt => prompt.text === 'Cat portrait').tags).toEqual(['cats']);
expect(data.results.find(prompt => prompt.text === 'Dog landscape').tags).toEqual(['dogs']);
const tagged = await (await request.get('/prompt_manager/images/output?mode=workspace&tags=sandstone')).json();
expect(tagged.images.map(image => `${image.root_index}:${image.path}`)).toEqual(['0:shared/same.png']);
});
test('actual Tags page reloads the selected filter and opens its image viewer', async ({ page }) => {
await page.goto('/prompt_manager/admin#/tags');
await page.locator('[data-tag-name="cats"]').click();
await expect(page.locator('#tagPromptsGrid')).toContainText('Cat portrait');
const dogs = page.waitForResponse(response => response.url().includes('/tags/dogs/prompts?'));
await page.locator('[data-tag-name="dogs"]').click();
const [shown] = (await (await dogs).json()).prompts[0].images;
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
await page.locator('#tagPromptsGrid img').first().click();
await expect(page.locator('.viewer-canvas img')).toBeVisible();
// The viewer's title names the shown image through the page's title callback. ViewerJS renders it only once the
// image is viewed, so closing at "visible" alone left the callback unrun on slower hosts (CI coverage missed it).
await expect(page.locator('.viewer-title')).toHaveText(shown.filename);
await page.locator('.viewer-container').getByRole('button', { name: 'Close', exact: true }).click();
await expect(page.locator('.viewer-container')).toHaveCount(0);
});
test('actual gallery serves colliding filenames and shows the matching prompt', async ({ page }) => {
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
const images = page.locator('#galleryGrid img[data-original]');
const first = await images.nth(0).getAttribute('data-original');
const second = await images.nth(1).getAttribute('data-original');
expect(first).not.toBe(second);
await page.locator('#galleryGrid .image-item[data-image-index="0"]').click();
await expect(page.locator('#metadata-content')).toContainText('Cat portrait');
await page.keyboard.press('ArrowRight');
await expect(page.locator('#metadata-content')).toContainText('Dog landscape');
await page.keyboard.press('Escape');
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
});
test('an edit collision is rejected by the backend and the page restores the original text', async ({ page }) => {
await page.goto('/prompt_manager/admin');
const original = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
const id = await original.getAttribute('data-id');
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Dog landscape');
const rejected = page.waitForResponse(response => response.request().method() === 'PUT' && response.url().endsWith(`/prompts/${id}`));
await editor.press('Enter');
expect((await rejected).status()).toBe(409);
await expect(editor).toHaveText('Cat portrait');
await page.reload();
await expect(page.locator(`.prompt-text[data-id="${id}"]`)).toHaveText('Cat portrait');
});
test('a delayed real Tags response cannot replace a newer selection', async ({ page }) => {
let release;
const delayed = new Promise(resolve => { release = resolve; });
let received;
const waiting = new Promise(resolve => { received = resolve; });
await page.route('**/prompt_manager/tags/cats/prompts?*', async route => {
const response = await route.fetch();
received();
await delayed;
await route.fulfill({ response });
});
await page.goto('/prompt_manager/admin#/tags');
await page.locator('[data-tag-name="cats"]').click();
await waiting;
await page.locator('[data-tag-name="dogs"]').click();
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
const completed = page.waitForResponse(response => response.url().includes('/tags/cats/prompts?'));
release();
await completed;
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
});
test('gallery infinite scroll appends a real backend page while retaining existing cards', async ({ page, request }) => {
await expect(await request.post('/__test__/reset', { data: { extra_images: 108 } })).toBeOK();
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(100);
await page.locator('#pageOptionsBtn').click();
await page.locator('#infiniteScrollToggle').check();
await page.locator('#saveSettingsBtn').click();
await expect(page.locator('#settingsModal')).toBeHidden();
const first = page.locator('#galleryGrid .image-item').first();
await first.evaluate(element => { element.dataset.preserved = 'yes'; });
await page.locator('#galleryScroll').evaluate(element => { element.scrollTop = element.scrollHeight; });
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(110);
await expect(first).toHaveAttribute('data-preserved', 'yes');
});
async function promptSnapshot(request) {
const response = await request.get('/prompt_manager/recent?limit=100');
await expect(response).toBeOK();
return (await response.json()).results.map(({ id, text, tags, images }) => ({
id, text, tags: [...tags].sort(),
images: images.map(image => image.image_path).sort(),
})).sort((a, b) => a.id - b.id);
}
function confirmNextDialog(page, accept, message) {
page.once('dialog', async dialog => {
expect(dialog.type()).toBe('confirm');
expect(dialog.message()).toContain(message);
await (accept ? dialog.accept() : dialog.dismiss());
});
}
async function deletePromptButton(page, text) {
const prompt = page.locator('.prompt-text').filter({ hasText: text });
await expect(prompt).toBeVisible();
const id = await prompt.getAttribute('data-id');
return page.locator(`[data-action="delete"][data-prompt-id="${id}"]`);
}
test('prompt deletion requires confirmation and can retry after a network failure', async ({ page, request }) => {
await page.goto('/prompt_manager/admin');
const before = await promptSnapshot(request);
const button = await deletePromptButton(page, 'Cat portrait');
let deletes = 0;
page.on('request', request => { if (request.method() === 'DELETE') deletes++; });
confirmNextDialog(page, false, 'delete this prompt');
await button.click();
expect(deletes).toBe(0);
expect(await promptSnapshot(request)).toEqual(before);
await page.route('**/prompt_manager/delete/*', route => route.abort('failed'), { times: 1 });
confirmNextDialog(page, true, 'delete this prompt');
await button.click();
await expect(page.getByText('Failed to delete prompt', { exact: true })).toBeVisible();
expect(await promptSnapshot(request)).toEqual(before);
confirmNextDialog(page, true, 'delete this prompt');
await button.click();
await expect(page.locator('.prompt-text')).toHaveCount(1);
await page.reload();
await expect(page.locator('.prompt-text')).toHaveCount(1);
expect(await promptSnapshot(request)).toEqual(before.filter(prompt => prompt.text !== 'Cat portrait'));
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
for (const url of await page.locator('#galleryGrid img[data-original]').evaluateAll(images => images.map(image => image.dataset.original))) {
await expect(await request.get(url)).toBeOK();
}
});
// #320: with previews in one folder, the legacy gallery still shows them, made
// and served from that folder (the fixture's own previews inside the sources
// are never served then).
test('the legacy gallery shows thumbnails kept in one folder', async ({ page, request }) => {
await expect(await request.post('/__test__/thumbnail-location', { data: { mode: 'folder' } })).toBeOK();
const served = page.waitForResponse(response =>
response.url().includes('/prompt_manager/images/serve/thumbnails/') && response.status() === 200);
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
const response = await served; // made in the folder before it was served
const name = decodeURIComponent(new URL(response.url()).pathname.split('/serve/thumbnails/')[1]);
const files = await (await request.get('/__test__/thumbnail-files')).json();
const stem = name.replace(/\.[^.]+$/, '');
expect(files.folder.some(file => /^[a-z0-9_-]+-[0-9a-f]{8}\//.test(file)
&& file.slice(file.indexOf('/') + 1).replace(/\.[^.]+$/, '') === stem)).toBe(true);
});
+4 -2
View File
@@ -565,9 +565,11 @@ test('URLs and media end with their owning session', async ({ page }) => {
// Replacement.
await choose(page, parityPng('f02.png'));
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
let state = await urls(page);
expect(state.revoked).toEqual([state.created[0]]);
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
await closeOpened(page);
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
@@ -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();
}
});
+216 -6
View File
@@ -269,15 +269,77 @@ test('an empty queue shows the empty notice only', async ({ page, request }) =>
await expect(reviewRow(page)).toHaveText('Needs review0');
});
test('load more appends the next page', async ({ page, request }) => {
const continuation = page => main(page).locator('.infinite-continuation');
const scrollToContinuation = page => continuation(page).evaluate(node => node.scrollIntoView({ block: 'end' }));
test('#657 D5: scrolling to the end of the queue loads the next page', async ({ page, request }) => {
await seed(request, 45);
const reads = reviewReads(page);
await open(page);
await expect(cards(page)).toHaveCount(40);
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images · more load as you scroll');
// Scrolling does the work, so there is no button.
await expect(continuation(page).getByRole('button')).toHaveCount(0);
await scrollToContinuation(page);
await expect(cards(page)).toHaveCount(45);
await expect(continuation(page)).toHaveCount(0);
expect(reads.filter(read => read === 'more')).toHaveLength(1);
});
test('#657 D5: a page that could not be read says so, and Retry reads it', async ({ page, request }) => {
await seed(request, 45);
await open(page);
let failing = true;
await page.route(url => url.pathname === '/prompt_manager/review/items' && url.searchParams.has('cursor'),
route => (failing ? route.fulfill({ status: 500, contentType: 'application/json',
body: JSON.stringify({ success: false, error: 'Internal error' }) }) : route.continue()));
const failed = page.waitForResponse(item => item.url().includes('cursor=') && item.status() === 500);
await scrollToContinuation(page);
await failed;
await expect(continuation(page).locator('p')).toHaveText('More items could not be loaded. Try again.');
const retry = continuation(page).getByRole('button', { name: 'Retry', exact: true });
await expect(retry).toBeVisible();
await expect(cards(page)).toHaveCount(40);
failing = false;
await retry.click();
await expect(cards(page)).toHaveCount(45);
await expect(continuation(page)).toHaveCount(0);
});
const frames = page => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
test('#657 D5: nothing loads behind an open dialog; closing it loads the page in view', async ({ page, request }) => {
// Two columns, so Link to a prompt… sits in the sticky panel beside the queue. At one column (touch) the panel
// follows the queue just above the continuation: bringing Link into view there loads the next page by itself.
await page.setViewportSize({ width: 1280, height: 800 });
await seed(request, 45);
const reads = reviewReads(page);
await open(page);
await linkButton(page).scrollIntoViewIfNeeded();
await frames(page);
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
await linkButton(page).click();
await expect(linkDialog(page)).toBeVisible();
await scrollToContinuation(page);
// Two frames: the observer's callback and the load it would schedule.
await frames(page);
await expect(cards(page)).toHaveCount(40);
expect(reads).not.toContain('more');
await linkDialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
await expect(linkDialog(page)).toHaveCount(0);
// The continuation is still in view, where the observer stays silent: closing the dialog loads the page.
await expect(cards(page)).toHaveCount(45);
});
test('#657 D5: without IntersectionObserver, Load more pages the queue', async ({ page, request }) => {
await page.addInitScript(() => { delete window.IntersectionObserver; });
await seed(request, 45);
await open(page);
await expect(cards(page)).toHaveCount(40);
const continuation = main(page).locator('.infinite-continuation');
await expect(continuation.locator('p')).toHaveText('40 of 45 images');
await continuation.getByRole('button', { name: 'Load more images', exact: true }).click();
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images');
await continuation(page).getByRole('button', { name: 'Load more images', exact: true }).click();
await expect(cards(page)).toHaveCount(45);
await expect(continuation).toHaveCount(0);
await expect(continuation(page)).toHaveCount(0);
});
test('a scan job with review items offers Review metadata in Activity', async ({ page, request }) => {
@@ -581,7 +643,7 @@ test('a live re-read keeps the loaded depth and the scroll position', async ({ p
await seed(request, 45);
await open(page);
await expect.poll(async () => (await streams(request)).streams).toBe(1);
await main(page).getByRole('button', { name: 'Load more images', exact: true }).click();
await scrollToContinuation(page);
await expect(cards(page)).toHaveCount(45);
await cards(page).last().scrollIntoViewIfNeeded();
const scrollTop = () => cards(page).first().evaluate(node => {
@@ -683,3 +745,151 @@ test('#536: a refused link stays in the dialog with the server\'s sentence', asy
expect(await pending(request)).toBe(1);
expect(await links(request)).toEqual([]);
});
test('#657 D4: Link to a prompt first lists the image\'s own prompts, and choosing one applies it', async ({ page, request }) => {
await seed(request, 2);
await open(page);
const harborHash = await context(page).locator('option', { hasText: 'Harbor lights at night' }).getAttribute('value');
await linkButton(page).click();
const dialog = linkDialog(page);
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
await expect(dialog.locator('.review-link-heading')).toHaveText(['From this image', 'Library']);
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur',
'Harbor lights at night / Soft negative, blur']);
// Typing searches the Library only; an empty box lists the image's prompts again.
const search = dialog.getByRole('searchbox');
await search.fill('zzz');
await expect(own).toBeHidden();
await expect(dialog.getByRole('status').first()).toHaveText('No prompt in the Library matches.');
await search.fill('');
await expect(own).toBeVisible();
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
await expect(submit).toHaveAttribute('aria-disabled', 'true');
const harbor = own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true });
await harbor.click();
await expect(harbor).toHaveAttribute('aria-pressed', 'true');
// The candidate carries its own negative.
await expect(dialog.getByRole('combobox', { name: 'Negative prompt', exact: true })).toBeHidden();
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
const decided = page.waitForResponse(item => /\/review\/items\/[^/]+\/decision$/.test(item.url()));
await submit.click();
const response = await decided;
expect(response.status()).toBe(200);
expect(response.request().postDataJSON().choice).toBe(harborHash);
await expect(dialog).toHaveCount(0);
await expect(toast(page)).toHaveText('Association accepted.');
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
expect(await links(request)).toEqual([{ filename: 'review_0000.png', prompt: 'Harbor lights at night',
pair_id: expect.any(Number), positive: 'Harbor lights at night', negative: 'Soft negative, blur' }]);
});
test('#657 D4: a refused candidate stays in the dialog with the server\'s sentence', async ({ page, request }) => {
await seed(request, 1);
await open(page);
await linkButton(page).click();
const dialog = linkDialog(page);
await dialog.getByRole('group', { name: 'From this image', exact: true }).getByRole('button').first().click();
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
body: JSON.stringify({ success: false, code: 'association-conflict', error: 'This image is already linked.' }) }));
await dialog.getByRole('button', { name: 'Link image', exact: true }).click();
await expect(dialog.locator('.warning-note')).toHaveText('This image is already linked.');
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await pending(request)).toBe(1);
});
test('#657 D3: a file whose prompts were shortened to the most used says so', async ({ page, request }) => {
await seed(request, 2);
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
const response = await route.fetch();
const body = await response.json();
const collapsed = body.filename === 'review_0000.png' ? { shown: 2, total: 81, paths: 165 } : null;
await route.fulfill({ response, json: { ...body, collapsed } });
});
await open(page);
const line = panel(page).locator('.review-collapsed');
await expect(line).toHaveText('Showing the 2 most used of 81 prompts in this file.');
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
await expect(line).toBeHidden();
});
test('#657 D4: typing drops a choice from the image; Link waits for a Library prompt and links it', async ({ page, request }) => {
await seed(request, 1, { unreadable: true });
await open(page);
await expect(panel(page).locator('p.small')).toHaveText('review_0000.png');
await linkButton(page).click();
const dialog = linkDialog(page);
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
const search = dialog.getByRole('searchbox');
await search.fill('harbor');
await expect(own).toBeHidden();
await expect(submit).toHaveAttribute('aria-disabled', 'true');
// An empty box lists the image's prompts again, none chosen.
await search.fill('');
await expect(own).toBeVisible();
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
await expect(submit).toHaveAttribute('aria-disabled', 'true');
await search.fill('harbor');
await dialog.getByRole('button', { name: 'Quiet harbor', exact: true }).click();
await dialog.getByRole('combobox', { name: 'Negative prompt', exact: true }).selectOption({ label: 'grainy' });
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
const sent = page.waitForRequest(item => /\/review\/items\/[^/]+\/(link|decision)$/.test(item.url()));
await submit.click();
const sentRequest = await sent;
expect(sentRequest.url()).toMatch(/\/link$/);
expect(sentRequest.postDataJSON()).toEqual(expect.objectContaining({ positive_id: expect.any(Number), pair_id: expect.any(Number) }));
await expect(toast(page)).toHaveText('Linked to Quiet harbor.');
const link = (await links(request)).find(row => row.filename === 'review_0000.png');
expect([link.positive, link.negative]).toEqual(['Quiet harbor', 'grainy']);
});
test('#657 D5: at one column, Info brings the panel into view without loading more until the reader moves', async ({ page, request }) => {
await page.setViewportSize({ width: 420, height: 900 });
await seed(request, 45);
const reads = reviewReads(page);
await open(page);
await expect(cards(page)).toHaveCount(40);
// The first cards are in view and the continuation, past the queue and the panel, is far away.
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
await expect(panel(page)).toBeInViewport();
// The continuation is near, but the panel stays put: two frames for the observer and the load it would schedule.
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top <= window.innerHeight + 250)).toBe(true);
expect(reads).not.toContain('more');
await expect(cards(page)).toHaveCount(40);
// The reader's next move releases it.
await page.mouse.wheel(0, 200);
await expect(cards(page)).toHaveCount(45);
});
test('#657 D4: a re-read that no longer offers the chosen image prompt drops it from the dialog', async ({ page, request }) => {
await seed(request, 1);
await open(page);
await linkButton(page).click();
const dialog = linkDialog(page);
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
// The decision is refused as stale, so the item is read again, and this time its Harbor path cannot be applied.
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
body: JSON.stringify({ success: false, code: 'review-conflict', error: 'This item changed. Choose again.' }) }));
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
const response = await route.fetch();
const body = await response.json();
const candidates = body.candidates.map(candidate => (candidate.positive?.text === 'Harbor lights at night'
? { ...candidate, state: 'unresolved', reason: 'Text is decided at run time' } : candidate));
await route.fulfill({ response, json: { ...body, candidates } });
});
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
await submit.click();
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur']);
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
await expect(submit).toHaveAttribute('aria-disabled', 'true');
await expect(dialog.locator('.warning-note')).toHaveText('This item changed. Choose again.');
expect(await pending(request)).toBe(1);
});
@@ -432,15 +432,12 @@ test('a failed settings read leaves the policy disabled with the reason', async
await expect(row.locator('input')).toBeDisabled();
});
test('the legacy Backup and Restore routes keep working and the admin page links to System', async ({ page, request }) => {
test('the legacy Backup and Restore routes keep working', async ({ request }) => {
const bytes = await backupBytes(request);
const restored = await request.post('/prompt_manager/restore', { multipart: { database_file: {
name: 'prompts_backup.db', mimeType: 'application/octet-stream', buffer: bytes } } });
await expect(restored).toBeOK();
expect((await restored.json()).success).toBe(true);
// #330: the admin page's Backup DB and Restore DB open System › Backup & export.
await page.goto('/prompt_manager/admin');
for (const id of ['#backupBtn', '#restoreBtn']) await expect(page.locator(id)).toHaveAttribute('href', 'workspace#/system/backups');
});
/** Start a fake running job (a metadata scan another tab started), which an exclusive restore must wait for. */
@@ -343,6 +343,7 @@ test('Review import shows replacement, blocked items and network effects with th
['LoraManager', 'environment settings · alongside storage · library default'],
['Scope', 'Replace 2 imported prompts with 3 LoRAs'],
['Found', '3 metadata files · 3 LoRAs · 0 with local images'],
['Trigger words', '3 become tags'],
['Protected', 'Nothing is protected'],
['Network', 'Downloads up to 3 example images from CivitAI'],
['Backup', 'Create and verify before changes (browser.db.backup_<date and time>)'],
@@ -387,7 +388,8 @@ test('saved pairs block the import: the review explains it and offers only Close
await enable(page);
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
// gridOf reads once; poll until the review has rendered its rows.
await expect.poll(async () => (await gridOf(page))[3]).toEqual(['Protected', '1 imported prompt used by saved pairs']);
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Protected'))
.toEqual(['Protected', '1 imported prompt used by saved pairs']);
await expect(dialog(page).locator('p.small')).toHaveText(
'Delete or change the saved pairs that use these prompts, then review the import again. Nothing was changed.');
expect(await dialog(page).locator('.dialog-actions button').allTextContents()).toEqual(['Close']);
@@ -395,6 +397,18 @@ test('saved pairs block the import: the review explains it and offers only Close
await expect(dialog(page)).toHaveCount(0);
});
test('the import review counts the trained words that are lists or sentences and not made tags (#618)',
async ({ page, request }) => {
await lora(request, { loras: 2, junk: true });
await openIntegrations(page);
await enable(page);
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Trigger words'))
.toEqual(['Trigger words', '2 become tags · 4 not made tags (lists or sentences)']);
await dialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
await expect(dialog(page)).toHaveCount(0);
});
test('unusable LoraManager settings: the review says why and offers only Close (#355)', async ({ page, request }) => {
await lora(request, { previous: 1, settings: 'invalid' });
await openIntegrations(page);
@@ -65,8 +65,8 @@ test('the section shows the concept rows; Metadata cache follows Q5 (D102)', asy
]))).toEqual([
['Database', [['Integrity & relationship checks', 'Check', ''], ['Duplicate prompt text', 'Review plan', ''],
['Optimize database', 'Review plan', ''], ['Unused prompt components', 'Review plan', 'danger'],
// D192 (#550): beyond the concept.
['Pair category and tags', 'Review plan', '']]],
// D192 (#550) and D210 (#618): beyond the concept.
['Pair category and tags', 'Review plan', ''], ['Tag cleanup', 'Find tags', 'danger']]],
['Images & cache', [['Missing-file links', 'Review plan', 'danger'], ['Duplicate image files', 'Find duplicates', ''],
['Thumbnail cache', 'Review options', ''], ['Metadata cache', 'Review plan', '']]],
]);
@@ -482,6 +482,104 @@ test('Find duplicates starts a job; its view links Review groups; Keep radios bu
expect((await request.get('/prompt_manager/images/serve/s7-dupes/copy.png?root=0')).status()).toBe(404);
});
test('D210: Tag cleanup finds comma and unused tags, reviews only the ticked rule and deletes only it (#618)',
async ({ page, request }) => {
await expect(await request.post('/__test__/system/tag-cleanup')).toBeOK();
const previews = [];
page.on('request', item => { if (item.url().endsWith(PREVIEW_URL)) previews.push(item.postDataJSON()); });
const before = (await serverJson(request, '/__test__/system/backups')).safety.length;
await openMaintenance(page);
const tagRow = row(page, 'Tag cleanup');
await expect(tagRow.locator('p')).toHaveText('Find tags that are whole comma lists or are used nowhere. Review them, '
+ 'then remove only what you tick.');
await tagRow.getByRole('button', { name: 'Find tags', exact: true }).click();
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const findId = page.url().split('/').pop();
const main = page.locator('#workspace-main');
await expect(main.locator('h1')).toHaveText('Find tags to clean up');
const reviewTags = main.getByRole('button', { name: 'Review tags', exact: true });
await expect(reviewTags).toBeVisible();
await expect(main.locator('.stat-row .stat dt')).toHaveText(['Found']);
await expect(main.locator('.stat-row .stat dd')).toHaveText(['4']);
// The found rows are tags (records): plain text, never an open action; no lora: tag is a comma finding.
const results = main.getByRole('region', { name: 'Results', exact: true });
await expect(results.locator('.outcome-files > .file-row')).toHaveText(['s618 a, b · Tags containing a comma',
's618 x,y · Tags containing a comma', 's618-ghost · Tags with no links', 's618-spirit · Tags with no links']);
await expect(results.locator('.outcome-files button')).toHaveCount(0);
await reviewTags.click();
const review = dialog(page);
await expect(review.locator('#modal-title')).toHaveText('Review tag cleanup');
const status = review.locator('#modal-body > p[role="status"]');
await expect(status).toHaveText('0 tags selected');
const start = review.getByRole('button', { name: 'Review cleanup', exact: true });
await expect(start).toBeDisabled();
const comma = review.locator('.tag-cleanup-rule[data-rule="comma"]');
const unused = review.locator('.tag-cleanup-rule[data-rule="unused"]');
await expect(comma.locator(':scope > label')).toHaveText('Tags containing a comma (2)');
await expect(unused.locator(':scope > label')).toHaveText('Tags with no links (2)');
await expect(comma.locator(':scope > p.small')).toHaveText('A whole list saved as one tag, usually from a LoRA\'s '
+ 'trained words. Removes the tag from its prompts, pairs and images and deletes it.');
await expect(review.locator('#modal-body > p.small').last()).toHaveText(/^Nothing is deleted until you review and apply/);
// Nothing is ticked; the tag rows are built when Show tags first opens.
await expect(comma.locator('details input')).toHaveCount(0);
await comma.locator(':scope > label input').check();
await expect(status).toHaveText('2 tags selected');
await expect(start).toBeEnabled();
await comma.locator('details > summary').click();
const tags = comma.locator('details label');
await expect(tags).toHaveText(['s618 a, b · 1 prompt', 's618 x,y · no links']);
await expect(tags.locator('input')).toHaveCount(2);
for (const box of await tags.locator('input').all()) await expect(box).toBeChecked();
await tags.nth(1).locator('input').uncheck();
await expect(status).toHaveText('1 tag selected');
expect(await comma.locator(':scope > label input').evaluate(box => [box.checked, box.indeterminate])).toEqual([false, true]);
await tags.nth(1).locator('input').check();
await expect(status).toHaveText('2 tags selected');
await start.click();
await expect(dialog(page).locator('#modal-title')).toHaveText('Review maintenance plan');
await expect(dialog(page).locator('#modal-body > h3')).toHaveText('Tag cleanup');
expect(previews).toHaveLength(1);
expect(previews[0].operation).toBe('tag_cleanup');
expect(previews[0].options.job_id).toBe(findId);
expect(previews[0].options.select.map(entry => [entry.rule, entry.tag_ids.length])).toEqual([['comma', 2]]);
const grid = await gridOf(page);
expect(grid.slice(0, 2)).toEqual([['Scope', 'Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)'],
['Protected', 'Nothing is protected']]);
expect(grid[2][1]).toMatch(/^Always created and verified first \(.+\.backup_<date and time>\)$/);
expect(grid[3]).toEqual(['Media on disk', 'No files are removed']);
await dialog(page).getByRole('button', { name: 'Apply reviewed operation', exact: true }).click();
await expect(page).not.toHaveURL(new RegExp(findId));
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const job = await ended(request, page.url().split('/').pop());
expect([job.kind, job.title, job.state, job.counters.changed, job.counters.protected])
.toEqual(['maintenance', 'Tag cleanup', 'finished', 2, 0]);
await expect(main.locator('h1')).toHaveText('Tag cleanup');
await results.locator('.outcome-list > button').filter({ hasText: 'Changed' }).click();
await expect(results.locator('.outcome-files > .file-row')).toHaveText([
'Deleted tag “s618 a, b” (Tags containing a comma) · removed from 1 prompt',
'Deleted tag “s618 x,y” (Tags containing a comma)']);
// The safety backup is always taken.
expect((await serverJson(request, '/__test__/system/backups')).safety.length).toBe(before + 1);
// Tags & categories: the other rule's tags and the lora: tag are still there.
const names = (await serverJson(request, '/prompt_manager/vocabulary/tags?limit=200')).tags.map(tag => tag.name);
expect(names).toEqual(expect.arrayContaining(['s618-ghost', 's618-spirit', 's618-clean', 'lora:S618, v2']));
expect(names).not.toContain('s618 a, b');
expect(names).not.toContain('s618 x,y');
// A second search finds only the rest.
await openMaintenance(page);
await row(page, 'Tag cleanup').getByRole('button', { name: 'Find tags', exact: true }).click();
await expect(page).not.toHaveURL(new RegExp(job.id));
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const again = await ended(request, page.url().split('/').pop());
expect(again.counters.found).toBe(2);
const body = await serverJson(request, `/prompt_manager/maintenance/tag_cleanup/${again.id}`);
expect(body.rules.map(rule => [rule.id, rule.findings.map(finding => finding.name)]))
.toEqual([['comma', []], ['unused', ['s618-ghost', 's618-spirit']]]);
});
test('the duplicates review pages ten groups at a time and keeps each choice (D101)', async ({ page, request }) => {
await expect(await request.post('/__test__/system/duplicate-files', { data: { groups: 11 } })).toBeOK();
const groupReads = [];
@@ -99,7 +99,7 @@ test('a rename while searching re-reads the same search and sort',async({page})=
test('Untagged prompts Browse opens the Library on exactly the prompts without tags',async({page})=>{
await open(page);
await untagged(page).getByRole('button',{name:'Browse',exact:true}).click();
await expect(page).toHaveURL(/#\/library$/);
await expect(page).toHaveURL(url=>url.hash==='#/library?tag_mode=untagged');
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
await expect(shelf(page)).toHaveCount(2);
await expect(page.locator('#workspace-main .section-caption > span').first()).toHaveText(/^2 positive prompts · /);
+3 -1
View File
@@ -23,7 +23,9 @@ async function seed(request,data={}) {
const response=await request.post('/__test__/vocabulary/reset',{data});await expect(response).toBeOK();return response.json();
}
async function expectLibrary(page,{tags='',category='',count}) {
await expect(page).toHaveURL(/#\/library$/);
// #668 (D207): a tag Browse lands on the filtered address; a category is not in the address.
const hash=tags?`#/library?${new URLSearchParams({tag:tags})}`:'#/library';
await expect(page).toHaveURL(url=>url.hash===hash);
await expect(main(page).getByRole('heading',{level:1})).toHaveText('Prompt library');
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
await expect(page.getByRole('searchbox',{name:'Search workspace',exact:true})).toHaveValue('');
+3 -3
View File
@@ -118,9 +118,9 @@ test('all shell destinations deep-link, reload and expose working existing appli
await expect(page.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true })).toBeVisible();
await expect(page.locator('a[href*="/prompt_manager/admin"], a[href*="/prompt_manager/gallery"]')).toHaveCount(0);
await expect(page.locator('#workspace-main').getByText('Your existing tools remain available')).toHaveCount(0);
// The legacy pages themselves stay at their URLs.
for (const legacy of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
await expect(await request.get(legacy)).toBeOK();
// The old pages' URLs stay and lead into the workspace (#668; old-urls.spec.mjs follows each one).
for (const old of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
await expect(await request.get(old)).toBeOK();
}
});
@@ -8,7 +8,7 @@ reaches a real LoraManager, ComfyUI install or the network:
the image cache, forgets every LoRA import and injected failure, and opens
the download gate;
- ``POST /__test__/integrations/lora-manager``
``{loras, civitai, preview, previous, settings}`` writes
``{loras, civitai, preview, previous, settings, junk}`` writes
``custom_nodes/ComfyUI-Lora-Manager`` (detected through the
``folder_paths`` stub's base path) and ``loras`` LoRAs under
``models/loras``: each a ``<stem>.safetensors`` model beside its
@@ -18,7 +18,9 @@ reaches a real LoraManager, ComfyUI install or the network:
downloads it only for a LoRA without a local preview); ``previous`` saves
that many earlier ``lora-manager`` imports with tags and image links;
``settings: "invalid"`` makes LoraManager's settings file unreadable JSON
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); ``junk``
adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which
the import does not make tags (#618);
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
download until it is released (``{"hold": false}``), so a test sees the job
while it downloads;
@@ -145,6 +147,9 @@ def register_integrations_commands(app, routes, api, root: Path):
for number in range(count):
stem = f"style_{number + 1:02}"
civitai = {"trainedWords": [f"trigger{number + 1}"]}
if data.get("junk") is True:
# #618: a comma list and a model call, never made tags.
civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"]
if data.get("civitai") is True:
civitai["images"] = [
{
+22 -7
View File
@@ -15,8 +15,9 @@ after the plain ones in this order:
- ``conflict``: an item whose file was linked to another prompt ("Misty
forest path") after it was queued (the next scan or monitor pass would
remove the item); applying a sampler path then conflicts with that link.
- ``limited``: a graph of 17 samplers, each with its own prompt, which the
recorder stores ``limited`` (more than 16 candidates, so none are stored).
- ``limited``: an item recorded while its evidence is over the 8 MiB bound
(simulated), so the recorder stores it ``limited`` without candidates.
More than 16 candidates are collapsed instead (#657 addendum D3).
An A1111 block with two negative lines is not queued any more: it offers
no candidate to choose (#284).
- ``unreadable`` (#536): an item whose stored candidates are all
@@ -79,8 +80,6 @@ CONCEPT_POSITIVE = (
"mountain peaks, cinematic composition, atmospheric mist, fine detail"
)
CONCEPT_NEGATIVE = "blurry, low quality, low resolution"
# More candidates than an item stores (16): the ``limited`` item.
LIMITED_SAMPLERS = 17
# More than one queue page (40), so Load more has a second page.
MAX_ITEMS = 45
_TABLES = (
@@ -210,6 +209,23 @@ def _linked_after_queueing(api: PromptManagerAPI, path: Path) -> None:
api.db.link_image_to_prompt(prompt_id, str(path))
def _limited(api: PromptManagerAPI, path: Path) -> None:
"""Record ``path`` as if its evidence were over the 8 MiB bound."""
from unittest.mock import patch
from utils import review_capture
real = review_capture.canonical_evidence
def capped(value):
if value.get("candidates"):
raise ValueError("Review evidence is larger than 8 MiB")
return real(value)
with patch.object(review_capture, "canonical_evidence", side_effect=capped):
_record(api, path, "limited")
def _unavailable(api: PromptManagerAPI, root: Path, path: Path) -> None:
from py.config import GalleryConfig
@@ -296,9 +312,8 @@ def seed_review(
_png(path, (70, 40, 120))
_unreadable(api, path)
elif kind == "limited":
many = tuple(f"{POSITIVES[0]} {n}" for n in range(LIMITED_SAMPLERS))
_png(path, (90, 90, 90), graph=_graph(positives=many))
_record(api, path, "limited")
_png(path, (90, 90, 90))
_limited(api, path)
else:
_png(path, (20, 140, 90))
_unavailable(api, root, path)
+22
View File
@@ -52,6 +52,10 @@ read. These per-server hooks only change what a System test needs on top:
``{"groups": n}`` adds ``n`` more groups of two copies each, and
``{"trio": false}`` leaves the three ``same.png``/``copy.png`` copies out,
and ``{"long": true}`` adds a group under long names with no spaces;
- ``POST /__test__/system/tag-cleanup`` (#618) saves ``S618 owner`` tagged
``s618 a, b`` (a comma list), ``s618-clean`` and ``lora:S618, v2`` (a LoRA's
identity tag, never a comma finding), and adds the unused tags
``s618 x,y`` (a fullwidth comma), ``s618-ghost`` and ``s618-spirit``;
- ``GET /__test__/system/digest`` (S7) answers the sha256 of the database's
rows (a read-only dump) and of every media file under ``output`` and
``input`` (not the automatic previews in ``thumbnails``), so a test proves
@@ -349,6 +353,24 @@ def register_system_commands(app, routes, api, root: Path):
conn.commit()
return web.json_response({"success": True})
@routes.post("/__test__/system/tag-cleanup")
async def tag_cleanup(request):
def seed():
text = "S618 owner"
api.db.save_prompt(
text,
prompt_hash=hashlib.sha256(text.lower().encode()).hexdigest(),
tags=["s618 a, b", "s618-clean", "lora:S618, v2"],
)
with api.db.model.get_connection() as conn:
conn.executemany(
"INSERT INTO tags(name) VALUES(?)",
[("s618 x\uff0cy",), ("s618-ghost",), ("s618-spirit",)],
)
await api._run_in_executor(seed)
return web.json_response({"success": True})
@routes.post("/__test__/system/pair-metadata")
async def pair_metadata(request):
def seed():
+4 -2
View File
@@ -210,7 +210,7 @@ test(`${label} follows actual ComfyUI light and dark palettes`, async ({ page },
}
});
test(`${label} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
test(`${label} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
await addEditor(page, type);
const popupPromise = page.waitForEvent('popup');
await page.locator('.pm-focused').getByRole('button', { name: 'Web UI ↗', exact: true }).click();
@@ -219,8 +219,10 @@ test(`${label} Web UI button opens the workspace; legacy pages still load`, asyn
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
await expect(page.locator('.pm-focused').getByRole('status').filter({ hasText: 'Web UI opened.' })).toHaveText('Web UI opened.');
// #668: the old gallery URL leads to the workspace's Images page.
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
await expect(popup.locator('#addPromptBtn')).toBeVisible();
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
await popup.close();
});
+4 -2
View File
@@ -84,7 +84,7 @@ test('all node schemas and extension entrypoints load from the real host', async
});
for (const type of ['PromptManager', 'PromptManagerText']) {
test(`${type} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
test(`${type} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
await page.evaluate(async type => {
const { app } = await import('/scripts/app.js');
const node = LiteGraph.createNode(type);
@@ -97,8 +97,10 @@ for (const type of ['PromptManager', 'PromptManagerText']) {
await popup.waitForLoadState('domcontentloaded');
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
// #668: the old gallery URL leads to the workspace's Images page.
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
await expect(popup.locator('#addPromptBtn')).toBeVisible();
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
await popup.close();
});
}
+4 -2
View File
@@ -37,12 +37,14 @@ test('workspace serves real library data beside either ComfyUI renderer', async
await expect(workspace.getByText('No matching images · 0 images', { exact: true })).toBeVisible();
await expect(workspace.locator('.gallery-body > .empty')).toHaveText('No matching images. Try another search or category.');
}
// D29: Images no longer links the legacy gallery; #525: nor does Overview. The page stays at its URL.
// D29: Images no longer links the old gallery; #525: nor does Overview. #668: its URL leads to the workspace.
await expect(workspace.locator('#workspace-main a[href="/prompt_manager/gallery"]')).toHaveCount(0);
await workspace.evaluate(() => { location.hash = '/overview'; });
const imagesCard = workspace.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true });
await expect(imagesCard).toHaveAttribute('href', '#/images');
expect((await workspace.request.get('/prompt_manager/gallery')).ok()).toBe(true);
const oldGallery = await workspace.request.get('/prompt_manager/gallery');
expect(oldGallery.ok()).toBe(true);
expect(new URL(oldGallery.url()).pathname).toMatch(/\/prompt_manager\/workspace$/);
await workspace.evaluate(() => { location.hash = '/images'; });
await workspace.reload();
await expect(workspace.locator('#workspace-main h1')).toHaveText('Images');
+16
View File
@@ -13,6 +13,22 @@ ffmpeg -f lavfi -i testsrc=size=32x32:rate=4:duration=1 \
Browser tests use the committed file; FFmpeg is not required to run them.
# AVIF metadata fixture
`media/comfyui_avif.avif` (96x96, about 1 KB) is an original synthetic gradient
written by ComfyUI's own AVIF writer, `SaveImageAdvanced` (PyAV with SVT-AV1,
then `inject_avif_metadata`), so it carries the EXIF item ComfyUI writes:
`prompt:{json}` at tag 0x0110 and `workflow:{json}` at 0x010F. It is dedicated
to the public domain under CC0-1.0. `utils/exif_text`, the scan and the monitor
read it; `tests/test_avif_media_type.py` and `tests/test_api_admin.py` cover it.
Reproduce from a ComfyUI checkout with ComfyUI's Python (torch and PyAV with
SVT-AV1), where `comfy_extras` imports:
```sh
python custom_nodes/ComfyUI-PromptManager/tools/make_avif_fixture.py
```
# Local Inspect header fixtures
`local-inspect/tiny.jpg` (48x32) and `local-inspect/tiny.webp` (40x24) are original
+1 -1
View File
@@ -935,7 +935,7 @@
"reason_code": "multistage-differs",
"selection": null,
"positive": null,
"negative": null,
"negative": "blurry, lowres",
"candidate_count": 0,
"facts": {
"seed": {
+2
View File
@@ -63,6 +63,7 @@
"GET /prompt_manager/lora/status",
"GET /prompt_manager/lora/trigger-words",
"GET /prompt_manager/maintenance/duplicates/{job_id}",
"GET /prompt_manager/maintenance/tag_cleanup/{job_id}",
"GET /prompt_manager/pairs",
"GET /prompt_manager/pairs/export",
"GET /prompt_manager/pairs/{pair_id}",
@@ -134,6 +135,7 @@
"POST /prompt_manager/jobs/image-tags",
"POST /prompt_manager/jobs/model-download",
"POST /prompt_manager/jobs/scan",
"POST /prompt_manager/jobs/tag_cleanup",
"POST /prompt_manager/jobs/thumbnails",
"POST /prompt_manager/jobs/{job_id}/cancel",
"POST /prompt_manager/library",
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 993 B

-50
View File
@@ -1,50 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture() {
const panel = { innerHTML: '', isConnected: true };
const requests = new Map();
const context = vm.createContext({ document: { readyState: 'loading', addEventListener() {},
getElementById: id => id === 'metadata-content' ? panel : null },
window: {}, console: { error() {} },
});
const Admin = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/admin.js'), 'utf8') + '\nPromptAdmin;', context, { filename: path.join(__dirname, '../../web/js/admin.js') });
const manager = Object.create(Admin.prototype);
manager.extractImageMetadata = url => new Promise((resolve, reject) => requests.set(url, { resolve, reject }));
manager.updateMetadataSidebar = metadata => { panel.innerHTML = metadata?.imagePath || 'No metadata'; };
manager.hideModal = () => {};
const load = url => manager.loadMetadataForImage({ getAttribute: () => url });
return { manager, panel, requests, load };
}
test('admin metadata and copy actions stay on the selected image', async () => {
const { manager, panel, requests, load } = fixture();
const old = load('old.png');
const current = load('current.png');
requests.get('current.png').resolve({ imagePath: 'current.png' }); await current;
requests.get('old.png').resolve({ imagePath: 'old.png' }); await old;
assert.equal(panel.innerHTML, 'current.png');
assert.equal(manager.currentMetadata.imagePath, 'current.png');
});
test('navigation clears old action data and late errors cannot replace current metadata', async () => {
const { manager, panel, requests, load } = fixture();
manager.currentMetadata = { imagePath: 'previous.png' };
const old = load('old.png');
assert.equal(manager.currentMetadata, null);
const current = load('current.png');
requests.get('current.png').resolve({ imagePath: 'current.png' }); await current;
requests.get('old.png').reject(new Error('old error')); await old;
assert.equal(panel.innerHTML, 'current.png');
});
for (const close of ['close gallery', 'detach sidebar']) {
test(`${close} prevents pending admin metadata from restoring copy state`, async () => {
const { manager, panel, requests, load } = fixture();
const pending = load('old.png');
if (close === 'close gallery') manager.closeGallery();
else panel.isConnected = false;
requests.get('old.png').resolve({ imagePath: 'old.png' }); await pending;
assert.equal(manager.currentMetadata, null);
assert.notEqual(panel.innerHTML, 'old.png');
});
}
+2 -18
View File
@@ -9,15 +9,11 @@ const path = require("node:path");
const vm = require("node:vm");
const MODULES = {
"html-escape.js": ["HtmlEscape", "escapeHtml", "escapeAttr"],
"data-actions.js": ["DataActions"],
"api-client.js": ["ApiClient"],
"list-state.js": ["ListState"],
"sse-stream.js": ["SseStream"],
"png-metadata.js": ["PngMetadata"],
"view-router.js": ["ViewRouter"],
"prompt-list-sort.js": ["PromptListSort"],
"comfy-metadata.js": ["ComfyMetadata"],
"gallery-settings.js": ["GallerySettings"],
"legacy-links.js": ["LegacyLinks"],
};
function loadInFakeBrowser(file) {
@@ -60,15 +56,3 @@ for (const [file, globals] of Object.entries(MODULES)) {
}
});
}
test("the browser escapeHtml global is the same function as HtmlEscape.escapeHtml", () => {
const window = loadInFakeBrowser("html-escape.js");
assert.equal(window.escapeHtml, window.HtmlEscape.escapeHtml);
assert.equal(window.escapeAttr, window.escapeHtml);
assert.equal(window.escapeHtml(`<a href="x">`), "&lt;a href=&quot;x&quot;&gt;");
});
test("the browser ViewRouter global resolves the tags deep link", () => {
const window = loadInFakeBrowser("view-router.js");
assert.equal(window.ViewRouter.resolveView("#/tags/a"), "tags");
});
+28
View File
@@ -1042,3 +1042,31 @@ test("Split workflow-only metadata recovers serialized fields and connected comp
assert.equal(result.negativePrompt, "avoid blurry watermark");
assert.equal(result.checkpoint, "model.safetensors");
});
// PromptManagerPair roles (moved from pair-metadata.test.js when the old gallery was retired, #668).
function pairGraph(positive = 0, negative = 1) {
return {
1:{class_type:'PromptManagerPair',inputs:{text:'cat',negative_text:'blur',prepend_text:'trigger',append_text:'detail'}},
2:{class_type:'KSampler',inputs:{positive:['1',positive],negative:['1',negative],model:['3',0]}},
3:{class_type:'CheckpointLoaderSimple',inputs:{ckpt_name:'m.safetensors'}},
};
}
test('paired conditioning uses actual output roles and composes only positive', () => {
const metadata = extractGenerationParams({prompt:pairGraph()});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
const swapped = extractGenerationParams({prompt:pairGraph(1,0)});
assert.equal(swapped.positivePrompt,'blur');
assert.equal(swapped.negativePrompt,'trigger cat detail');
});
test('paired strings passed through encoders retain the connected output slot', () => {
const prompt=pairGraph();
prompt[4]={class_type:'CLIPTextEncode',inputs:{text:['1',2]}};
prompt[5]={class_type:'CLIPTextEncode',inputs:{text:['1',3]}};
prompt[2].inputs.positive=['4',0];prompt[2].inputs.negative=['5',0];
const metadata=extractGenerationParams({prompt});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
});
-49
View File
@@ -1,49 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { readAction, dispatch } = require("../../web/js/data-actions.js");
test("readAction parses promptId and index as integers", () => {
const parsed = readAction({ action: "open-film", promptId: "42", index: "3" });
assert.equal(parsed.action, "open-film");
assert.equal(parsed.promptId, 42);
assert.equal(parsed.index, 3);
});
test("readAction turns missing or non-numeric ids into null", () => {
assert.equal(readAction({ action: "edit" }).promptId, null);
assert.equal(readAction({ action: "edit", promptId: "abc" }).promptId, null);
assert.equal(readAction({ action: "edit", index: "" }).index, null);
});
test("readAction passes string fields through untouched", () => {
const parsed = readAction({ action: "remove-tag", tag: `a "quoted" tag`, url: "/x?y=1&z=2", copyText: "p" });
assert.equal(parsed.tag, `a "quoted" tag`);
assert.equal(parsed.url, "/x?y=1&z=2");
assert.equal(parsed.copyText, "p");
});
test("readAction tolerates a missing dataset", () => {
assert.equal(readAction(undefined).action, "");
assert.equal(readAction(null).promptId, null);
});
test("dispatch calls the matching handler with the parsed action and extras", () => {
const calls = [];
const handled = dispatch(
{ action: "edit", promptId: "7" },
{ edit: (a, el) => calls.push([a.promptId, el]) },
"element",
);
assert.equal(handled, true);
assert.deepEqual(calls, [[7, "element"]]);
});
test("dispatch returns false and calls nothing for an unknown or empty action", () => {
let called = 0;
const handlers = { edit: () => called++ };
assert.equal(dispatch({ action: "other" }, handlers), false);
assert.equal(dispatch({}, handlers), false);
assert.equal(dispatch({ action: "constructor" }, handlers), false, "no prototype lookups");
assert.equal(called, 0);
});
-76
View File
@@ -1,76 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function fixture() {
const context = vm.createContext({ document: { addEventListener() {}, getElementById() {} },
window: {}, console: { error() {} }, escapeHtml: value => value });
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
const requests = new Map();
manager.extractImageMetadata = url => {
const pending = deferred();
requests.set(url, pending);
return pending.promise;
};
manager.displayMetadata = (metadata, panel) => {
panel.innerHTML = metadata?.positivePrompt || 'No metadata';
manager.currentMetadata = metadata;
};
manager.stopViewerSlideshow = () => {};
return { manager, requests, panel: { innerHTML: '', isConnected: true } };
}
test('a late response cannot overwrite the selected image or copy state', async () => {
const { manager, requests, panel } = fixture();
const first = manager.loadImageMetadata('old.png', panel);
const second = manager.loadImageMetadata('new.png', panel);
requests.get('new.png').resolve({ positivePrompt: 'new prompt' });
await second;
requests.get('old.png').resolve({ positivePrompt: 'old prompt' });
await first;
assert.equal(panel.innerHTML, 'new prompt');
assert.equal(manager.currentMetadata.positivePrompt, 'new prompt');
});
test('navigation clears old action data while the new request is pending', async () => {
const { manager, requests, panel } = fixture();
manager.currentMetadata = { positivePrompt: 'old prompt' };
const pending = manager.loadImageMetadata('new.png', panel);
assert.equal(manager.currentMetadata, null);
requests.get('new.png').resolve(null);
await pending;
assert.equal(manager.currentMetadata, null);
});
test('a stale error cannot replace newer metadata', async () => {
const { manager, requests, panel } = fixture();
const first = manager.loadImageMetadata('old.png', panel);
const second = manager.loadImageMetadata('new.png', panel);
requests.get('new.png').resolve({ positivePrompt: 'new prompt' });
await second;
requests.get('old.png').reject(new Error('old request failed'));
await first;
assert.equal(panel.innerHTML, 'new prompt');
});
for (const close of ['destroy viewer', 'remove modal']) {
test(`closing via ${close} prevents pending metadata from restoring action data`, async () => {
const { manager, requests, panel } = fixture();
const pending = manager.loadImageMetadata('old.png', panel);
if (close === 'destroy viewer') manager.destroyViewer();
else panel.isConnected = false;
requests.get('old.png').resolve({ positivePrompt: 'closed prompt' });
await pending;
assert.equal(manager.currentMetadata, null);
assert.notEqual(panel.innerHTML, 'closed prompt');
});
}
-209
View File
@@ -1,209 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const { escapeHtml } = require('../../web/js/html-escape.js');
function fixture(count = 2000) {
const elements = new Map();
function element() {
return {
dataset: {}, children: [], listeners: {}, classList: { add() {}, remove() {} },
set innerHTML(html) { this.html = html; this.children = [{ html }]; },
get innerHTML() { return this.html || ''; },
insertAdjacentHTML(position, html) { this.children.push({ html }); },
addEventListener(type, handler) { (this.listeners[type] ||= []).push(handler); },
querySelectorAll() { return []; },
remove() {},
};
}
const document = {
addEventListener() {},
getElementById(id) { if (!elements.has(id)) elements.set(id, element()); return elements.get(id); },
createElement: element,
};
const instances = [];
const timers = new Map();
let timerId = 0;
class Viewer {
constructor(holder, options) {
this.element = holder; this.options = { fullscreen: true, ...options };
this.index = options.initialViewIndex; this.isShown = true;
this.length = (holder.innerHTML.match(/<img /g) || []).length;
instances.push(this);
}
requestFullscreen() { this.fullscreenRequested = true; }
exitFullscreen() { this.fullscreenExited = true; }
show() { this.shown = true; }
view(index) { this.index = index; }
clearEnforceFocus() { this.focusCleared = true; }
destroy() { this.destroyed = true; }
}
const context = vm.createContext({ document, window: {}, Viewer, escapeHtml,
console, setTimeout(callback) { timers.set(++timerId, callback); return timerId; },
clearTimeout(id) { timers.delete(id); },
ApiClient: { resolveUrl: value => value, STALE: Symbol() },
ListState: { nextPageState: (state, next) => ({ ...state, ...next }) },
});
const source = fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8');
const Manager = vm.runInContext(source + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { images: Array.from({ length: count }, (_, i) => ({
filename: `${i}.png`, url: `/original/${i}.png`, thumbnail_url: `/thumb/${i}.jpg`,
relative_path: `${i}.png`, size: 100, modified_time: 1,
})), viewMode: 'grid', viewer: null, currentPage: 1, limit: 100, total: count,
getSettings: () => ({ showImageInfo: true }), });
return { manager, document, instances, timers };
}
for (const mode of ['grid', 'list']) {
test(`${mode} append retains existing cards and adds only the new page`, () => {
const { manager, document, timers } = fixture(100);
manager.viewMode = mode;
manager.renderGallery();
const container = document.getElementById(mode === 'grid' ? 'galleryGrid' : 'galleryList');
assert.equal(timers.size, 0);
const first = container.children[0];
manager.images.push({ ...manager.images[0], filename: 'new.png' });
manager.renderGallery({ from: 100 });
assert.equal(container.children[0], first);
assert.equal(container.children.length, 2);
assert.match(container.children[1].html, /new.png/);
assert.doesNotMatch(container.children[1].html, /alt="0.png"/);
assert.match(container.children[1].html, /data-image-index="100"/);
});
}
test('loadImages passes the previous length for append, and zero for replacement', async () => {
const { manager } = fixture(200);
const offsets = [];
Object.assign(manager, { imagesRequest: async () => ({ total: 500, images: [manager.images[0]] }),
renderGallery: options => offsets.push(options.from), updateStats() {},
updatePagination() {}, maybeLoadMore() {}, showLoading() {}, });
await manager.loadImages(3, { append: true });
await manager.loadImages(1);
assert.deepEqual(offsets, [200, 0]);
assert.equal(manager.images.length, 1);
});
test('viewer opening is bounded and selects the clicked original', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const viewer = instances[0];
assert.ok(viewer.element.innerHTML.match(/<img /g).length <= 100);
assert.match(viewer.element.innerHTML, /data-original="\/original\/1500.png"/);
const urls = [...viewer.element.innerHTML.matchAll(/data-original="([^"]+)"/g)].map(m => m[1]);
assert.equal(urls[viewer.options.initialViewIndex], '/original/1500.png');
assert.equal(viewer.shown, true);
});
test('previous/next cross window edges and wrap only at gallery edges', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const first = manager.viewer;
first.index = 99;
const lastUrl = [...first.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)].at(-1);
first.next(true);
const next = manager.viewer;
const urls = [...next.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)];
assert.equal(Number(urls[next.index][1]), Number(lastUrl[1]) + 1);
manager.openViewer(0);
manager.viewer.prev(true);
const wrapped = manager.viewer;
const wrappedUrls = [...wrapped.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)];
assert.equal(Number(wrappedUrls[wrapped.index][1]), 1999);
assert.ok(instances.length >= 3);
});
test('delegated card clicks bind once, open appended indices, and preserve video dispatch', () => {
const { manager, document } = fixture();
const opened = [];
manager.openViewer = index => opened.push(index);
manager.showVideoModal = (...args) => opened.push(args);
manager.addFallbackClickHandlers();
manager.addFallbackClickHandlers();
const grid = document.getElementById('galleryGrid');
assert.equal(grid.listeners.click.length, 1);
const item = { dataset: { imageIndex: '1500' }, querySelector: () => ({ dataset: {
original: '/original/1500.png', caption: 'caption', isVideo: 'false',
} }) };
const click = () => grid.listeners.click[0]({ target: { closest: () => item }, preventDefault() {}, stopPropagation() {} });
click();
item.querySelector = () => ({ dataset: { original: '/video.mp4', caption: 'video', isVideo: 'true' } });
click();
assert.deepEqual(opened, [1500, ['/video.mp4', 'video', 1500]]);
});
test('navigation inside the window reuses the viewer and honors non-looping edges', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
viewer.next(true);
assert.equal(manager.viewer, viewer);
assert.equal(viewer.index, 51);
viewer.prev(true);
assert.equal(viewer.index, 50);
manager.openViewer(0);
const edge = manager.viewer;
edge.prev(false);
assert.equal(manager.viewer, edge);
assert.equal(edge.index, 0);
assert.equal(instances.length, 2);
});
test('append leaves an open viewer intact; a full render destroys it', () => {
const { manager } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
manager.renderGallery({ from: 1900 });
assert.equal(manager.viewer, viewer);
manager.renderGallery();
assert.equal(viewer.destroyed, true);
assert.equal(manager.viewer, null);
});
test('each viewed image updates sidebar metadata without waiting for DOM mutations', () => {
const { manager, document } = fixture();
const urls = [];
document.querySelector = () => ({});
const sidebar = document.getElementById('metadata-sidebar');
sidebar.querySelector = () => ({});
manager.loadImageMetadata = url => urls.push(url);
manager.openViewer(1500);
manager.viewer.options.viewed({ detail: { originalImage: { dataset: { original: '/original/1500.png' } } } });
manager.viewer.options.viewed({ detail: { originalImage: { dataset: { original: '/original/1501.png' } } } });
assert.deepEqual(urls, ['/original/1500.png', '/original/1501.png']);
});
test('slideshow advances across windows without preloading every original and stops on hide', () => {
const { manager, timers } = fixture();
manager.openViewer(1500);
let prevented = false;
manager.viewer.options.play({ preventDefault() { prevented = true; } });
assert.equal(prevented, true);
assert.equal(manager.viewer.fullscreenRequested, true);
assert.equal(timers.size, 1);
manager.viewer.index = 99;
const tick = timers.values().next().value;
timers.clear();
tick();
const viewer = manager.viewer;
const urls = [...viewer.element.innerHTML.matchAll(/data-original="([^"]+)"/g)];
assert.equal(urls[viewer.index][1], '/original/1550.png');
assert.equal(timers.size, 1);
viewer.options.hide();
assert.equal(viewer.fullscreenExited, true);
assert.equal(timers.size, 0);
});
test('destroying a viewer removes its focus trap and slideshow timer', () => {
const { manager, timers } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
viewer.options.play({ preventDefault() {} });
manager.destroyViewer();
assert.equal(viewer.focusCleared, true);
assert.equal(viewer.destroyed, true);
assert.equal(timers.size, 0);
});
-103
View File
@@ -1,103 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ImageHelpers = require('../../web/js/image-helpers.js');
function deferred() {
let resolve;
const promise = new Promise(yes => { resolve = yes; });
return { promise, resolve };
}
function fixture() {
const elements = new Map();
const requests = [];
const document = { addEventListener() {}, getElementById(id) {
if (!elements.has(id)) elements.set(id, {});
return elements.get(id);
} };
const context = vm.createContext({ document, window: {}, ImageHelpers,
escapeHtml: value => value, console: { error() {} },
ApiClient: { resolveUrl: value => value, fetchUrl: (url, options) => {
const request = deferred();
requests.push({ url, body: JSON.parse(options.body), ...request });
return request.promise;
} },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
const notifications = [];
Object.assign(manager, { autoTagState: { reviewImages: [
{ id: 'digest', path: 'same.png', root_index: 1, url: '/same.png' },
{ id: 'other', path: 'next.png', root_index: 0, url: '/next.png' },
], reviewIndex: 0, currentTags: [], modelType: 'gguf' },
renderReviewTags() {}, showNotification: (...args) => notifications.push(args), hideModal() {}, loadImages() {},
});
const reply = (index, data) => requests[index].resolve({ json: async () => data });
return { manager, requests, reply, notifications };
}
const SHA = 'a'.repeat(64);
test('gallery review retains root identity and applies the tags to the image by its sha256 (#379)', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
assert.equal(requests[0].body.root_index, 1);
assert.equal(requests[0].body.existing, 'merge');
reply(0, { success: true, prompt_id: 42, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
manager.loadNextReviewImage = () => {};
const apply = manager.applyReviewTags();
assert.equal(requests[1].url, '/prompt_manager/autotag/apply');
assert.deepEqual(requests[1].body, ImageHelpers.autotagApplyBody(
{ id: 'digest', path: 'same.png', root_index: 1 }, SHA, ['smile']));
assert.equal('prompt_id' in requests[1].body, false);
reply(1, { success: true });
await apply;
});
test('an unlinked image applies to the image like a linked one', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: null, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
manager.loadNextReviewImage = () => {};
const apply = manager.applyReviewTags();
assert.equal(requests[1].body.sha256, SHA);
assert.deepEqual(requests[1].body.tags, ['smile']);
reply(1, { success: true });
await apply;
});
test('an answer without a captured sha256 never sends an apply', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: 42, tags: ['smile'] });
await load;
manager.loadNextReviewImage = () => {};
await manager.applyReviewTags();
assert.equal(requests.filter(r => r.url === '/prompt_manager/autotag/apply').length, 0);
});
test('a failed apply keeps the current image available for retry', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: 42, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
const apply = manager.applyReviewTags();
reply(1, { success: false, error: 'Try again' });
await apply;
assert.equal(manager.autoTagState.reviewIndex, 0);
assert.equal(requests.length, 2);
});
test('late generation responses cannot restore tags from a skipped or closed image', async () => {
const { manager, reply } = fixture();
const first = manager.loadNextReviewImage();
manager.autoTagState.reviewIndex = 1;
const second = manager.loadNextReviewImage();
reply(1, { success: true, prompt_id: 2, tags: ['current'] });
await second;
reply(0, { success: true, prompt_id: 1, tags: ['stale'] });
await first;
assert.deepEqual(Array.from(manager.autoTagState.currentTags), ['current']);
const third = manager.loadNextReviewImage();
manager.cancelReview();
reply(2, { success: true, prompt_id: 2, tags: ['closed'] });
await third;
assert.equal(manager.autoTagState.currentTags.length, 0);
});
-30
View File
@@ -1,30 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const ImageHelpers = require('../../web/js/image-helpers.js');
test('gallery metadata requests retain root identity without including cache parameters in filenames', async () => {
const requests = [];
const context = vm.createContext({ document: { addEventListener() {} }, window: {}, console,
ImageHelpers, ApiClient: { fetchUrl: async url => {
requests.push(url);
return { ok: true, json: async () => ({ success: true, prompt: { text: url } }) };
} },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
manager.extractImageMetadata = async () => null;
manager.displayMetadata = (metadata, panel) => { panel.prompt = metadata.positivePrompt; };
for (const root of [0, 1]) {
const panel = {};
const expected = `/prompt_manager/images/prompt/sub%2Fsame.png?root=${root}`;
await manager.loadImageMetadata(`/prompt_manager/images/serve/sub/same.png?v=123&root=${root}`, panel);
assert.equal(panel.prompt, expected);
}
assert.deepEqual(requests, [
'/prompt_manager/images/prompt/sub%2Fsame.png?root=0',
'/prompt_manager/images/prompt/sub%2Fsame.png?root=1',
]);
});
-101
View File
@@ -87,104 +87,3 @@ test("the viewer open mode defaults to centered and accepts only its two values"
assert.equal(normalizeGallerySettings({ viewerOpenMode: "fullscreen" }).viewerOpenMode, "fullscreen");
for (const value of ["full", true, 1, null]) assert.equal(normalizeGallerySettings({ viewerOpenMode: value }).viewerOpenMode, "centered");
});
// #330 S13: the legacy gallery's Page options edit only the page-only keys (PAGE_OPTION_KEYS); System › Appearance owns the rest, so a Save
// or a Reset from the legacy page keeps every other stored key.
function legacyGallery(stored, controls, extra = {}) {
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const settings = require("../../web/js/gallery-settings.js");
const storage = new Map([["gallerySettings", JSON.stringify(stored)]]);
const context = vm.createContext({
document: { addEventListener() {}, getElementById: id => controls[id] },
window: {}, console: { debug() {}, warn() {}, error() {} }, GallerySettings: settings,
localStorage: { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value),
removeItem: key => storage.delete(key) },
...extra,
});
const file = path.join(__dirname, "../../web/js/gallery.js");
const Manager = vm.runInContext(`${fs.readFileSync(file, "utf8")}\nGalleryManager;`, context, { filename: file });
const manager = Object.create(Manager.prototype);
const calls = [];
Object.assign(manager, { showNotification: (message, type) => calls.push([type, message]), hideSettings() {},
applySettings: applied => calls.push(["apply", applied.lazyLoading]) });
return { manager, storage, calls, saved: () => JSON.parse(storage.get("gallerySettings")) };
}
const PAGE_OPTION_CONTROLS = () => ({
checkThumbnailsAtStartup: { checked: false }, lazyLoadingToggle: { checked: false },
defaultLimitSelect: { value: "200" },
gridColumnsSelect: { value: "6" }, infiniteScrollToggle: { checked: true }, debugModeToggle: { checked: true },
apiTimeoutInput: { value: "45" },
});
test("a legacy gallery Save keeps the workspace keys and every other stored key", () => {
const { manager, saved } = legacyGallery({ workspaceLayout: "masonry", workspaceDensity: "compact", someOtherTool: 1,
imageQuality: "high", showImageInfo: false, videoMute: false, thumbnailPromptDismissed: "sig", defaultViewMode: "list",
viewerOpenMode: "fullscreen" },
PAGE_OPTION_CONTROLS());
manager.saveSettings();
const result = saved();
assert.equal(result.workspaceLayout, "masonry");
assert.equal(result.workspaceDensity, "compact");
assert.equal(result.someOtherTool, 1);
assert.equal(result.imageQuality, "high");
assert.equal(result.showImageInfo, false);
assert.equal(result.videoMute, false);
assert.equal(result.thumbnailPromptDismissed, "sig");
assert.equal(result.viewerOpenMode, "fullscreen");
// Page options no longer edit the default view (S13 G5), so a stored one stays.
assert.equal(result.defaultViewMode, "list");
// The page-only keys come from the dialog.
assert.equal(result.lazyLoading, false);
assert.equal(result.debugMode, true);
assert.equal(result.checkThumbnailsAtStartup, false);
assert.equal(result.defaultLimit, 200);
assert.equal(result.gridColumns, 6);
assert.equal(result.infiniteScroll, true);
assert.equal(result.apiTimeout, 45);
});
test("a legacy gallery Reset restores only the page options and keeps every other stored key", () => {
const controls = PAGE_OPTION_CONTROLS();
const { manager, saved, calls } = legacyGallery({ workspaceLayout: "masonry", imageQuality: "high", videoMute: false,
thumbnailPromptDismissed: "sig", thumbnailsGenerated: true, lazyLoading: false, debugMode: true, defaultLimit: 200,
gridColumns: 6, infiniteScroll: true, apiTimeout: 45, checkThumbnailsAtStartup: false, defaultViewMode: "list" }, controls,
{ confirm: message => (calls.push(["confirm", message]), true) });
manager.resetSettings();
const result = saved();
const { DEFAULT_SETTINGS } = require("../../web/js/gallery-settings.js");
for (const key of ["checkThumbnailsAtStartup", "lazyLoading", "defaultLimit", "gridColumns",
"infiniteScroll", "debugMode", "apiTimeout"]) {
assert.equal(result[key], DEFAULT_SETTINGS[key], key);
}
// The default view is not a page option (S13 G5): Reset keeps a stored one.
assert.equal(result.defaultViewMode, "list");
assert.equal(result.workspaceLayout, "masonry");
assert.equal(result.imageQuality, "high");
assert.equal(result.videoMute, false);
assert.equal(result.thumbnailPromptDismissed, "sig");
assert.equal(result.thumbnailsGenerated, true);
// The dialog shows the defaults again and the page applies them.
assert.equal(controls.lazyLoadingToggle.checked, DEFAULT_SETTINGS.lazyLoading);
assert.equal(controls.apiTimeoutInput.value, DEFAULT_SETTINGS.apiTimeout);
assert.deepEqual(calls, [["confirm", "Reset these page options to their defaults?"], ["apply", DEFAULT_SETTINGS.lazyLoading],
["success", "Page options reset to defaults"]]);
});
test("Page options no longer hold the default view; System › Appearance's Default layout is the one control", () => {
const { manager } = legacyGallery({}, {});
assert.deepEqual([...manager.constructor.PAGE_OPTION_KEYS], ["checkThumbnailsAtStartup", "lazyLoading", "defaultLimit",
"gridColumns", "infiniteScroll", "debugMode", "apiTimeout"]);
});
test("a viewer mute or loop click remembers only that key and never reads the Page options dialog", () => {
const { manager, saved, calls } = legacyGallery({ defaultLimit: 200, lazyLoading: false, videoMute: true }, {});
manager.storeSetting("videoMute", false);
const result = saved();
assert.equal(result.videoMute, false);
assert.equal(result.defaultLimit, 200);
assert.equal(result.lazyLoading, false);
assert.deepEqual(calls, []);
});
-235
View File
@@ -1,235 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture(status, settings = {}) {
const timers = [];
const prompts = [];
const requests = [];
const buttons = {};
const storage = new Map();
const document = {
addEventListener() {},
createElement: () => ({ addEventListener() {} }),
body: { appendChild() {}, removeChild() {} },
getElementById: id => buttons[id] ||= { addEventListener(type, handler) { this[type] = handler; } },
};
const context = vm.createContext({ document, window: {}, console: { debug() {}, warn() {} },
setTimeout: callback => timers.push(callback),
localStorage: { setItem: (key, value) => storage.set(key, value) },
ApiClient: { fetchUrl: async () => ({ json: async () => ({ success: true,
total: 10000, images: Array.from({ length: 50 }, () => ({ thumbnail_url: null })),
}) }) },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { getSettings: () => ({ checkThumbnailsAtStartup: true, ...settings }),
api: { get: async url => { requests.push(url); return status; } },
});
const originalPrompt = manager.showThumbnailGenerationPrompt.bind(manager);
manager.showThumbnailGenerationPrompt = (...args) => prompts.push(args);
async function check() {
await manager.checkThumbnailsAtStartup();
await timers.shift()();
}
return { manager, check, prompts, requests, settings, buttons, storage, originalPrompt };
}
test('startup uses exact collection counts instead of extrapolating the newest 50 images', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 50, ready: 9950, collection_id: 'a' });
await f.check();
assert.deepEqual(f.requests, ['/prompt_manager/images/thumbnails/status']);
assert.equal(f.prompts.length, 0);
});
test('startup prompt reports the actual number needing generation', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 1200, collection_id: 'a' });
await f.check();
assert.equal(f.prompts.length, 1);
assert.deepEqual(f.prompts[0].slice(0, 2), [10000, 1200]);
});
test('a complete collection never prompts again', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 0, collection_id: 'a' });
await f.check();
await f.check();
assert.equal(f.prompts.length, 0);
});
test('Not Now persists the collection state and suppresses the unchanged prompt', async () => {
const status = { success: true, total_images: 100, pending: 30, collection_id: 'a' };
const f = fixture(status);
await f.check();
f.originalPrompt(...f.prompts[0]);
f.buttons.thumbnailPromptNo.click();
Object.assign(f.settings, JSON.parse(f.storage.get('gallerySettings')));
f.prompts.length = 0;
await f.check();
assert.equal(f.prompts.length, 0);
status.pending = 40;
await f.check();
assert.equal(f.prompts.length, 1);
});
// WebKit fails a fetch a leaving page starts ("Fetch API cannot load … due to access control checks.") and logs it
// as a page error: the delayed startup check starts no read once the page has begun to leave (as admin.js, #290).
test('the startup check starts no read once the page is leaving', async () => {
const f = fixture({ success: true, total_images: 100, pending: 30, collection_id: 'a' });
f.manager.pageLifetime = new AbortController();
f.manager.pageLifetime.abort();
await f.check();
assert.equal(f.requests.length, 0);
assert.equal(f.prompts.length, 0);
});
test('the startup check passes the page lifetime to its read', async () => {
const f = fixture({ success: true, total_images: 100, pending: 30, collection_id: 'a' });
const signals = [];
f.manager.pageLifetime = new AbortController();
const get = f.manager.api.get;
f.manager.api.get = async (url, options) => { signals.push(options?.signal); return get(url); };
await f.check();
assert.deepEqual(signals, [f.manager.pageLifetime.signal]);
assert.equal(f.prompts.length, 1);
});
test('disabled checks do not request collection status', async () => {
const f = fixture({}, { checkThumbnailsAtStartup: false });
await f.check();
assert.equal(f.requests.length, 0);
assert.equal(f.prompts.length, 0);
});
test('saving gallery settings retains the remembered thumbnail dismissal', () => {
const f = fixture({}, { thumbnailPromptDismissed: 'remembered-state' });
f.manager.showNotification = () => {};
f.manager.hideSettings = () => {};
f.manager.applySettings = () => {};
f.manager.saveSettings();
assert.equal(JSON.parse(f.storage.get('gallerySettings')).thumbnailPromptDismissed, 'remembered-state');
});
// #249 System S5: the stream's work is now an Activity job that outlives the page's connection, so the gallery's
// Cancel asks the server to stop the job. Since #330 the startup dialog is the gallery's only thumbnail stream (System
// › Sources & scans generates the rest). The stream's first frame, `job {id, started}`, names the job; the gallery
// cancels by that id, only a job this stream started, and a Cancel before the id waits for it (review I1).
const JOB = 'b'.repeat(32);
function streamFixture({ postFails = false } = {}) {
const posts = [];
const warnings = [];
const gets = [];
const listeners = {};
const source = { closed: 0, readyState: 1, CLOSED: 2, url: null,
addEventListener(type, handler) { (listeners[type] ||= []).push(handler); },
close() { this.closed += 1; } };
const element = () => ({ classList: { add() {}, remove() {} }, style: {}, textContent: '', handlers: {},
addEventListener(type, handler) { this.handlers[type] = handler; },
removeEventListener(type, handler) { if (this.handlers[type] === handler) delete this.handlers[type]; },
click() { this.handlers.click?.(); } });
const elements = {};
const document = { addEventListener() {}, getElementById: id => elements[id] ||= element(),
createElement: () => element(), body: { appendChild() {}, removeChild() {} } };
const context = vm.createContext({ document, window: {},
console: { debug() {}, warn: (...args) => warnings.push(args), error() {} },
setTimeout() {}, localStorage: { setItem() {} },
SseStream: { connect: (url, options) => { source.url = url; source.options = options; return source; } } });
const file = path.join(__dirname, '../../web/js/gallery.js');
const Manager = vm.runInContext(fs.readFileSync(file, 'utf8') + '\nGalleryManager;', context, { filename: file });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { getSettings: () => ({}),
api: { get: async url => { gets.push(url); return { success: true, jobs: [] }; },
post: async (url, body) => {
posts.push([url, body]);
if (postFails) throw new Error('offline');
return { success: true };
} } });
const emit = (type, data) => (listeners[type] || []).forEach(handler => handler({ data: JSON.stringify(data) }));
// The dialog's Cancel runs the handler and from then on reads as cancelled, as the startup dialog does.
let cancelled = false;
const ui = { addStatusMessage() {}, progressText: element(), progressPercent: element(), progressBar: element(),
progressDetails: element(), progressETA: element(), isCancelled: () => cancelled,
onCancel: handler => { ui.cancel = () => { cancelled = true; handler(); }; } };
const result = manager.generateThumbnailsWithProgressInModal(ui);
const outcome = result.then(value => ({ value }), error => ({ error: error.message }));
const cancel = () => ui.cancel();
const settle = () => new Promise(resolve => setImmediate(resolve));
return { emit, source, posts, gets, warnings, outcome, cancel, settle };
}
const cancelUrl = id => `/prompt_manager/jobs/${id}/cancel`;
const CANCELLED = 'Thumbnail generation cancelled; previews already written are kept';
test('Cancel before the job id arrives cancels that job once it does', async () => {
const f = streamFixture();
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
assert.equal(f.source.closed, 0); // kept open until the stream names its job
assert.deepEqual(await f.outcome, { error: CANCELLED });
// The job frame is the stream's first (the dialog closes the stream on any later frame once cancelled).
f.emit('job', { id: JOB, started: true });
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
f.emit('job', { id: 'c'.repeat(32), started: true }); // a stray second frame changes nothing
await f.settle();
assert.equal(f.posts.length, 1);
assert.deepEqual(f.gets, []); // never looks a job up by kind
});
test('Cancel after the id cancels it at once, and a double Cancel posts once', async () => {
const f = streamFixture();
f.emit('job', { id: JOB, started: true });
f.cancel();
f.cancel();
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
assert.deepEqual(await f.outcome, { error: CANCELLED });
assert.deepEqual(f.gets, []);
});
test("Cancel leaves another tab's or System's job running and only stops following it", async () => {
const f = streamFixture();
f.emit('job', { id: JOB, started: false });
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
assert.deepEqual(f.gets, []);
assert.equal(f.source.closed, 1);
assert.match((await f.outcome).error, /keeps running/);
});
test('a Cancel the stream never names a job for posts nothing and closes when it ends', async () => {
const f = streamFixture();
f.cancel();
f.emit('error', { error: 'Scan for metadata already running' });
await f.settle();
assert.deepEqual(f.posts, []);
assert.equal(f.source.closed, 1);
});
test('a cancel post that fails is reported, not thrown', async () => {
const f = streamFixture({ postFails: true });
f.emit('job', { id: JOB, started: true });
f.cancel();
await f.settle();
assert.equal(f.posts.length, 1);
assert.equal(f.warnings.length, 1);
assert.deepEqual(await f.outcome, { error: CANCELLED });
});
test('the startup dialog cancels its own job by id too', async () => {
const f = streamFixture();
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
f.emit('job', { id: JOB, started: true });
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
assert.match((await f.outcome).error, /cancelled/);
});
-56
View File
@@ -1,56 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { escapeHtml, escapeAttr } = require("../../web/js/html-escape.js");
test("escapes the five HTML-significant characters", () => {
assert.equal(escapeHtml(`&<>"'`), "&amp;&lt;&gt;&quot;&#39;");
});
test("a double quote cannot break out of an attribute", () => {
const payload = `" onmouseover="alert(1)`;
const escaped = escapeHtml(payload);
assert.ok(!escaped.includes(`"`), escaped);
assert.equal(escaped, `&quot; onmouseover=&quot;alert(1)`);
assert.equal(`<a data-tag="${escaped}">`, `<a data-tag="&quot; onmouseover=&quot;alert(1)">`);
});
test("a single quote cannot break out of a single-quoted attribute", () => {
const escaped = escapeHtml(`' onclick='alert(1)`);
assert.ok(!escaped.includes(`'`), escaped);
assert.equal(escaped, `&#39; onclick=&#39;alert(1)`);
});
test("a script tag is neutralised in text context", () => {
assert.equal(escapeHtml("<script>x</script>"), "&lt;script&gt;x&lt;/script&gt;");
});
test("unicode and ordinary text pass through unchanged", () => {
assert.equal(escapeHtml("héllo wörld 日本語 🙂"), "héllo wörld 日本語 🙂");
assert.equal(escapeHtml("plain text, no specials"), "plain text, no specials");
});
test("already escaped text is escaped again, never double-decoded", () => {
assert.equal(escapeHtml("&amp;"), "&amp;amp;");
});
test("null and undefined become the empty string", () => {
assert.equal(escapeHtml(null), "");
assert.equal(escapeHtml(undefined), "");
});
test("numbers and booleans are coerced to strings", () => {
assert.equal(escapeHtml(42), "42");
assert.equal(escapeHtml(0), "0");
assert.equal(escapeHtml(1.5), "1.5");
assert.equal(escapeHtml(false), "false");
});
test("objects are coerced through String()", () => {
assert.equal(escapeHtml({ toString: () => "<b>" }), "&lt;b&gt;");
});
test("escapeAttr is the same function as escapeHtml", () => {
assert.equal(escapeAttr, escapeHtml);
assert.equal(escapeAttr(`a"b`), "a&quot;b");
});
-149
View File
@@ -1,149 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const {
formatImageCaption,
workflowDocumentHtml,
autotagSingleBody,
autotagApplyBody,
autotagCompleteMessage,
fallbackImageSource,
} = require("../../web/js/image-helpers.js");
const WD14 = { modelType: "wd14-vit", generalThreshold: 0.35, characterThreshold: 0.85, prompt: "ignored" };
const CAPTION = { modelType: "blip", generalThreshold: 0.35, characterThreshold: 0.85, prompt: "describe it" };
test("autotagSingleBody sends image_id for a database row", () => {
const body = autotagSingleBody({ id: 42, prompt_id: 7, image_path: "/out/a.png" }, WD14);
assert.equal(body.image_id, 42);
assert.equal("path" in body, false);
});
test("autotagSingleBody sends path for an output-folder entry whose id is a digest", () => {
const body = autotagSingleBody({ id: "3f2a9c1b0d4e5f67", path: "/out/sub/a.png", filename: "a.png" }, WD14);
assert.equal(body.path, "/out/sub/a.png");
assert.equal("image_id" in body, false);
});
test("autotagSingleBody prefers path when a numeric-looking string id has no prompt link", () => {
const body = autotagSingleBody({ id: "1234567890abcdef", path: "/out/b.png" }, WD14);
assert.deepEqual(Object.keys(body).filter((k) => k === "path" || k === "image_id"), ["path"]);
});
test("autotagSingleBody adds wd14 thresholds and no prompt", () => {
const body = autotagSingleBody({ id: 1 }, WD14);
assert.equal(body.model_type, "wd14-vit");
assert.equal(body.general_threshold, 0.35);
assert.equal(body.character_threshold, 0.85);
assert.equal("prompt" in body, false);
});
test("autotagSingleBody adds the prompt for caption models and no thresholds", () => {
const body = autotagSingleBody({ id: 1 }, CAPTION);
assert.equal(body.model_type, "blip");
assert.equal(body.prompt, "describe it");
assert.equal("general_threshold" in body, false);
});
test("autotagSingleBody does not mutate its inputs", () => {
const image = Object.freeze({ id: 1 });
const settings = Object.freeze({ ...WD14 });
assert.doesNotThrow(() => autotagSingleBody(image, settings));
});
const XSS = '"><img src=x onerror=1>';
const formatFileSize = (bytes) => `${bytes} B`;
test("formatImageCaption joins dimensions and size with the separator", () => {
const caption = formatImageCaption({ width: 640, height: 480, file_size: 2048 }, { formatFileSize });
assert.equal(caption, "640×480 | 2048 B");
});
test("formatImageCaption honours a custom separator and omits a missing size", () => {
assert.equal(formatImageCaption({ width: 1, height: 2 }, { formatFileSize, separator: " • " }), "1×2");
});
test("formatImageCaption falls back to Unknown size when a dimension is missing", () => {
assert.equal(formatImageCaption({ width: 640 }, { formatFileSize }), "Unknown size");
assert.equal(formatImageCaption({}, { formatFileSize }), "Unknown size");
assert.equal(formatImageCaption(null, { formatFileSize }), "Unknown size");
});
test("formatImageCaption escapes string dimensions so they cannot break out of an attribute", () => {
const caption = formatImageCaption({ width: XSS, height: 10 }, { formatFileSize });
assert.ok(!caption.includes("<"), caption);
assert.ok(!caption.includes('"'), caption);
assert.ok(caption.includes("&quot;&gt;&lt;img"), caption);
});
test("formatImageCaption ignores a non-numeric file_size instead of formatting it", () => {
const caption = formatImageCaption({ width: 1, height: 1, file_size: XSS }, { formatFileSize });
assert.equal(caption, "1×1");
});
test("formatImageCaption escapes whatever formatFileSize returns", () => {
const caption = formatImageCaption({ width: 1, height: 1, file_size: 5 }, { formatFileSize: () => "<b>" });
assert.equal(caption, "1×1 | &lt;b&gt;");
});
test("workflowDocumentHtml escapes the JSON so it cannot close the pre block", () => {
const html = workflowDocumentHtml({ note: "</pre><script>alert(1)</script>" });
assert.ok(html.includes("&lt;/pre&gt;&lt;script&gt;"), html);
assert.ok(!html.includes("</pre><script>"), html);
assert.ok(html.startsWith("<!DOCTYPE html>"));
assert.ok(html.includes("<title>ComfyUI Workflow Data</title>"));
});
test("workflowDocumentHtml pretty-prints the workflow with two-space indentation", () => {
const html = workflowDocumentHtml({ a: 1 });
assert.ok(html.includes('{\n &quot;a&quot;: 1\n}'), html);
});
test("fallbackImageSource offers the original once when a thumbnail fails", () => {
const dataset = { original: "/serve/a.png", thumbnail: "/serve/thumbnails/a_thumb.png?v=1" };
assert.equal(fallbackImageSource("/serve/thumbnails/a_thumb.png?v=1", dataset), "/serve/a.png");
});
test("fallbackImageSource gives up when the original itself failed or was already tried", () => {
assert.equal(fallbackImageSource("/serve/a.png", { original: "/serve/a.png" }), null);
assert.equal(fallbackImageSource("/serve/t.png", { original: "/serve/a.png", fellBack: "1" }), null);
assert.equal(fallbackImageSource("/serve/t.png", {}), null);
assert.equal(fallbackImageSource("/serve/t.png", undefined), null);
});
const { metadataLookupUrl } = require('../../web/js/image-helpers.js');
test('metadata lookup keeps root identity and strips thumbnail cache query parameters', () => {
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/sub/a.png?root=1&v=123'), '/prompt_manager/images/prompt/sub%2Fa.png?root=1');
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/a.png?root=0'), '/prompt_manager/images/prompt/a.png?root=0');
});
test('metadata lookup preserves encoded filename characters and works behind a proxy', () => {
assert.equal(metadataLookupUrl('https://example.test/ComfyBackendDirect/prompt_manager/images/serve/space%20%23%3F%2520%20caf%C3%A9.png?root=1'), '/prompt_manager/images/prompt/space%20%23%3F%2520%20caf%C3%A9.png?root=1');
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/a.png?v=123'), '/prompt_manager/images/prompt/a.png');
assert.equal(metadataLookupUrl('/elsewhere/a.png'), null);
});
test("autotagSingleBody asks to skip auto-tagged images only when told (#379)", () => {
assert.equal(autotagSingleBody({ id: 1 }, WD14).existing, "merge");
assert.equal(autotagSingleBody({ id: 1 }, { ...WD14, existing: "skip" }).existing, "skip");
assert.equal(autotagSingleBody({ id: 1 }, { ...WD14, existing: "odd" }).existing, "merge");
});
test("autotagApplyBody names the image, its bytes and the tags, never a prompt (#379)", () => {
const sha = "a".repeat(64);
assert.deepEqual(autotagApplyBody({ id: 4, prompt_id: 7 }, sha, ["bird"]), { image_id: 4, sha256: sha, tags: ["bird"] });
assert.deepEqual(autotagApplyBody({ id: "digest", path: "sub/a.png", root_index: 1 }, sha, []),
{ path: "sub/a.png", root_index: 1, sha256: sha, tags: [] });
assert.deepEqual(autotagApplyBody({ id: 2 }, undefined, null), { image_id: 2, sha256: "", tags: [] });
const tags = ["x"];
autotagApplyBody({ id: 1 }, sha, tags).tags.push("y");
assert.deepEqual(tags, ["x"]);
});
test("autotagCompleteMessage counts images (#379)", () => {
assert.equal(autotagCompleteMessage(2), "Auto tagging complete! Tagged 2 images.");
assert.equal(autotagCompleteMessage(1), "Auto tagging complete! Tagged 1 image.");
assert.equal(autotagCompleteMessage(0), "Auto tagging complete! Tagged 0 images.");
assert.equal(autotagCompleteMessage(undefined), "Auto tagging complete! Tagged 0 images.");
});
+95
View File
@@ -0,0 +1,95 @@
// Run with: node --test tests/js/
// #668 (D207): where an old `/prompt_manager/admin#…` bookmark lands in the workspace (web/js/legacy-links.js, loaded
// by web/admin-redirect.html). Every target must be one the workspace router understands.
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { adminTarget } = require("../../web/js/legacy-links.js");
const state = import("../../web/js/workspace/state.mjs");
test("the dashboard and unknown hashes open the Prompt library", () => {
for (const hash of ["", "#", "#/", "#/prompts", "#tags", "#/tagsx", "#/tagged/a", undefined, null, 7]) {
assert.equal(adminTarget(hash), "workspace#/library", String(hash));
}
});
test("the bare Tags route and an empty tag list open Tags & categories", () => {
for (const hash of ["#/tags", "#/tags/", "#/tags/,", "#/tags/%20", "#/tags/ , ,", "#/tags/?mode=or"]) {
assert.equal(adminTarget(hash), "workspace#/tags", hash);
}
});
test("selected tags open the Library filtered by them, matching all unless the old mode was or", () => {
assert.equal(adminTarget("#/tags/landscape"), "workspace#/library?tag=landscape");
assert.equal(adminTarget("#/tags/landscape,portrait"), "workspace#/library?tag=landscape&tag=portrait");
assert.equal(adminTarget("#/tags/landscape,portrait?mode=or"), "workspace#/library?tag=landscape&tag=portrait&tag_mode=any");
for (const mode of ["and", "OR", "", "any"]) {
assert.equal(adminTarget(`#/tags/a,b?mode=${mode}`), "workspace#/library?tag=a&tag=b", mode);
}
// The old page wrote ?mode=or only for two or more tags and ignored it for one.
assert.equal(adminTarget("#/tags/a?mode=or"), "workspace#/library?tag=a");
assert.equal(adminTarget("#/tags/a,a?mode=or"), "workspace#/library?tag=a");
});
test("tag names are decoded as the old page encoded them and encoded again for the workspace", () => {
// encodeURIComponent per tag, joined with commas (tags-page.js updateUrlHash).
assert.equal(adminTarget("#/tags/red%20fox,a%2Cb,%E2%98%85%26%3D%3F%23"),
`workspace#/library?${new URLSearchParams([["tag", "red fox"], ["tag", "a,b"], ["tag", "★&=?#"]])}`);
// Trimmed before and after decoding; repeats dropped.
assert.equal(adminTarget("#/tags/ a ,%20a,b"), "workspace#/library?tag=a&tag=b");
// A segment that cannot be decoded is used as written (the old page threw on it).
assert.equal(adminTarget("#/tags/100%,b"), "workspace#/library?tag=100%25&tag=b");
// Only the text between the first and the second `?` was the old query.
assert.equal(adminTarget("#/tags/a,b?x=1?mode=or"), "workspace#/library?tag=a&tag=b");
assert.equal(adminTarget("#/tags/a,b?x=1&mode=or"), "workspace#/library?tag=a&tag=b&tag_mode=any");
});
test("the old untagged entry opens the Library's untagged prompts, alone or mixed", () => {
assert.equal(adminTarget("#/tags/__untagged__"), "workspace#/library?tag_mode=untagged");
// The old page asked for untagged prompts whenever the list held the entry, ignoring the other tags.
assert.equal(adminTarget("#/tags/a,__untagged__?mode=or"), "workspace#/library?tag_mode=untagged");
});
test("every target is relative and resolves in the workspace router to the filter it names", async () => {
const { resolveRoute } = await state;
const cases = [
["", "library", undefined],
["#/tags", "tags", undefined],
["#/tags/red%20fox,a%2Cb?mode=or", "library", { tags: ["red fox", "a,b"], tagMode: "any" }],
["#/tags/a", "library", { tags: ["a"], tagMode: "all" }],
["#/tags/__untagged__", "library", { tags: [], tagMode: "untagged" }],
["#/tags/100%", "library", { tags: ["100%"], tagMode: "all" }],
];
for (const [hash, id, browse] of cases) {
const target = adminTarget(hash);
// Relative, so a reverse-proxy mount prefix in front of /prompt_manager/admin survives.
assert.match(target, /^workspace#\//, hash);
const route = resolveRoute(target.slice("workspace".length));
assert.deepEqual([route.id, route.browse, route.browseInvalid], [id, browse, undefined], hash);
}
});
test("the redirect page loads the module, replaces the address and always offers the Library link", () => {
const html = fs.readFileSync(path.join(__dirname, "../../web/admin-redirect.html"), "utf8");
const moduleTag = '<script src="js/legacy-links.js"></script>';
assert.ok(html.includes(moduleTag), "the page loads the mapping module");
// The link is plain markup, visible without scripts and when the script fails: the page has no <noscript> at all.
assert.ok(html.includes('<a href="workspace#/library">'));
assert.equal(html.toLowerCase().includes("<noscript"), false);
// The inline script follows the module tag; on a page where the module failed to load it still leaves for the Library.
const open = html.indexOf("<script>", html.indexOf(moduleTag));
const inline = html.slice(open + "<script>".length, html.indexOf("</script>", open));
assert.ok(open > 0 && inline.includes("location.replace("));
for (const [globals, expected] of [
[{}, "workspace#/library"],
[{ LegacyLinks: { adminTarget() { throw new Error("broken"); } } }, "workspace#/library"],
[{ LegacyLinks: { adminTarget: hash => `workspace#/seen${hash}` } }, "workspace#/seen#/tags/a"],
]) {
const replaced = [];
const window = { ...globals, location: { hash: "#/tags/a", replace: target => replaced.push(target) } };
vm.runInContext(inline, vm.createContext({ window }));
assert.deepEqual(replaced, [expected]);
}
});
@@ -1,6 +1,6 @@
// Run with: node --test tests/js/
// Characterization, not a specification: pins what the legacy viewers
// (web/metadata.html, web/js/gallery.js) show today on the synthetic inspection
// (the old metadata and gallery pages, removed in #668) showed on the synthetic inspection
// parity fixtures, so the #240 workspace work cannot change them by accident.
// Some answers are known to be wrong (f01b shows the preview-only detailer text
// as both roles; f16 shows the last of two conflicting prompt chunks; f19 shows the
@@ -18,8 +18,8 @@ const { extractGenerationParams } = require("../../web/js/comfy-metadata.js");
const FIXTURES = path.join(__dirname, "..", "fixtures", "inspection_parity");
const DETAILER = "Detailer pass: refine the face";
// Copy of the legacy pages' inline glue (NaN cleanup and field order): web/metadata.html
// extractComfyUIData (line 107) and web/js/gallery.js extractComfyUIData (line 1643).
// Copy of the legacy pages' inline glue (NaN cleanup and field order): extractComfyUIData of
// web/metadata.html (line 107) and web/js/gallery.js (line 1643), as of 3.7.2.
// The spec only promises extractGenerationParams is unchanged, so the glue is copied here.
function legacyComfyData(metadata) {
const parse = text => JSON.parse(text.replace(/:\s*NaN\b/g, ": null").replace(/\bNaN\b/g, "null"));
-100
View File
@@ -1,100 +0,0 @@
// The legacy admin and gallery pages show a server refusal's reason (#220, PR #289 review I1 and M8): a job that
// runs in the workspace refuses their record-changing requests, and a corrupt config.json refuses a settings save.
// Each page must name the reason, not report a lost connection, a bare HTTP status or a success.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function elements() {
const nodes = {};
return {
nodes,
getElementById: id => nodes[id] ||= { id, textContent: '', innerHTML: '', disabled: false, style: {},
value: '', checked: false, addEventListener() {}, querySelectorAll: () => [] },
};
}
function jsonResponse(status, body) {
return { ok: status >= 200 && status < 300, status, statusText: status === 409 ? 'Conflict' : 'OK',
json: async () => body };
}
function load(file, className, fetchUrl, extra = {}, dom = elements()) {
const timers = [];
const notifications = [];
const storage = new Map([['pm_cached', '1'], ['userData', 'keep'], ['pm_workspace_theme', 'light'],
['pm_update_notice_dismissed', '3.3.0']]);
const localStorage = {
get length() { return storage.size; },
key: index => [...storage.keys()][index] ?? null,
getItem: key => storage.get(key) ?? null,
setItem: (key, value) => storage.set(key, String(value)),
removeItem: key => storage.delete(key),
};
const context = vm.createContext({
document: { readyState: 'loading', addEventListener() {}, getElementById: dom.getElementById,
querySelectorAll: () => [] },
window: {}, console: { error() {}, warn() {}, debug() {} },
setTimeout: callback => timers.push(callback),
confirm: () => true,
localStorage,
TextDecoder, TextEncoder, JSON,
ApiClient: { fetchUrl },
...extra,
});
// gallery.html loads cache-ownership.js before gallery.js (#222).
vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/cache-ownership.js'), 'utf8'), context);
const source = fs.readFileSync(path.join(__dirname, `../../web/js/${file}`), 'utf8');
const Page = vm.runInContext(`${source}\n${className};`, context, { filename: path.join(__dirname, `../../web/js/${file}`) });
const page = Object.create(Page.prototype);
page.showNotification = (message, type) => notifications.push([type, message]);
page.showModal = id => notifications.push(['show', id]);
page.hideModal = id => notifications.push(['hide', id]);
return { page, dom, timers, notifications, storage };
}
test('admin settings save shows why config.json refused it', async () => {
const message = 'config.json cannot be read, so nothing was saved. Fix or remove the file, then save again.';
const { page, notifications } = load('admin.js', 'PromptAdmin',
async () => jsonResponse(409, { success: false, persisted: false, code: 'config-unreadable', error: message }));
page.settings = {};
page.setInfiniteScroll = () => assert.fail('nothing changes after a refusal');
await page.saveSettings();
assert.deepEqual(notifications, [['error', `Failed to save settings: ${message}`]]);
});
test('admin settings save keeps its plain message when the reply has no reason', async () => {
const { page, notifications } = load('admin.js', 'PromptAdmin', async () => ({ ok: false, status: 500,
json: async () => { throw new SyntaxError('not json'); } }));
page.settings = {};
await page.saveSettings();
assert.deepEqual(notifications, [['error', 'Failed to save settings']]);
});
// #330 S13-9: the admin page's reduced Page options save sends only the list's scroll default, so a stale legacy form
// can no longer overwrite scan folders or other settings edited in System.
test('admin Page options save posts only infinite_scroll', async () => {
const sent = [];
const { page, dom, notifications } = load('admin.js', 'PromptAdmin', async (url, init) => {
sent.push([url, init.method, JSON.parse(init.body)]);
return jsonResponse(200, { success: true, restart_required: true });
});
page.settings = { infiniteScroll: false };
const scrolled = [];
page.setInfiniteScroll = (on, options) => scrolled.push([on, { ...options }]);
dom.getElementById('infiniteScrollDefault').checked = true;
await page.saveSettings();
assert.deepEqual(sent, [['/prompt_manager/settings', 'POST', { infinite_scroll: true }]]);
assert.deepEqual(scrolled, [[true, { session: false }]]);
assert.equal(page.settings.infiniteScroll, true);
assert.deepEqual(notifications, [['success', 'Page options saved'], ['hide', 'settingsModal']]);
});
-65
View File
@@ -1,65 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { nextPageState, shouldSaveEdit, hasMorePages, shouldLoadMore } = require("../../web/js/list-state.js");
test("hasMorePages follows pagination.has_more only while pages keep arriving", () => {
assert.equal(hasMorePages({ pagination: { has_more: true } }, 5000), true);
assert.equal(hasMorePages({ pagination: { has_more: false } }, 5000), false);
assert.equal(hasMorePages({ pagination: { has_more: true } }, 0), false, "an empty page ends the loop");
assert.equal(hasMorePages({}, 10), false, "no pagination block means a single page");
assert.equal(hasMorePages(null, 10), false);
});
const current = { page: 2, limit: 50, total: 120, totalPages: 3 };
test("nextPageState moves to the requested page once the fetch succeeded", () => {
assert.deepEqual(nextPageState(current, { page: 3, total: 120 }), { page: 3, limit: 50, total: 120, totalPages: 3 });
});
test("nextPageState clamps a page beyond the end when the total shrank", () => {
assert.deepEqual(nextPageState(current, { page: 3, total: 60 }), { page: 2, limit: 50, total: 60, totalPages: 2 });
});
test("nextPageState never goes below page 1 and has at least one page", () => {
assert.deepEqual(nextPageState(current, { page: 0, total: 0 }), { page: 1, limit: 50, total: 0, totalPages: 1 });
assert.equal(nextPageState(current, { page: -5, total: 10 }).page, 1);
});
test("nextPageState keeps the current page and total when the response omits them", () => {
assert.deepEqual(nextPageState(current, {}), current);
assert.deepEqual(nextPageState(current, { total: "many", page: "x" }), current);
});
test("nextPageState accepts a new limit and recomputes totalPages", () => {
assert.deepEqual(nextPageState(current, { page: 1, limit: 25, total: 120 }), { page: 1, limit: 25, total: 120, totalPages: 5 });
assert.equal(nextPageState(current, { limit: 0 }).limit, 50, "a zero limit is ignored");
});
test("nextPageState does not mutate its input", () => {
const before = { ...current };
nextPageState(current, { page: 1, total: 5 });
assert.deepEqual(current, before);
});
test("shouldSaveEdit is true only for a non-empty text that changed", () => {
assert.equal(shouldSaveEdit("old", "new"), true);
assert.equal(shouldSaveEdit("same", "same"), false);
assert.equal(shouldSaveEdit("same", " same \n"), false, "whitespace-only changes are not saved");
assert.equal(shouldSaveEdit("old", " "), false, "an emptied prompt is not saved");
assert.equal(shouldSaveEdit("old", null), false);
});
test("shouldLoadMore asks for the next page only near the bottom with pages left", () => {
const base = {
infiniteScroll: true, loading: false, page: 1, limit: 100, total: 1000,
scrollTop: 0, clientHeight: 800, scrollHeight: 4000, threshold: 600,
};
assert.equal(shouldLoadMore(base), false, "far from the bottom");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700 }), true, "within the threshold");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, loading: true }), false, "a load is in flight");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, infiniteScroll: false }), false, "setting off");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, page: 10 }), false, "last page reached");
assert.equal(shouldLoadMore({ ...base, scrollHeight: 700 }), true, "content shorter than the viewport");
assert.equal(shouldLoadMore({ ...base, total: 0, scrollHeight: 700 }), false, "nothing to load");
});
-61
View File
@@ -1,61 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const ImageHelpers = require('../../web/js/image-helpers.js');
const {extractGenerationParams} = require('../../web/js/comfy-metadata.js');
function graph(positive = 0, negative = 1) {
return {
1:{class_type:'PromptManagerPair',inputs:{text:'cat',negative_text:'blur',prepend_text:'trigger',append_text:'detail'}},
2:{class_type:'KSampler',inputs:{positive:['1',positive],negative:['1',negative],model:['3',0]}},
3:{class_type:'CheckpointLoaderSimple',inputs:{ckpt_name:'m.safetensors'}},
};
}
test('paired conditioning uses actual output roles and composes only positive', () => {
const metadata = extractGenerationParams({prompt:graph()});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
const swapped = extractGenerationParams({prompt:graph(1,0)});
assert.equal(swapped.positivePrompt,'blur');
assert.equal(swapped.negativePrompt,'trigger cat detail');
});
test('paired strings passed through encoders retain the connected output slot', () => {
const prompt=graph();
prompt[4]={class_type:'CLIPTextEncode',inputs:{text:['1',2]}};
prompt[5]={class_type:'CLIPTextEncode',inputs:{text:['1',3]}};
prompt[2].inputs.positive=['4',0];prompt[2].inputs.negative=['5',0];
const metadata=extractGenerationParams({prompt});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
});
test('recorded image pair overrides unrelated PNG fallback, including an empty negative', async () => {
for (const negative of ['blur','']) {
const context=vm.createContext({document:{addEventListener(){}},window:{},console,ImageHelpers,
ApiClient:{fetchUrl:async()=>({ok:true,json:async()=>({success:true,prompt:{text:'raw cat',pair:{negative_text:negative},pair_context:{positive_text:'trigger cat',negative_text:negative}}})})},
});
const Manager=vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/js/gallery.js'),'utf8')+'\nGalleryManager;',context);
const manager=Object.create(Manager.prototype);
manager.extractImageMetadata=async()=>({positivePrompt:'wrong',negativePrompt:'wrong'});
manager.displayMetadata=data=>{manager.last=data;};
await manager.loadImageMetadata('/prompt_manager/images/serve/example.png',{});
assert.equal(manager.last.positivePrompt,'trigger cat');
assert.equal(manager.last.negativePrompt,negative);
}
});
test('gallery labels graph-inferred text separately from recorded execution text', () => {
const context=vm.createContext({document:{addEventListener(){}},window:{},console,escapeHtml:value=>String(value)});
const Manager=vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/js/gallery.js'),'utf8')+'\nGalleryManager;',context);
const manager=Object.create(Manager.prototype);
manager.formatPromptText=value=>String(value||'');manager.setupMetadataActions=()=>{};
for (const [source,label] of [['graph-inferred','Recovered from workflow metadata'],['execution','Recorded during execution'],['embedded-parameters','Read from embedded parameters'],['mixed','Execution and workflow metadata']]) {
const panel={};
manager.displayMetadata({positivePrompt:'cat',negativePrompt:'blur',textSource:source},panel);
assert.ok(panel.innerHTML.includes(label),source);
}
});
+16
View File
@@ -289,3 +289,19 @@ test('a fallback after a re-render returns focus to the same-role copy button, n
const {fallbacks,copy,current}=await copyWithClipboard({writeText:async()=>{throw new Error('Denied');}},{detach:true});
assert.equal(fallbacks.length,1);assert.notEqual(current,copy);assert.equal(fallbacks[0].trigger,current);
});
// #658: an ambiguous file whose candidates share one role shows that role resolved; the other keeps the ambiguous
// line. The shared role has Copy and Send; the pair action needs both roles, so it is absent.
test('one shared role beside an ambiguous one has its own actions and no pair action',()=>{
const f=dom(),scope=createScope(),container=new f.Element('div'),sent=[];
try{
module.mountPromptBlocks(container,{parentScope:scope,sender:{open:roles=>sent.push(roles)},
prompts:{positive:{status:'ambiguous',text:null,source:null},negative:{status:'resolved',text:'shared negative',source:'graph-inferred'}}});
assert.deepEqual(statusLines(f,container),['Multiple possible prompts. Source could not be determined.']);
assert.equal(f.walk(container,node=>node.dataset.sendRole==='pair').length,0);
assert.equal(f.walk(container,node=>node.dataset.sendRole==='positive').length,0);
assert.equal(f.walk(container,node=>node.dataset.copyRole==='positive').length,0);
assert.equal(f.walk(container,node=>node.dataset.copyRole==='negative').length,1);
const send=f.walk(container,node=>node.dataset.sendRole==='negative')[0];container.click(send);
assert.deepEqual(sent,[{negative:'shared negative'}]);
}finally{scope.dispose();f.restore();}
});

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