Compare commits

..
45 changed files with 190 additions and 3017 deletions
+1 -2
View File
@@ -22,8 +22,7 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped for an inert push; a docs push runs only the two tests that read the docs
# (tools/ci/change_class.py, #639, #679).
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
- id: tests
name: tests
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
-258
View File
@@ -1,258 +0,0 @@
# 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 |
+46 -62
View File
@@ -10,22 +10,22 @@
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
Prompt Manager saves your prompts as you generate 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.
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.
## What's new
## What's new: rebuilt from the ground up
- **A new UI.** The workspace replaces the separate dashboard, gallery and metadata pages.
- **A new UI.** One app, 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.
- **Automated tests.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Tested end to end.** 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.
### Browse your whole output folder
### Your whole output folder, finally browsable
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.
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.
![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)
### Keyboard shortcuts
### Keep your hands on the keyboard
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)
### Select and act while you scroll
### Long libraries stay easy to work in
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.
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.
![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. Repeat runs and negative variants stay with their positive prompt and don't add near-duplicate entries to your list.
The Prompt library groups everything by positive prompt, so repeat runs and negative variants stay together instead of filling your list with near-duplicates.
![Prompt library cards showing each prompt's images, negative variants, runs and tags](assets/readme/library.webp)
### See negative variants on a timeline
### Watch your negatives branch 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 variant 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 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 negative variants side by side and lists the terms one adds, so you can see what changed between runs.
Compare negatives shows two variants side by side and lists the terms one adds, so you can see what actually 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 the suggestions
### Auto-tag your images, and approve what sticks
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 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 image dialog with WD14 suggestions and their confidence scores](assets/readme/autotag.webp)
### Manage tags and categories
### Keep your vocabulary tidy
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 & 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 and categories page](assets/readme/tags.webp)
### Group images your own way
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.
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.
![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 the file 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 it 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. Your browser reads the file. Prompt Manager doesn't upload it or add it to your library.
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.
![Inspecting a local file in the viewer](assets/readme/inspect.webp)
@@ -103,13 +103,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
### Deletes you can review
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.
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.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -123,17 +117,17 @@ System holds settings, image sources, auto-tag models, integrations, maintenance
### Works on your phone too
The workspace adapts to narrow screens, and the browser test suite includes touch.
The workspace adapts to narrow screens, and touch is part of the browser test suite.
![Images page and viewer at phone width](assets/readme/phone.webp)
## The nodes
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.
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.
### Prompt Manager (Classic)
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.
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.
![Prompt Manager Classic node in a workflow, Classic renderer](assets/readme/node-classic.webp)
@@ -143,19 +137,19 @@ The same workflow in Nodes 2.0:
### Prompt Manager (Focused)
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.
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.
![Prompt Manager Focused node in a workflow](assets/readme/node-focused.webp)
### Prompt Manager (Split)
This node has the same editor with the library always visible. A wide node shows them side by side. A narrow node stacks them.
The same editor with the library always visible. Wide nodes put them side by side; narrow nodes stack them.
![Prompt Manager Split node in a workflow](assets/readme/node-split.webp)
### Prompt Manager (+/-)
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.
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.
![Prompt Manager plus/minus node in a workflow](assets/readme/node-pair.webp)
@@ -165,23 +159,23 @@ The same workflow in Nodes 2.0:
### Prompt Manager 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.
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.
![Prompt Manager Text node feeding a CLIP Text Encode node](assets/readme/node-text.webp)
### Prompt Search List
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.
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.
![Prompt Search List node producing three images](assets/readme/node-search.webp)
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.
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.
## Install
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.
**Requirements:** ComfyUI and Python 3.12 or newer. `watchdog` and `Pillow` are the only dependencies of their own; the rest comes with ComfyUI.
Install from the Comfy Registry or ComfyUI-Manager by searching for Prompt Manager, or install by hand:
Install from the Comfy Registry or ComfyUI-Manager (search for Prompt Manager), or by hand:
```bash
cd ComfyUI/custom_nodes/
@@ -191,7 +185,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.** Prompt Manager installs none of these for you:
**Optional extras.** Nothing here is installed for you:
| To use | You need |
| --- | --- |
@@ -199,7 +193,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 the import on in System > Integrations. |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed; turn it on in System > Integrations |
Download or unload tagging models in System > Auto-tagging.
@@ -216,13 +210,13 @@ 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 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.
- **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.
## The old pages are gone
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.
The dashboard, tags page, gallery and metadata viewer have been removed. Everything they did is in the workspace, and their URLs and bookmarks still work: each one opens the matching workspace page.
| Old URL | Opens |
| --- | --- |
@@ -232,24 +226,18 @@ This version removes the dashboard, tags page, gallery and metadata viewer. The
| `/prompt_manager/gallery` | Images |
| `/prompt_manager/gallery.html` | Inspect a file |
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.
A tag bookmark opens the Prompt library with that filter, and the filter stays in the address: `/prompt_manager/workspace#/library?tag=cats&tag=dogs&tag_mode=any`. Reload, Back and Forward keep it, the address follows the tags you set in **Filters**, and you can bookmark or write such a link yourself (leave out `tag_mode` to match all the tags; `tag_mode=untagged` lists prompts without a tag). The sidebar's Prompt library link always shows the whole library. Search, category and sort aren't part of the address; **Save view** keeps those.
[README-legacy.md](README-legacy.md) still describes the old pages, for reference.
## Known limits
- **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.
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
- **Leave unresolved is permanent.** Needs review doesn't offer the file again unless its bytes change.
- **Leave unresolved is permanent.** A file you leave unresolved in Needs review isn't offered 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
@@ -261,12 +249,8 @@ A tag bookmark opens the Prompt library with that filter, and the filter stays i
| Browser | Over 60 Playwright spec files in Chromium, Firefox, WebKit and touch emulation |
| Real ComfyUI | A pinned CPU ComfyUI, started in Classic and Nodes 2.0, running real workflows |
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. 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).
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## License
The license is MIT. See [LICENSE](LICENSE).
MIT. See [LICENSE](LICENSE).
+3 -98
View File
@@ -855,7 +855,7 @@ and every other job runs for one class only:
| Class | Files | What runs |
| --- | --- | --- |
| `inert` | Only `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and `gate`: green in seconds. |
| `docs` | Only `README.md`, `README-legacy.md`, `CHANGELOG.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
| `docs` | Only `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
| `release` | `pyproject.toml` alone, and in it only the `version = "..."` line rewritten | The above and `package contents` (`tests/test_package_contents.py`). |
| `code` | Anything else | The whole gate. |
@@ -875,8 +875,7 @@ else by the next code change's gate. Run
editing those files.
The pre-push hook uses the same script: it skips the Python suite when the
pushed commits are `inert`, runs only those two test modules when they are
`docs` (#679), and runs the whole suite otherwise.
pushed commits are `inert` and runs it otherwise.
## Required merge checks
@@ -4463,38 +4462,6 @@ the per-section hand-off panel, was retired by S12 (#329): every section is nati
node runs saved, from their saved pairs. Only empty fields of never-edited prompts."
`system-maintenance-concept.spec.mjs` maps it (`mapPairRow`) as a copy of Optimize
database's row.
- **D210** (Maintenance and Integrations, #618, beyond the concept): Database adds "Tag
cleanup" after "Pair category and tags", with the line "Find tags that are whole comma
lists or are used nowhere. Review them, then remove only what you tick." and the button
"Find tags" with a danger mark (it ends in deleting tags, like Unused prompt
components). The button starts the tag search as an Activity job and opens it, as Find
duplicates does (`startFind`): kind `tag_cleanup`, pill "Finding tags", toasts "Tag
search started." and "Tag search finished · N tags found", one tile and outcome
"Found", log "Search log", no Cancel; its rows are tags (records, never opened). A
finished search that found tags adds **Review tags** (primary) after Download report.
It opens "Review tag cleanup" (`web/js/workspace/tag-cleanup-review.mjs`), drawn from
whatever rules the server returns: a `p.small[role=status]` "N tags selected", then per
rule with findings a checkbox "<title> (<total>)" that ticks or clears every listed tag
(indeterminate while only some are), a `p.small` with its explanation and what applying
does, a closed `details` "Show tags" whose checkbox rows "<name> · <detail>" are built
when it first opens (names wrap anywhere, CSS under D210), and, when the server's cap
of 2,000 cut the list, "Only the first 2,000 are listed. Clean these up, then search
again."; then "Nothing is deleted until you review and apply the cleanup. Prompts, pairs
and images are kept; only the tag is removed from them." and Cancel / "Review cleanup"
(disabled while nothing is ticked). Nothing is ticked when it opens. Review cleanup
opens the D100 plan "Tag cleanup" (Scope "Delete N tags (removed from P prompts, Q
pairs and R images)", Protected "N tags changed since the search", Backup "Always
created and verified first", Media "No files are removed"). A failed Tag cleanup job's
Review again goes to Maintenance (its plan needs a search). Integrations' LoRA import
review adds the row **Trigger words** after Found, only when a count is above 0: "N
become tags · M not made tags (lists or sentences)", or "N become tags" when M is 0.
`system-maintenance-concept.spec.mjs` maps the row (`mapTagRow`) as a copy of Unused
prompt components' row with the label "Find tags"; `system-integrations-concept.spec.mjs`
maps the Trigger words row. Tests: `D210: Tag cleanup finds comma and unused tags,
reviews only the ticked rule and deletes only it (#618)`
(workspace-system-maintenance.spec, hook `/__test__/system/tag-cleanup`),
`workspace-tag-cleanup-review.test.js`, `tests/test_tag_cleanup.py`,
`tests/test_api_tag_cleanup.py`.
- **D102** (Maintenance, S7, Q5, #222): Metadata cache clears only the browser entries
Prompt Manager owns as a cache (`web/js/cache-ownership.js`). The inventory of every
storage writer has none (see "Browser cache ownership" below), so the row's line adds
@@ -5158,54 +5125,6 @@ Tests: `tests/test_maintenance_pair_metadata.py`, `tests/test_api_maintenance_pa
`tests/browser/workspace-system-maintenance.spec.mjs` (hook `/__test__/system/pair-metadata`).
A Python change: ComfyUI needs a restart.
#### Tag cleanup (#618)
`tag_cleanup` ("Tag cleanup", D210) is in `MAINTENANCE_OPERATIONS` but is never
previewed alone (`preview_maintenance("tag_cleanup")` raises): it is planned from a tag
search's findings. `database/tag_cleanup.py` holds a registry of rules (`RULES`, each a
`TagRule` with `find`, `recheck` and `apply`); registry order is review order and
ownership: a tag is listed only under the first rule that finds it. Two rules ship:
- `comma`, "Tags containing a comma": a name holding `,` or `,` (U+FF0C), except a name
starting with `lora:` (the LoRA import's identity tag, made again by every import;
maintainer ruling 2026-11-22). Applying removes the tag from its prompts, pairs and
images and deletes it. Removed only: never split.
- `unused`, "Tags with no links": no `prompt_tags`, `prompt_pair_tags` or
`media_image_tags` row (image links count as none when the annotation tables are
missing). Deleted. A tag made by hand and not used yet is listed too (the schema does
not record who made a tag); nothing is pre-ticked.
`POST /prompt_manager/jobs/tag_cleanup` (body ignored) starts the find: kind
`tag_cleanup`, "Find tags to clean up", admission `read`, not cancellable, group `found`
(one row "<name> · <rule title>" per tag). It reads one `mode=ro` snapshot, writes
nothing, holds the result under the job id (the last 3 finds) and ends "Found N tags to
clean up" or "No tags need cleaning up"; a failure ends it "The tag search failed." A
second find while one runs, or beside an exclusive job, is 409 `busy`. `GET
/prompt_manager/maintenance/tag_cleanup/{job_id}` (`no-store`) answers every rule with
its findings `{tag_id, name, detail}` (at most 2,000 per rule; `total` exact; `detail`
"3 prompts · 1 pair", "no links", plus " · in N saved views" when saved views name it);
404 `not-found`, 409 `job-running`, 409 `no-groups`. The preview's options are exactly
`{job_id, select:[{rule, tag_ids}]}`: a known rule once each, 1 to 2,000 distinct tag ids,
each a held finding of that rule, else 400 `invalid-request`; the body has the large cap
(500 ids are not 413). Each selected finding is read again: one whose `(tag_id, name,
links)` changed since the search (`links` hashes its prompt ids, pair ids and image
`(byte_id, position)` rows, so a tag moved between owners is seen) is protected, "N tags
changed since the search". The plan's backup policy is always `required`: the apply
takes a safety backup first even when the setting is off (`ALWAYS_BACKED_UP`, with
`workflow_storage`). The apply job ("Tag cleanup", `maintenance`, `records`) runs in one
`BEGIN IMMEDIATE` transaction and does not compare the plan's fingerprint: each target's
rule rechecks it and keeps it with its reason (`already deleted`, `renamed since the
review`, `it is used now`, `its links changed since the review`, or `kept so the old tag
migration does not run again` when deleting it would empty `tags` while a prompt still
holds legacy JSON tags), and the rest still apply; an exception rolls everything back.
Changed rows read "Deleted tag “<name>” (<rule title>) · removed from 3 prompts",
Protected rows "Kept tag “<name>”: <reason>" (the review's protected findings first),
both complete in the report. Saved views, the auto-tag marks, the LoRA trigger cache and
history are never written. Tests: `tests/test_tag_cleanup.py`,
`tests/test_api_tag_cleanup.py`, `tests/test_vocabulary.py` (the shared `_delete_tag`),
`tests/browser/workspace-system-maintenance.spec.mjs`. A Python change: ComfyUI needs a
restart.
The legacy restore (`POST /prompt_manager/restore`) takes a backup of any size the disks
have room for, so a real library's safety backup restores: the upload, its staged copy
and the swap (the upload twice in the temporary folder, once more plus the current
@@ -5438,8 +5357,7 @@ legacy scan refuses it.
nothing (`test_preview_writes_nothing_and_makes_no_requests`: DB and `-wal` bytes, `-shm`
size, rows, no cache folder, the downloader never called) and answers the maintenance
`Plan` shape plus `lora_files`, `with_metadata`, `current_imports`, `blocked_by_pairs`,
`planned_downloads`, `trigger_tags`, `trigger_not_tags` and `network`; a blocked plan
has no token. `POST
`planned_downloads` and `network`; a blocked plan has no token. `POST
/prompt_manager/lora/import/apply {token}` starts the `lora_import` job (202): title "LoRA
reference import", admission `records`, cancellable only while it stages, the safety
backup the policy promises before the replace. Refusals: `plan-changed` (409, the files
@@ -5472,19 +5390,6 @@ refused while a restore runs; the review is a request lease ("LoRA import review
accepts the optional `expected_revision`. LoraManager detection also searches every
`custom_nodes` folder ComfyUI registers through `folder_paths` (#144), main folder first.
**Trained words as tags (#618).** A CivitAI `trainedWords` entry becomes a tag only when
it is one short clean phrase (`lora_utils.is_tag_phrase`, Option A): stripped, it passes
the tag rule (`validate_tags`: not empty, at most 50 characters, no control character),
holds no ASCII or fullwidth comma, no `<` or `>` (`<lora:x:0.8>`) and no prompt weight
(`(masterpiece:1.2)`); plain parentheses stay (`hatsune miku (vocaloid)`), and `ratio
(16:9)` is a recorded loss. `trigger_word_tags` returns the tags and how many entries were
not made tags; `build_record` adds `trigger_not_tags`, the preview sums `trigger_tags` and
`trigger_not_tags`, the review's Trigger words row shows them (D210) and the job logs "M
trained-words entries were not made tags (lists or sentences)". The trigger-word lookup
(`get_trigger_words_from_metadata`, the trigger cache) still sees every entry. Tests:
`TestTriggerWordTags`, `test_build_record_makes_tags_only_from_short_phrases`,
`test_preview_and_job_say_how_many_entries_were_not_made_tags`.
**Where LoraManager keeps its files (#355).** `py/lora_manager_layout.py` repeats
LoraManager's rules without importing it (`tests/test_lora_manager_layout.py`). The
settings file is `<LORA_MANAGER_SETTINGS_DIR>/settings.json`, else the plugin's own
-17
View File
@@ -19,10 +19,6 @@ 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
@@ -68,9 +64,6 @@ 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)
@@ -581,9 +574,6 @@ 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()
@@ -877,8 +867,6 @@ 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}")
@@ -897,11 +885,6 @@ 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)
+21 -5
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, bump_image_tag_bytes
from .vocabulary import VocabularyOperations
from .execution_history import ExecutionHistoryOperations
from .execution_contexts import ExecutionContextOperations
from .execution_outputs import ExecutionOutputOperations
@@ -1262,10 +1262,26 @@ class PromptDatabase(
"has_more": (offset + limit) < total,
}
# 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)
@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
@classmethod
def _move_tag_links(
-440
View File
@@ -1,440 +0,0 @@
"""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}
+2 -33
View File
@@ -295,38 +295,6 @@ 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.
@@ -437,7 +405,8 @@ 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)
_delete_tag(conn, tag_id)
self._bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
return {"library_epoch": epoch, "deleted": True, **counts}
def vocabulary_tag_impact(self, tag_id: int) -> dict | None:
-7
View File
@@ -23,7 +23,6 @@ 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
"""
@@ -75,7 +74,6 @@ 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
@@ -319,7 +317,6 @@ class PromptManagerAPI(
BackupRestoreRoutesMixin,
WorkflowStorageRoutesMixin,
DuplicateFilesMixin,
TagCleanupMixin,
LoggingRoutesMixin,
LogCleanupMixin,
DiagnosticsReportMixin,
@@ -397,9 +394,6 @@ 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).
@@ -697,7 +691,6 @@ 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)
-4
View File
@@ -124,10 +124,6 @@ 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"
+3 -18
View File
@@ -6,12 +6,9 @@ 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, 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
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
that saved pairs block, or whose layout is unusable, carries no token
(nothing can be applied).
@@ -107,13 +104,6 @@ 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:
@@ -325,8 +315,6 @@ 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": (
@@ -453,9 +441,6 @@ 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",
+11 -62
View File
@@ -5,9 +5,7 @@ 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; ``tag_cleanup``,
#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the
event loop and
``py/api/log_cleanup.py``, which has its own apply job) 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
@@ -31,17 +29,13 @@ 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, and always
for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy
``required``): SQLite's
policy (``maintenance.safety_backup``, default on) is on now: 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); ``tag_cleanup``
rechecks each tag instead and keeps, with its reason, each one that
changed, while the rest still apply;
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing);
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
@@ -93,13 +87,6 @@ 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.
@@ -113,12 +100,9 @@ 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; #618:
# the report and the backup are the only record of the deleted tag names).
COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP})
# Operations whose job keeps every changed row for its report (#550).
COMPLETE_RECORD = frozenset({"pair_metadata"})
_OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS)
MAINTENANCE_GROUPS = ("changed", "protected", "errors")
MAX_TOKEN_LENGTH = 128
@@ -323,8 +307,6 @@ 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}"
@@ -426,7 +408,7 @@ class MaintenanceRoutesMixin:
("operation", "options"),
cap=lambda body: (
DUPLICATE_PREVIEW_BODY_MAX
if body.get("operation") in LARGE_PREVIEWS
if body.get("operation") == DUPLICATE_FILES
else PREVIEW_BODY_MAX
),
)
@@ -438,8 +420,6 @@ 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:
@@ -490,12 +470,10 @@ class MaintenanceRoutesMixin:
)
policy = self._safety_backup_policy()
destination = "backup"
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.
# Always backed up first, whatever the policy (the way back);
# one kept pre-migration backup ever, pooled ones after it.
policy = "required"
kept = await self._run_in_executor(pre_migration_backups, db.model.db_path)
destination = "backup" if kept else PRE_MIGRATION_LABEL
try:
@@ -657,8 +635,8 @@ class MaintenanceRoutesMixin:
Decided once, when the apply starts (the disk check measured it), and
handed to the job.
"""
if plan.operation in ALWAYS_BACKED_UP:
return True # never without its backup (pre-migration, or #618's)
if plan.operation == WORKFLOW_STORAGE:
return True # never without its pre-migration backup
return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on"
async def _safety_backup_step(self, job, db, backup_on):
@@ -768,13 +746,6 @@ 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 [
@@ -804,8 +775,6 @@ 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 [
{
@@ -823,26 +792,6 @@ 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 = []
-245
View File
@@ -1,245 +0,0 @@
"""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),
},
)
+9 -27
View File
@@ -111,29 +111,23 @@ def preview(
"""The review's counts (blocking; reads only, requests nothing).
``{lora_files, with_metadata, skipped, with_local_media,
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``).
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``).
"""
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:
@@ -148,8 +142,6 @@ 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()),
@@ -157,22 +149,17 @@ 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.
Only the trained words that are one short clean phrase become tags
(#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest.
"""
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images."""
model_name = lora_utils.get_model_name_from_metadata(metadata)
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
words, not_tags = lora_utils.trigger_word_tags(metadata)
tags = ["lora-manager", f"lora:{model_name}", *words]
tags = ["lora-manager", f"lora:{model_name}"]
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
return {
"name": model_name,
"text": text,
"hash": generate_prompt_hash(text),
"tags": list(dict.fromkeys(tags)),
"images": images,
"trigger_not_tags": not_tags,
}
@@ -184,11 +171,7 @@ 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,
"trigger_not_tags": 0,
}
default_factory=lambda: {"downloaded": 0, "download_errors": 0}
)
@@ -236,7 +219,6 @@ 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,13 +22,11 @@ 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
@@ -389,44 +387,6 @@ 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.8.0"
version = "3.7.2"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
@@ -261,8 +261,7 @@ 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, Trigger words (#618, D210) and Network, the LoRAs it
* found (`details`), the hold
* the concept's four rows with the plan's values plus Found 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) {
@@ -274,7 +273,6 @@ 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']] },
@@ -335,10 +333,9 @@ 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([]);
// 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'; });
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'; });
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,29 +83,9 @@ 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 = mapTagRow(mapPairRow(reference));
const mapped = mapPairRow(reference);
return {
...mapped,
surfaces: mapped.surfaces.map(surface => ({ ...surface, rows: surface.rows.map(row => row.title !== 'Metadata cache' ? row : {
@@ -249,8 +229,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 and D210 rows, the section differs only on the D102 row.
expect(diffInventory(mapTagRow(mapPairRow(concept)), production).map(item => item.path).sort()).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([
'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);
@@ -343,7 +343,6 @@ 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>)'],
@@ -388,8 +387,7 @@ 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)).find(([term]) => term === 'Protected'))
.toEqual(['Protected', '1 imported prompt used by saved pairs']);
await expect.poll(async () => (await gridOf(page))[3]).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']);
@@ -397,18 +395,6 @@ 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) and D210 (#618): beyond the concept.
['Pair category and tags', 'Review plan', ''], ['Tag cleanup', 'Find tags', 'danger']]],
// D192 (#550): beyond the concept.
['Pair category and tags', 'Review plan', '']]],
['Images & cache', [['Missing-file links', 'Review plan', 'danger'], ['Duplicate image files', 'Find duplicates', ''],
['Thumbnail cache', 'Review options', ''], ['Metadata cache', 'Review plan', '']]],
]);
@@ -482,104 +482,6 @@ 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 = [];
@@ -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, junk}`` writes
``{loras, civitai, preview, previous, settings}`` 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,9 +18,7 @@ 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``); ``junk``
adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which
the import does not make tags (#618);
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
download until it is released (``{"hold": false}``), so a test sees the job
while it downloads;
@@ -147,9 +145,6 @@ def register_integrations_commands(app, routes, api, root: Path):
for number in range(count):
stem = f"style_{number + 1:02}"
civitai = {"trainedWords": [f"trigger{number + 1}"]}
if data.get("junk") is True:
# #618: a comma list and a model call, never made tags.
civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"]
if data.get("civitai") is True:
civitai["images"] = [
{
-22
View File
@@ -52,10 +52,6 @@ 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
@@ -353,24 +349,6 @@ 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():
-2
View File
@@ -63,7 +63,6 @@
"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}",
@@ -135,7 +134,6 @@
"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",
-20
View File
@@ -248,23 +248,3 @@ test('autotag gets Tagged / Unchanged / Skipped / Errors and Cancel; its legacy
assert.deepEqual([legacy.tiles, legacy.outcomes, [...legacy.openable]], [[], [], []]);
assert.equal(canCancel(held), false);
});
test('a tag search counts the tags found, opens no row and cannot be cancelled (#618)', async () => {
const { kindOf, viewOf, canCancel } = await source;
const { finishToast, startToast, pillParts, outcomeLine } = await store;
const find = job({ kind: 'tag_cleanup', title: 'Find tags to clean up', processed: 0, total: 0, progress: 0,
counters: { found: 0 }, cancellable: false });
const view = kindOf('tag_cleanup');
assert.equal(viewOf(find), view);
assert.deepEqual(view.tiles, [['found', 'Found', '']]);
assert.deepEqual(view.outcomes, [['found', 'Found']]);
assert.deepEqual([...view.openable], []);
assert.equal(view.log, 'Search log');
assert.equal(canCancel(find), false);
assert.equal(pillParts(find).text, 'Finding tags');
assert.equal(startToast(find), 'Tag search started.');
const found = { ...find, state: 'finished', counters: { found: 232 } };
assert.equal(outcomeLine(found), '232 tags found');
assert.equal(finishToast(found), 'Tag search finished · 232 tags found');
assert.equal(finishToast({ ...found, counters: { found: 1 } }), 'Tag search finished · 1 tag found');
});
@@ -137,23 +137,6 @@ test('the import review shows replacement, blocked items and network effects (D1
['Found', '1 metadata file · 1 LoRA · 0 with local images']);
});
test('the import review counts the trained words not made tags, after Found (#618)', async () => {
const { importGrid } = await integrations;
const rowAfterFound = plan => {
const rows = importGrid(plan);
const at = rows.findIndex(([term]) => term === 'Found');
return rows[at + 1];
};
assert.deepEqual(rowAfterFound({ trigger_tags: 1204, trigger_not_tags: 232 }),
['Trigger words', '1,204 become tags · 232 not made tags (lists or sentences)']);
assert.deepEqual(rowAfterFound({ trigger_tags: 3, trigger_not_tags: 0 }), ['Trigger words', '3 become tags']);
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 1 }),
['Trigger words', '0 become tags · 1 not made tags (lists or sentences)']);
// Neither number above 0 (or missing, as from an older server): no row.
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 0 })[0], 'Protected');
assert.deepEqual(rowAfterFound({ trigger_tags: '5', trigger_not_tags: -1 })[0], 'Protected');
});
test('the LoraManager row names what the import read, and an unusable layout closes the review (#355)', async () => {
const { layoutText, closeNote, LAYOUT_UNUSABLE, BLOCKED_NOTE, NOTHING_TO_IMPORT } = await integrations;
assert.equal(layoutText({ source: 'environment', mode: 'alongside', library: 'default', error: null }),
+1 -45
View File
@@ -24,42 +24,8 @@ test('the section lists the concept rows in its order, labels and danger marks',
// D192 (#550, beyond the concept): "Pair category and tags" follows "Unused prompt components" in Database.
const expected = concept.map(([title, ...rest]) => [title.replace('&amp;', '&'), ...rest]);
expected.splice(expected.findIndex(([title]) => title === 'Unused prompt components') + 1, 0, PAIR_ROW);
// D210 (#618, beyond the concept): "Tag cleanup" follows "Pair category and tags".
expected.splice(expected.findIndex(([title]) => title === PAIR_ROW[0]) + 1, 0, TAG_ROW);
assert.deepEqual(production, expected);
assert.equal(production.length, 10);
});
const TAG_ROW = Object.freeze(['Tag cleanup', 'Find tags that are whole comma lists or are used nowhere. Review them, then ' +
'remove only what you tick.', 'Find tags', true]);
test('D210: the Tag cleanup row starts the tag search with a danger mark (#618)', async () => {
const { MAINTENANCE_SURFACES, TAG_CLEANUP_KIND } = await maintenance;
const { OPERATION_TITLES } = await review;
const [, database] = MAINTENANCE_SURFACES[0];
const row = database.find(([title]) => title === TAG_ROW[0]);
assert.deepEqual(row, [TAG_ROW[0], TAG_ROW[1], TAG_ROW[2], TAG_CLEANUP_KIND, true]);
assert.equal(TAG_CLEANUP_KIND, 'tag_cleanup');
assert.equal(OPERATION_TITLES.tag_cleanup, 'Tag cleanup');
});
test('startFind opens the started search, toasts a busy start and says when it could not start', async () => {
const { startFind, TAG_FIND_FAILED, FIND_FAILED } = await maintenance;
const scope = { signal: { aborted: false } };
const toasts = [];
const routes = [];
const run = (result, kind = 'tag_cleanup', failed = TAG_FIND_FAILED) => startFind({
store: { start: async started => { assert.equal(started, kind); if (result instanceof Error) throw result; return result; } },
scope, kind, failed, notify: text => toasts.push(text), navigate: route => routes.push(route) });
await run({ job: { id: 'a'.repeat(32) } });
assert.deepEqual(routes, [`#/activity/${'a'.repeat(32)}`]);
await run({ busy: { id: 'b', title: 'Restore database', kind: 'restore' } });
assert.equal(toasts.length, 1);
await run(new Error('offline'));
assert.equal(toasts[1], 'The tag search could not start. Try again.');
await run(new Error('offline'), 'duplicates', FIND_FAILED);
assert.equal(toasts[2], 'The duplicate search could not start. Try again.');
assert.equal(routes.length, 1);
assert.equal(production.length, 9);
});
const PAIR_ROW = Object.freeze(['Pair category and tags', 'Fill an empty category or tags on prompts older Pair node runs ' +
@@ -207,16 +173,6 @@ test('a failed apply the library overtook offers Review again, back to its revie
assert.equal(reviewAgainOf(failed('maintenance', 'plan-changed', 'not_an_operation')), null);
assert.equal(reviewAgainOf({ ...failed('maintenance', 'plan-changed', 'optimize'), state: 'finished' }), null);
assert.equal(reviewAgainOf(failed('scan', 'plan-changed', 'optimize')), null);
// #618: a Tag cleanup cannot be previewed without its options: search again in Maintenance.
assert.deepEqual(reviewAgainOf(failed('maintenance', 'backup-failed', 'tag_cleanup')), { section: '#/system/maintenance' });
assert.deepEqual(reviewAgainOf(failed('maintenance', undefined, 'tag_cleanup')), { section: '#/system/maintenance' });
});
test('#618: a tag search lists records, not files', async () => {
const { listsRecords } = await jobView;
assert.equal(listsRecords({ kind: 'tag_cleanup', scope: {} }), true);
assert.equal(listsRecords({ kind: 'maintenance', scope: { operation: 'tag_cleanup' } }), true);
assert.equal(listsRecords({ kind: 'duplicates', scope: {} }), false);
});
test('a plan with nothing to do offers no Apply (S7 live test)', async () => {
@@ -1,82 +0,0 @@
// Tag cleanup review (#618, D210): the dialog draws whatever rules the findings route returns; its selection is one
// set of tag ids per rule, nothing ticked at first, and Review cleanup sends exactly the ticked ids per rule.
const test = require('node:test');
const assert = require('node:assert/strict');
const review = import('../../web/js/workspace/tag-cleanup-review.mjs');
const RULES = Object.freeze([
{ id: 'comma', title: 'Tags containing a comma', explanation: 'A whole list saved as one tag.',
action_label: 'Removes the tag and deletes it.', total: 3,
findings: [{ tag_id: 4, name: 'a, b', detail: '3 prompts · 1 pair' }, { tag_id: 9, name: 'c, d', detail: 'no links' },
{ tag_id: 2, name: 'x,y', detail: '1 prompt' }] },
{ id: 'unused', title: 'Tags with no links', explanation: 'No prompt, saved pair or image carries the tag.',
action_label: 'Deletes the tag.', total: 2501, findings: [{ tag_id: 7, name: 'ghost', detail: 'no links' }] },
{ id: 'later', title: 'A later rule', explanation: 'x', action_label: 'y', total: 0, findings: [] },
]);
test('nothing is ticked at first; only rules with findings are drawn', async () => {
const { createSelection, selectedCount, statusText, shownRules } = await review;
const selection = createSelection(RULES);
assert.equal(selectedCount(selection), 0);
assert.equal(statusText(0), '0 tags selected');
assert.equal(statusText(1), '1 tag selected');
assert.equal(statusText(1204), '1,204 tags selected');
assert.deepEqual(shownRules(RULES).map(rule => rule.id), ['comma', 'unused']);
assert.deepEqual(shownRules(null), []);
});
test('a rule tick ticks every listed tag of the rule and clears them; single ticks make it indeterminate', async () => {
const { createSelection, ruleState, toggleRule, toggleTag, selectedCount, isTicked } = await review;
const selection = createSelection(RULES);
assert.equal(ruleState(selection, 'comma'), 'none');
toggleRule(selection, 'comma', true);
assert.equal(ruleState(selection, 'comma'), 'all');
assert.equal(selectedCount(selection), 3);
assert.equal(ruleState(selection, 'unused'), 'none');
toggleTag(selection, 'comma', 9, false);
assert.equal(ruleState(selection, 'comma'), 'some');
assert.equal(isTicked(selection, 'comma', 9), false);
assert.equal(isTicked(selection, 'comma', 4), true);
toggleRule(selection, 'comma', false);
assert.equal(ruleState(selection, 'comma'), 'none');
assert.equal(selectedCount(selection), 0);
toggleTag(selection, 'unused', 7, true);
assert.equal(ruleState(selection, 'unused'), 'all');
// An id the rule did not list is never ticked.
toggleTag(selection, 'unused', 999, true);
assert.equal(selectedCount(selection), 1);
});
test('the select payload names each ticked rule once, in registry order, with its ticked ids', async () => {
const { createSelection, toggleRule, toggleTag, selectPayload } = await review;
const selection = createSelection(RULES);
assert.deepEqual(selectPayload(selection), []);
toggleTag(selection, 'unused', 7, true);
toggleTag(selection, 'comma', 2, true);
toggleTag(selection, 'comma', 4, true);
assert.deepEqual(selectPayload(selection), [{ rule: 'comma', tag_ids: [4, 2] }, { rule: 'unused', tag_ids: [7] }]);
toggleRule(selection, 'comma', false);
assert.deepEqual(selectPayload(selection), [{ rule: 'unused', tag_ids: [7] }]);
});
test('labels: the rule with its total, a finding with its detail, the cap note only when the cap cut the list', async () => {
const { ruleLabel, findingLabel, ruleText, capNote, CAP_NOTE } = await review;
assert.equal(ruleLabel(RULES[1]), 'Tags with no links (2,501)');
assert.equal(findingLabel(RULES[0].findings[0]), 'a, b · 3 prompts · 1 pair');
assert.equal(findingLabel({ name: 'ghost' }), 'ghost');
assert.equal(ruleText(RULES[1]), 'No prompt, saved pair or image carries the tag. Deletes the tag.');
assert.equal(capNote(RULES[0]), null);
assert.equal(capNote(RULES[1]), CAP_NOTE);
assert.equal(CAP_NOTE, 'Only the first 2,000 are listed. Clean these up, then search again.');
});
test('only a finished tag search that found tags offers Review tags', async () => {
const { hasTagFindings } = await review;
const job = (state, found, kind = 'tag_cleanup') => ({ kind, state, counters: { found } });
assert.equal(hasTagFindings(job('finished', 3)), true);
assert.equal(hasTagFindings(job('finished', 0)), false);
assert.equal(hasTagFindings(job('running', 3)), false);
assert.equal(hasTagFindings(job('finished', 3, 'duplicates')), false);
assert.equal(hasTagFindings({ kind: 'tag_cleanup', state: 'finished' }), false);
});
-369
View File
@@ -1,369 +0,0 @@
"""Tag cleanup routes (#618, ``py/api/tag_cleanup.py``).
``POST /prompt_manager/jobs/tag_cleanup`` finds tags to clean up as a ``read``
Activity job; ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers
every rule with the findings it holds; ``tag_cleanup`` previews the ticked
findings as a reviewed plan whose apply always takes a safety backup first,
whatever the setting, then deletes each target that is unchanged and keeps,
with its reason, each one that changed.
"""
import asyncio
import json
import os
try:
from tests.test_api_maintenance import APPLY, WAIT, ApplyTestCase
except ImportError: # discovered with tests/ as the top-level directory
from test_api_maintenance import APPLY, WAIT, ApplyTestCase
from py.config import PromptManagerConfig # noqa: E402
FIND = "/prompt_manager/jobs/tag_cleanup"
FINDINGS = "/prompt_manager/maintenance/tag_cleanup/"
class TagCleanupTestCase(ApplyTestCase):
def tags(self, *names):
with self.api.db.model.get_connection() as conn:
for name in names:
conn.execute("INSERT INTO tags(name) VALUES(?)", (name,))
def names(self):
with self.api.db.model.get_connection() as conn:
return sorted(r[0] for r in conn.execute("SELECT name FROM tags"))
def seed(self):
"""Two comma tags (one on a prompt), two unused, one clean in use."""
self.save("Owner", tags=["a, b", "clean"])
self.tags("x,y", "ghost", "spirit")
async def find(self):
response = await self.client.request("POST", FIND)
text = await response.text()
self.assertEqual(response.status, 202, text)
job = self.api._jobs.get(json.loads(text)["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
return job
async def findings(self, job_id, status=200):
response = await self.client.request("GET", f"{FINDINGS}{job_id}")
text = await response.text()
self.assertEqual(response.status, status, text)
self.assertNotIn(self.tmpdir, text)
if status == 200:
self.assertEqual(response.headers.get("Cache-Control"), "no-store")
return json.loads(text)
async def select(self, job, **by_rule):
"""The preview body selecting every finding of the named rules."""
body = await self.findings(job.id)
rules = {rule["id"]: rule for rule in body["rules"]}
return {
"job_id": job.id,
"select": [
{
"rule": rule,
"tag_ids": [f["tag_id"] for f in rules[rule]["findings"]],
}
for rule in by_rule
],
}
async def plan(self, options, status=200):
return await self.preview("tag_cleanup", status=status, options=options)
class TestFindJob(TagCleanupTestCase):
async def test_find_is_a_read_job_that_records_one_row_per_tag(self):
self.seed()
job = await self.find()
self.assertEqual(
(job.kind, job.title, job.admission, job.cancellable),
("tag_cleanup", "Find tags to clean up", "read", False),
)
self.assertEqual(job.state, "finished", job.log)
self.assertEqual(job.counters, {"found": 4})
self.assertEqual(
[row["detail"] for row in job.outcomes["found"]],
[
"a, b · Tags containing a comma",
"x,y · Tags containing a comma",
"ghost · Tags with no links",
"spirit · Tags with no links",
],
)
self.assertEqual(job.status_line, "Found 4 tags to clean up")
self.assertIn(job.id, self.api._tag_cleanup_finds)
async def test_a_clean_library_finds_nothing(self):
self.save("Owner", tags=["clean"])
job = await self.find()
self.assertEqual(job.counters, {"found": 0})
self.assertEqual(job.status_line, "No tags need cleaning up")
async def test_a_failed_search_says_so_and_holds_nothing(self):
from database import tag_cleanup
original = tag_cleanup.find_tag_cleanup
tag_cleanup.find_tag_cleanup = lambda path: 1 / 0
try:
job = await self.find()
finally:
tag_cleanup.find_tag_cleanup = original
self.assertEqual(job.state, "failed")
self.assertEqual(job.status_line, "The tag search failed.")
body = await self.findings(job.id, status=409)
self.assertEqual(body["code"], "no-groups")
async def test_a_second_find_while_one_runs_is_busy(self):
gate = asyncio.Event()
async def hold(job, db):
await gate.wait()
self.api._run_tag_cleanup_find = hold
response = await self.client.request("POST", FIND)
self.assertEqual(response.status, 202)
first = (await response.json())["job"]["id"]
response = await self.client.request("POST", FIND)
body = await response.json()
self.assertEqual((response.status, body["code"]), (409, "busy"))
reply = await self.findings(first, status=409)
self.assertEqual(reply["code"], "job-running")
gate.set()
await asyncio.wait_for(asyncio.shield(self.api._jobs.get(first).task), WAIT)
async def test_only_the_last_three_finds_are_held(self):
jobs = [await self.find() for _ in range(4)]
self.assertEqual(list(self.api._tag_cleanup_finds), [j.id for j in jobs[1:]])
body = await self.findings(jobs[0].id, status=404)
self.assertEqual(body["code"], "not-found")
class TestFindingsRoute(TagCleanupTestCase):
async def test_findings_list_every_rule_with_its_copy(self):
self.seed()
job = await self.find()
body = await self.findings(job.id)
self.assertTrue(body["success"])
self.assertEqual(body["job"], {"id": job.id, "state": "finished"})
comma, unused = body["rules"]
self.assertEqual(
{k: comma[k] for k in ("id", "title", "total")},
{"id": "comma", "title": "Tags containing a comma", "total": 2},
)
self.assertTrue(comma["explanation"] and comma["action_label"])
self.assertEqual(
[(f["name"], f["detail"]) for f in comma["findings"]],
[("a, b", "1 prompt"), ("x,y", "no links")],
)
self.assertEqual(set(comma["findings"][0]), {"tag_id", "name", "detail"})
self.assertEqual([f["name"] for f in unused["findings"]], ["ghost", "spirit"])
async def test_the_total_says_when_the_cap_cut_the_list(self):
from database import tag_cleanup
self.tags("a", "b", "c")
original = tag_cleanup.MAX_FINDINGS
tag_cleanup.MAX_FINDINGS = 2
try:
job = await self.find()
finally:
tag_cleanup.MAX_FINDINGS = original
unused = (await self.findings(job.id))["rules"][1]
self.assertEqual((unused["total"], len(unused["findings"])), (3, 2))
async def test_unknown_jobs_are_not_found(self):
self.assertEqual((await self.findings("nope", status=404))["code"], "not-found")
other = self.api._jobs.start(
"health", "Health", admission="read", runner=lambda job: asyncio.sleep(0)
)
await other.task
self.assertEqual(
(await self.findings(other.id, status=404))["code"], "not-found"
)
class TestPreview(TagCleanupTestCase):
async def test_the_plan_names_scope_protection_and_a_required_backup(self):
self.seed()
job = await self.find()
PromptManagerConfig.SAFETY_BACKUP = False
plan = await self.plan(await self.select(job, comma=True))
self.assertEqual(plan["operation"], "tag_cleanup")
self.assertEqual(
plan["scope"],
{
"count": 2,
"label": "Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)",
},
)
self.assertEqual(plan["protected"], {"count": 0, "reasons": []})
self.assertEqual(plan["backup"]["policy"], "required")
self.assertEqual(
plan["backup"]["destination_label"], "prompts.db.backup_<date and time>"
)
self.assertEqual(plan["backup"]["expected_bytes"], self.database_bytes())
self.assertEqual(
plan["media"], {"deletes_files": False, "label": "No files are removed"}
)
self.assertEqual(
[(d["label"], d["detail"]) for d in plan["details"]],
[
("a, b", "Tags containing a comma · 1 prompt"),
("x,y", "Tags containing a comma · no links"),
],
)
self.assertNotIn('"links"', json.dumps(plan)) # the hash stays server-side
async def test_every_bad_shape_is_invalid(self):
self.seed()
job = await self.find()
good = await self.select(job, comma=True)
comma_ids = good["select"][0]["tag_ids"]
cases = [
[],
{},
{"job_id": job.id},
{**good, "extra": 1},
{**good, "job_id": ""},
{**good, "job_id": 3},
{**good, "job_id": "x" * 65},
{**good, "select": []},
{**good, "select": "comma"},
{**good, "select": [good["select"][0]] * 2},
{**good, "select": [{"rule": "reboot", "tag_ids": comma_ids}]},
{**good, "select": [{"rule": "comma"}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids, "x": 1}]},
{**good, "select": [{"rule": "comma", "tag_ids": []}]},
{**good, "select": [{"rule": "comma", "tag_ids": [True]}]},
{**good, "select": [{"rule": "comma", "tag_ids": ["1"]}]},
{**good, "select": [{"rule": "comma", "tag_ids": [0]}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids * 2}]},
# A tag the search listed under the other rule.
{**good, "select": [{"rule": "unused", "tag_ids": comma_ids}]},
{**good, "select": [{"rule": "comma", "tag_ids": [999999]}]},
{**good, "select": [{"rule": "comma", "tag_ids": list(range(1, 2002))}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids}] * 3},
]
for options in cases:
with self.subTest(options=options):
body = await self.plan(options, status=400)
self.assertEqual(body["code"], "invalid-request")
async def test_a_held_find_is_needed(self):
self.seed()
options = {"job_id": "nope", "select": [{"rule": "comma", "tag_ids": [1]}]}
self.assertEqual((await self.plan(options, status=404))["code"], "not-found")
async def test_hundreds_of_ids_are_not_too_large(self):
self.tags(*(f"tag {n:04}" for n in range(500)))
job = await self.find()
plan = await self.plan(await self.select(job, unused=True))
self.assertEqual(plan["scope"]["count"], 500)
async def test_a_finding_changed_since_the_search_is_protected(self):
self.seed()
job = await self.find()
options = await self.select(job, unused=True)
with self.api.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
plan = await self.plan(options)
self.assertEqual(
plan["protected"],
{"count": 1, "reasons": ["1 tag changed since the search"]},
)
self.assertEqual(plan["scope"]["count"], 1)
class TestApply(TagCleanupTestCase):
async def run_plan(self, options):
plan = await self.plan(options)
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
return plan, job
async def test_apply_takes_a_backup_even_with_the_setting_off(self):
self.seed()
find = await self.find()
PromptManagerConfig.SAFETY_BACKUP = False
plan, job = await self.run_plan(await self.select(find, comma=True))
self.assertEqual(
(job.kind, job.title, job.admission, job.cancellable),
("maintenance", "Tag cleanup", "records", False),
)
self.assertEqual(job.state, "finished", job.log)
[backup] = self.backups()
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, backup)))
self.assertEqual(job.counters, {"changed": 2, "protected": 0, "errors": 0})
self.assertEqual(job.status_line, f"Deleted 2 tags · Safety backup {backup}")
self.assertEqual(
[row["detail"] for row in job.complete["changed"]],
[
"Deleted tag “a, b” (Tags containing a comma) · removed from 1 prompt",
"Deleted tag “x,y” (Tags containing a comma)",
],
)
# Applying one rule leaves the other rule's tags.
self.assertEqual(self.names(), ["clean", "ghost", "spirit"])
self.assertEqual(self.api.db.search_prompts()[0]["tags"], ["clean"])
async def test_changed_targets_are_kept_one_by_one_and_the_rest_apply(self):
self.seed()
find = await self.find()
plan = await self.plan(await self.select(find, unused=True))
with self.api.db.model.get_connection() as conn:
conn.execute("DELETE FROM tags WHERE name='spirit'")
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
self.assertEqual(job.state, "finished", job.log)
self.assertEqual(job.counters, {"changed": 1, "protected": 1, "errors": 0})
self.assertEqual(
[row["detail"] for row in job.complete["protected"]],
["Kept tag “spirit”: already deleted"],
)
self.assertEqual(self.names(), ["a, b", "clean", "x,y"])
async def test_findings_protected_at_review_are_in_the_job(self):
self.seed()
find = await self.find()
options = await self.select(find, unused=True)
with self.api.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
_plan, job = await self.run_plan(options)
self.assertEqual(job.counters["protected"], 1)
self.assertEqual(
[row["detail"] for row in job.complete["protected"]],
["Kept tag “ghost”: changed since the search"],
)
async def test_a_plan_applies_once_and_expires(self):
self.seed()
find = await self.find()
plan, _job = await self.run_plan(await self.select(find, comma=True))
used = await self.post(APPLY, {"token": plan["token"]}, 409)
self.assertEqual(used["code"], "plan-used")
expired = await self.post(APPLY, {"token": "f" * 32}, 410)
self.assertEqual(expired["code"], "plan-expired")
async def test_a_failed_job_offers_the_maintenance_section(self):
self.seed()
find = await self.find()
plan = await self.plan(await self.select(find, comma=True))
self.api.db.apply_maintenance = lambda *args: 1 / 0
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
self.assertEqual(job.state, "failed")
self.assertEqual(job.status_line, "Maintenance failed; nothing was changed.")
self.assertEqual(job.scope["operation"], "tag_cleanup")
self.assertIn("a, b", self.names())
class TestOperationEnum(TagCleanupTestCase):
async def test_the_operation_error_names_tag_cleanup(self):
body = await self.preview("reboot", status=400)
self.assertIn("tag_cleanup", body["error"])
+2 -31
View File
@@ -48,7 +48,6 @@ class TestClassify(unittest.TestCase):
def test_documents_a_test_reads_are_docs(self):
for paths in (
["README.md"],
["CHANGELOG.md"],
["README-legacy.md", "assets/readme/hero.webp"],
["assets/brand/banner.webp", ".github/FUNDING.yml"],
):
@@ -288,43 +287,15 @@ class TestCommandLine(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(marker.exists())
self.assertIn("inert", result.stdout)
# No range from pre-commit (a manual run) and a code push both run it.
# No range from pre-commit (a manual run) and a docs push both run it.
self.assertEqual(self.run_script(*command).returncode, 0)
self.assertTrue(marker.exists())
marker.unlink()
self.commit({"py/x.py": "x = 1\n"})
self.commit({"README.md": "r3\n"})
refs["PRE_COMMIT_TO_REF"] = self.head()
self.assertEqual(self.run_script(*command, **refs).returncode, 0)
self.assertTrue(marker.exists())
def test_a_docs_push_runs_only_the_tests_that_read_the_docs(self):
# #679: the full suite took minutes for a README edit.
ran = unittest.mock.Mock(return_value=unittest.mock.Mock(returncode=5))
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
with (
unittest.mock.patch.object(
change_class, "class_of_range", return_value="docs"
),
unittest.mock.patch.object(change_class.subprocess, "run", ran),
):
code = change_class.main(["--unless-inert", "python", "-m", "full"])
ran.assert_called_once_with(
[
sys.executable,
"-m",
"unittest",
"tests.test_brand_assets",
"tests.test_package_contents",
],
check=False,
)
self.assertEqual(code, 5)
def test_the_docs_tests_named_by_the_hook_exist(self):
for module in change_class.DOCS_TESTS:
path = ROOT / (module.replace(".", "/") + ".py")
self.assertTrue(path.is_file(), module)
def test_the_pre_push_command_is_found_through_path(self):
# On Windows a bare "npm" is npm.cmd: only a PATH lookup with PATHEXT finds it.
found = unittest.mock.Mock(return_value=unittest.mock.Mock(returncode=3))
-56
View File
@@ -537,32 +537,6 @@ class LoraImportRouteTests(LoraImportAPITestCase):
resp, body = await self._post(APPLY, {"token": plan["token"]})
self.assertEqual((resp.status, body["code"]), (409, "plan-used"))
async def test_preview_and_job_say_how_many_entries_were_not_made_tags(self):
# #618: the review and the job log count the trained-words entries
# that were lists or sentences.
_write_metadata(self.loras, "neon", words=["glow", "a, b, c", "<lora:x:1>"])
(self.loras / "neon.png").write_bytes(_png_bytes())
resp, plan = await self._post(PREVIEW)
self.assertEqual(resp.status, 200, plan)
self.assertEqual((plan["trigger_tags"], plan["trigger_not_tags"]), (1, 2))
resp, body = await self._post(APPLY, {"token": plan["token"]})
self.assertEqual(resp.status, 202, body)
job = self.api._jobs.get(body["job"]["id"])
await job.task
self.assertEqual(job.state, "finished", job.log)
line = "2 trained-words entries were not made tags (lists or sentences)"
self.assertTrue(any(entry.endswith(line) for entry in job.log), job.log)
neon = self.api.db.search_prompts(category=CATEGORY)[0]
self.assertEqual(sorted(neon["tags"]), ["glow", "lora-manager", "lora:neon"])
async def test_job_log_is_silent_when_every_entry_is_a_tag(self):
self._two_loras()
_plan, job = await self._apply_reviewed()
await job.task
self.assertEqual(job.state, "finished", job.log)
self.assertFalse(any("not made tags" in line for line in job.log), job.log)
async def test_a_finished_import_clears_the_layout_cache(self):
# #362: the import may link files under a folder LoraManager created
# after the image routes cached its layout.
@@ -1472,40 +1446,10 @@ class LoraImportStageTests(unittest.TestCase):
"hash": generate_prompt_hash("neon street"),
"tags": ["lora-manager", "lora:neon", "glow"],
"images": [os.path.realpath(self.loras / "neon.png")],
"trigger_not_tags": 0,
}
],
)
# #618: only one short clean phrase becomes a tag.
def test_build_record_makes_tags_only_from_short_phrases(self):
metadata = {
"file_name": "neon.safetensors",
"model_name": "neon",
"civitai": {"trainedWords": ["neon", "a, b, c", "<lora:x:1>"]},
}
record = lora_import.build_record(metadata, self.loras / "neon.json", [])
self.assertEqual(record["tags"], ["lora-manager", "lora:neon", "neon"])
self.assertEqual(record["trigger_not_tags"], 2)
def test_stage_counts_entries_not_made_tags(self):
_write_metadata(self.loras, "one", words=["glow", "a, b", "<lora:x:1>"])
_write_metadata(self.loras, "two", words=["long, comma, list"])
_write_metadata(self.loras, "three", words=["fine"])
staged = lora_import.stage(self.discover(), self.tmp, media_extensions=MEDIA)
self.assertEqual(staged.stats["trigger_not_tags"], 3)
tags = {r["name"]: r["tags"] for r in staged.records}
self.assertEqual(tags["one"], ["lora-manager", "lora:one", "glow"])
self.assertEqual(tags["two"], ["lora-manager", "lora:two"])
def test_preview_sums_trigger_tags_and_not_tags(self):
_write_metadata(self.loras, "one", words=["glow", "a, b", "(x:1.2)"])
_write_metadata(self.loras, "two", words=["neon", "street"])
_write_metadata(self.loras, "none")
found = lora_import.preview(str(self.lm), self.tmp / "cache", MEDIA)
self.assertEqual((found["trigger_tags"], found["trigger_not_tags"]), (3, 2))
def test_preview_counts_local_media_and_downloads(self):
_write_metadata(self.loras, "local", images=["https://civitai.com/l.png"])
(self.loras / "local.webp").write_bytes(b"x")
-72
View File
@@ -99,64 +99,6 @@ class TestGetTriggerWords(unittest.TestCase):
self.assertEqual(get_trigger_words_from_metadata(meta), ["valid", "also_valid"])
class TestTriggerWordTags(unittest.TestCase):
"""#618: a trained-words entry becomes a tag only when it is one short
clean phrase (Option A); the trigger-word lookup keeps every entry."""
KEPT = [
"neon glow",
" ohwx woman ",
"score_9",
"hatsune miku (vocaloid)",
"hatsune miku \\(vocaloid\\)",
"a" * 50,
]
SKIPPED = [
"a" * 51,
"score_9, score_8_up, realistic,",
"realistic,",
"赛博朋克,霓虹",
"line one\nline two",
"tab\tword",
"<lora:neon:0.8>",
"(masterpiece:1.2)",
"a girl (smile:0.8) outdoors",
"ratio (16:9)",
]
def test_short_clean_phrases_are_tags(self):
for entry in self.KEPT:
with self.subTest(entry=entry):
self.assertTrue(lora_utils.is_tag_phrase(entry))
def test_lists_sentences_and_prompt_syntax_are_not(self):
for entry in self.SKIPPED:
with self.subTest(entry=entry):
self.assertFalse(lora_utils.is_tag_phrase(entry))
def test_non_entries_are_not_phrases(self):
for entry in ("", " ", None, 12):
with self.subTest(entry=entry):
self.assertFalse(lora_utils.is_tag_phrase(entry))
def test_trigger_word_tags_keeps_order_strips_and_counts(self):
meta = _make_metadata(
trained_words=[*self.KEPT, *self.SKIPPED, "", " ", None, 12]
)
tags, not_tags = lora_utils.trigger_word_tags(meta)
self.assertEqual(tags, [entry.strip() for entry in self.KEPT])
self.assertEqual(not_tags, len(self.SKIPPED))
def test_trigger_word_tags_without_trained_words(self):
self.assertEqual(lora_utils.trigger_word_tags({}), ([], 0))
def test_trigger_words_still_hold_every_entry(self):
meta = _make_metadata(trained_words=["neon", "a, b, c", "<lora:x:1>"])
self.assertEqual(
get_trigger_words_from_metadata(meta), ["neon", "a, b, c", "<lora:x:1>"]
)
class TestGetExamplePrompt(unittest.TestCase):
"""Test get_example_prompt_from_metadata — extracts first usable prompt."""
@@ -1354,20 +1296,6 @@ class TestTriggerWordCache(unittest.TestCase):
self.cache.get_trigger_words("my_lora"), ["trigger1", "trigger2"]
)
def test_lists_and_sentences_stay_trigger_words(self):
"""#618: the phrase rule only decides tags; the lookup keeps all."""
with tempfile.TemporaryDirectory() as tmpdir:
words = ["neon", "a, b, c", "<lora:x:1>"]
meta = {
"file_name": "lists.safetensors",
"civitai": {"trainedWords": words},
}
(Path(tmpdir) / "lists.metadata.json").write_text(json.dumps(meta))
(Path(tmpdir) / "lists.safetensors").write_bytes(b"m")
with patch("py.lora_utils.default_lora_roots", return_value=[tmpdir]):
self.cache.load(tmpdir)
self.assertEqual(self.cache.get_trigger_words("lists"), words)
def test_case_insensitive_lookup(self):
with tempfile.TemporaryDirectory() as tmpdir:
meta = {
-28
View File
@@ -252,13 +252,6 @@ class TestPreviews(MaintenanceDatabaseCase):
with self.assertRaises(ValueError):
self.db.preview_maintenance("reboot", [])
def test_tag_cleanup_is_planned_from_a_find_not_previewed(self):
# #618: it needs a find's findings and a selection; without this
# refusal it would fall through to the unused-components plan.
self.assertIn("tag_cleanup", maintenance.MAINTENANCE_OPERATIONS)
with self.assertRaises(ValueError):
self.db.preview_maintenance("tag_cleanup", [])
def test_same_library_gives_the_same_fingerprint(self):
self.populate()
for operation in OPERATIONS:
@@ -444,27 +437,6 @@ class TestApply(MaintenanceDatabaseCase):
draft.operation, draft.fingerprint, draft.targets, roots
)
def test_tag_cleanup_apply_runs_the_per_target_rechecks(self):
from database import tag_cleanup
with self.db.model.get_connection() as conn:
conn.execute("INSERT INTO tags(name) VALUES('a, b'), ('ghost')")
found = tag_cleanup.find_tag_cleanup(self.db_path)
select = {
r: [f["tag_id"] for f in found["rules"][r]] for r in ("comma", "unused")
}
draft = tag_cleanup.plan_tag_cleanup(self.db_path, found, select)
with self.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
result = self.db.apply_maintenance(
"tag_cleanup", draft.fingerprint, draft.targets, []
)
self.assertEqual([r["name"] for r in result["rows"]], ["a, b"])
self.assertEqual(
[(k["name"], k["reason"]) for k in result["kept"]],
[("ghost", "renamed since the review")],
)
def test_unused_components_apply_removes_exactly_the_reviewed_prompts(self):
first, second = self.save("One"), self.save("Two")
draft = self.preview("unused_components")
-1
View File
@@ -31,7 +31,6 @@ KEPT = (
"LICENSE",
"README.md",
"README-legacy.md",
"CHANGELOG.md",
"assets/readme/hero.webp",
)
-432
View File
@@ -1,432 +0,0 @@
"""Tag cleanup rules (#618, ``database/tag_cleanup.py``).
Two rules ship: tags containing a comma (removed from every owner and
deleted; a ``lora:`` tag is never one) and tags with no links (deleted). A
tag belongs to the first rule that finds it. A find reads one snapshot; a
plan re-reads each selected finding and protects the ones that changed; the
apply rechecks every target in the caller's transaction and keeps the ones
that changed, with their reason, while the rest still apply.
"""
import hashlib
import json
import os
import sqlite3
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from database import tag_cleanup
from database.operations import PromptDatabase
from utils.hashing import generate_prompt_hash
try:
from tests.open_handles import assert_closed
except ImportError: # discovered with tests/ as the top-level directory
from open_handles import assert_closed
class TagCleanupCase(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(os.path.realpath(self.temp.name))
self.db_path = str(self.root / "prompts.db")
self.db = PromptDatabase(self.db_path)
self.epoch = self.db.get_execution_epoch()
def tearDown(self):
self.db.close_all()
assert_closed(self, self.root)
self.temp.cleanup()
def save(self, text, tags):
return self.db.save_prompt(
text, prompt_hash=generate_prompt_hash(text), tags=tags
)
def add_unused(self, *names):
with self.db.model.get_connection() as conn:
for name in names:
conn.execute("INSERT INTO tags(name) VALUES(?)", (name,))
def image(self, name, tags, digest="a"):
locator = os.path.normcase(str(self.root / name))
self.db.replace_image_tags(
locator=locator,
sha256=hashlib.sha256(digest.encode()).hexdigest(),
size=1,
mtime_ns=1,
expected_epoch=self.db.get_execution_epoch(),
expected_tag_revision=0,
tags=tags,
)
return locator
def image_with(self, name, tag):
"""An image set carrying ``tag``, which the image API refuses when it
holds a comma: the link row is written as older builds could."""
self.image(name, ["placeholder"], digest=name)
with self.db.model.get_connection() as conn:
conn.execute("INSERT OR IGNORE INTO tags(name) VALUES(?)", (tag,))
conn.execute(
"INSERT INTO media_image_tags(byte_id, tag_id, position) "
"SELECT b.id, t.id, 1 FROM media_annotation_bytes b, tags t "
"WHERE t.name=? AND b.sha256=?",
(tag, hashlib.sha256(name.encode()).hexdigest()),
)
def tag_id(self, name):
with self.db.model.get_connection() as conn:
row = conn.execute("SELECT id FROM tags WHERE name=?", (name,)).fetchone()
return row[0] if row else None
def names(self):
with self.db.model.get_connection() as conn:
return sorted(r[0] for r in conn.execute("SELECT name FROM tags"))
def find(self):
return tag_cleanup.find_tag_cleanup(self.db_path)
def found(self, rule):
return [f["name"] for f in self.find()["rules"][rule]]
def plan(self, result, select):
return tag_cleanup.plan_tag_cleanup(self.db_path, result, select)
def apply(self, targets):
with self.db._pair_transaction() as conn:
return tag_cleanup.apply_tag_cleanup(conn, targets)
def select_all(self, result, rule):
return {rule: [f["tag_id"] for f in result["rules"][rule]]}
class TestRegistry(TagCleanupCase):
def test_rules_ship_in_order_with_their_copy(self):
self.assertEqual([r.id for r in tag_cleanup.RULES], ["comma", "unused"])
comma, unused = tag_cleanup.RULES
self.assertEqual(comma.title, "Tags containing a comma")
self.assertEqual(unused.title, "Tags with no links")
for rule in tag_cleanup.RULES:
for text in (rule.explanation, rule.action_label):
self.assertTrue(text and "\n" not in text)
self.assertIs(comma.apply, unused.apply)
class TestFinders(TagCleanupCase):
def test_comma_rule_finds_ascii_and_fullwidth_commas(self):
self.save("a", ["score_9, score_8_up", "clean"])
self.save("b", ["赛博朋克,霓虹", "realistic,"])
self.assertEqual(
self.found("comma"), ["realistic,", "score_9, score_8_up", "赛博朋克,霓虹"]
)
def test_comma_rule_skips_lora_identity_tags(self):
# Maintainer ruling Q1: a lora: tag is never a comma finding.
self.save("a", ["lora:Style, v2", "a, b"])
self.add_unused("lora:Old, model")
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"])
# The unused rule still lists an unused lora: tag.
self.assertEqual(
[f["name"] for f in found["rules"]["unused"]], ["lora:Old, model"]
)
def test_unused_rule_counts_prompt_pair_and_image_links(self):
self.save("a", ["on-prompt"])
self.db.save_prompt_pair("pos", "neg", tags=["on-pair"])
self.image("one.png", ["on-image"])
self.add_unused("nowhere", "Also nowhere")
self.assertEqual(self.found("unused"), ["Also nowhere", "nowhere"])
def test_an_autotag_mark_is_not_a_link(self):
self.image("one.png", [], digest="z")
with self.db.model.get_connection() as conn:
byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0]
conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,))
self.add_unused("lonely")
self.assertEqual(self.found("unused"), ["lonely"])
def test_a_comma_tag_without_links_is_listed_once_under_comma(self):
self.add_unused("a, b", "plain")
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"])
self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["plain"])
self.assertEqual(found["totals"], {"comma": 1, "unused": 1})
def test_findings_carry_counts_saved_views_and_a_links_hash(self):
prompt = self.save("a", ["x, y"])
self.save("b", ["x, y"])
self.db.save_prompt_pair("pos", "neg", tags=["x, y"])
self.image_with("one.png", "x, y")
self.add_unused("ghost")
self.db.create_saved_view(
"images",
"Ghosts",
{
"q": "",
"category": "",
"sort": "newest",
"source": "all",
"folder": "",
"media": "all",
"tags": ["ghost"],
"favorites": False,
"collection": "",
},
)
found = self.find()
[comma] = found["rules"]["comma"]
self.assertEqual(
{k: comma[k] for k in ("rule", "name", "prompts", "pairs", "images")},
{"rule": "comma", "name": "x, y", "prompts": 2, "pairs": 1, "images": 1},
)
self.assertEqual(comma["saved_views"], 0)
self.assertEqual(comma["tag_id"], self.tag_id("x, y"))
self.assertRegex(comma["links"], r"^[0-9a-f]{64}$")
self.assertEqual(
tag_cleanup.finding_detail(comma), "2 prompts · 1 pair · 1 image"
)
[ghost] = found["rules"]["unused"]
self.assertEqual(ghost["saved_views"], 1)
self.assertEqual(ghost["links"], tag_cleanup.NO_LINKS)
self.assertEqual(
tag_cleanup.finding_detail(ghost), "no links · in 1 saved view"
)
self.assertIsNotNone(prompt)
def test_cap_holds_the_first_findings_by_name_and_totals_stay_exact(self):
self.add_unused("b", "A", "c", "d")
with patch.object(tag_cleanup, "MAX_FINDINGS", 2):
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["A", "b"])
self.assertEqual(found["totals"]["unused"], 4)
def test_find_writes_nothing_and_closes_its_connection(self):
self.add_unused("a, b")
before = self.names()
with patch.object(sqlite3, "connect", wraps=sqlite3.connect) as connect:
self.find()
self.assertEqual(connect.call_count, 1)
self.assertEqual(self.names(), before)
class TestPlan(TagCleanupCase):
def test_plan_lists_targets_scope_and_details(self):
self.save("a", ["x, y"])
self.save("b", ["x, y", "q, r"])
self.add_unused("ghost")
found = self.find()
draft = self.plan(found, self.select_all(found, "comma"))
self.assertEqual(draft.operation, "tag_cleanup")
self.assertEqual(
[(t["rule"], t["name"]) for t in draft.targets],
[("comma", "q, r"), ("comma", "x, y")],
)
self.assertEqual(
draft.scope,
{
"count": 2,
"label": "Delete 2 tags (removed from 3 prompts, 0 pairs and 0 images)",
},
)
self.assertEqual(draft.protected, {"count": 0, "reasons": []})
self.assertEqual(
draft.media, {"deletes_files": False, "label": "No files are removed"}
)
self.assertEqual(
draft.details[0],
{"label": "q, r", "detail": "Tags containing a comma · 1 prompt"},
)
self.assertTrue(draft.fingerprint.startswith("sha256:"))
def test_one_tag_reads_in_the_singular(self):
self.add_unused("ghost")
found = self.find()
draft = self.plan(found, self.select_all(found, "unused"))
self.assertEqual(
draft.scope["label"],
"Delete 1 tag (removed from 0 prompts, 0 pairs and 0 images)",
)
def test_a_finding_changed_since_the_search_is_protected(self):
first = self.save("a", ["x, y"])
second = self.save("b", ["q, r"])
found = self.find()
# Moved to another prompt: the count stays 1, the links differ.
with self.db.model.get_connection() as conn:
conn.execute(
"UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?",
(second, first, self.tag_id("x, y")),
)
draft = self.plan(found, self.select_all(found, "comma"))
self.assertEqual([t["name"] for t in draft.targets], ["q, r"])
self.assertEqual(
draft.protected,
{"count": 1, "reasons": ["1 tag changed since the search"]},
)
self.assertEqual(
[(h["name"], h["reason"]) for h in tag_cleanup.held_rows(draft)],
[("x, y", "changed since the search")],
)
def test_a_renamed_or_deleted_finding_is_protected(self):
self.add_unused("ghost", "spirit")
found = self.find()
with self.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='GHOST' WHERE name='ghost'")
conn.execute("DELETE FROM tags WHERE name='spirit'")
draft = self.plan(found, self.select_all(found, "unused"))
self.assertEqual(draft.targets, [])
self.assertEqual(
draft.protected["reasons"], ["2 tags changed since the search"]
)
class TestApply(TagCleanupCase):
def planned(self, rule):
found = self.find()
return self.plan(found, self.select_all(found, rule)).targets
def test_apply_deletes_the_tag_and_its_three_kinds_of_links(self):
prompt = self.save("a", ["x, y", "keep"])
pair = self.db.save_prompt_pair("pos", "neg", tags=["x, y"])
self.image_with("one.png", "x, y")
with self.db.model.get_connection() as conn:
byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0]
conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,))
revision = conn.execute(
"SELECT image_index_revision FROM media_annotation_metadata"
).fetchone()[0]
targets = self.planned("comma")
result = self.apply(targets)
self.assertEqual(result["changed"], 1)
self.assertEqual([r["name"] for r in result["rows"]], ["x, y"])
self.assertEqual(result["kept"], [])
self.assertIsNone(self.tag_id("x, y"))
with self.db.model.get_connection() as conn:
for table in ("prompt_tags", "prompt_pair_tags", "media_image_tags"):
names = conn.execute(
f"SELECT t.name FROM {table} x JOIN tags t ON t.id=x.tag_id"
).fetchall()
self.assertNotIn(("x, y",), [tuple(n) for n in names], table)
self.assertEqual(
conn.execute(
"SELECT tag_revision FROM media_annotation_bytes"
).fetchone()[0],
2,
)
self.assertEqual(
conn.execute(
"SELECT image_index_revision FROM media_annotation_metadata"
).fetchone()[0],
revision + 1,
)
self.assertEqual(
conn.execute("SELECT COUNT(*) FROM media_image_autotags").fetchone()[0],
1,
)
self.assertIsNotNone(self.db.get_prompt_by_id(prompt))
self.assertIsNotNone(self.db.get_prompt_pair(pair))
self.assertIn("keep", self.names())
def test_saved_views_are_never_rewritten(self):
self.add_unused("ghost")
state = {
"q": "",
"category": "",
"sort": "newest",
"tags": ["ghost"],
"tag_mode": "all",
"folder": "",
}
self.db.create_saved_view("library", "Ghosts", state)
self.apply(self.planned("unused"))
[view] = self.db.list_saved_views()
self.assertEqual(view["state"]["tags"], ["ghost"])
def test_each_recheck_keeps_the_target_with_its_reason(self):
self.add_unused("gone", "renamed", "used")
first = self.save("first", ["moved, tag"])
second = self.save("second", ["anchor"])
self.save("third", ["relinked, tag"])
unused = self.planned("unused")
comma = self.planned("comma")
with self.db.model.get_connection() as conn:
conn.execute("DELETE FROM tags WHERE name='gone'")
conn.execute("UPDATE tags SET name='Renamed' WHERE name='renamed'")
conn.execute(
"INSERT INTO prompt_tags(prompt_id, tag_id) VALUES(?, ?)",
(first, self.tag_id("used")),
)
# Same count, other prompt: its links changed.
conn.execute(
"UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?",
(second, first, self.tag_id("moved, tag")),
)
result = self.apply(unused + comma)
kept = {k["name"]: k["reason"] for k in result["kept"]}
self.assertEqual(
kept,
{
"gone": "already deleted",
"renamed": "renamed since the review",
"used": "it is used now",
"moved, tag": "its links changed since the review",
},
)
# The rest of the plan still applied.
self.assertEqual([r["name"] for r in result["rows"]], ["relinked, tag"])
self.assertEqual(result["changed"], 1)
self.assertIsNone(self.tag_id("relinked, tag"))
def test_the_last_tag_is_kept_while_legacy_json_tags_remain(self):
self.add_unused("only")
with self.db.model.get_connection() as conn:
conn.execute(
"INSERT INTO prompts(text, tags) VALUES('legacy', ?)",
(json.dumps(["old"]),),
)
result = self.apply(self.planned("unused"))
self.assertEqual(
[(k["name"], k["reason"]) for k in result["kept"]],
[("only", "kept so the old tag migration does not run again")],
)
self.assertEqual(self.names(), ["only"])
def test_the_last_tag_goes_when_no_legacy_tags_remain(self):
self.add_unused("only")
result = self.apply(self.planned("unused"))
self.assertEqual(result["changed"], 1)
self.assertEqual(self.names(), [])
def test_an_exception_rolls_everything_back(self):
self.add_unused("a", "b")
targets = self.planned("unused")
calls = []
real = tag_cleanup._delete_target
def fail_second(conn, target):
calls.append(target["name"])
if len(calls) == 2:
raise sqlite3.OperationalError("disk I/O error")
real(conn, target)
with patch.object(tag_cleanup, "_delete_target", fail_second):
with self.assertRaises(sqlite3.OperationalError):
self.apply(targets)
self.assertEqual(self.names(), ["a", "b"])
def test_names_with_quotes_and_percent_signs(self):
name = 'it\'s 100% "real", ok'
self.save("a", [name])
self.add_unused("50%_off")
self.assertEqual(self.found("comma"), [name])
self.assertEqual(self.found("unused"), ["50%_off"])
self.apply(self.planned("comma") + self.planned("unused"))
self.assertEqual(self.names(), [])
if __name__ == "__main__":
unittest.main()
-12
View File
@@ -871,18 +871,6 @@ class TestVocabularyTagCommands(unittest.TestCase):
],
3,
)
with self.db.model.get_connection() as conn:
# The sets that carried it moved revision (a Tag dialog opened
# before sees tag-conflict); so did the image index once.
self.assertEqual(
sorted(
r[0]
for r in conn.execute(
"SELECT tag_revision FROM media_annotation_bytes"
)
),
[2, 2, 2],
)
renamed = self.command(
"rename_vocabulary_tag",
self.tag_id("keep"),
-3
View File
@@ -103,9 +103,6 @@ ROUTE_AUDIT = {
"POST /prompt_manager/maintenance/apply",
),
"no media file": (
# #618: tag cleanup reads and deletes tag rows only.
"POST /prompt_manager/jobs/tag_cleanup",
"GET /prompt_manager/maintenance/tag_cleanup/{job_id}",
"DELETE /prompt_manager/collections/{collection_id}",
"DELETE /prompt_manager/delete/{prompt_id}",
"DELETE /prompt_manager/pairs/{pair_id}",
+4 -12
View File
@@ -6,11 +6,10 @@ Four classes. Two come from allowlists:
- ``inert``: every file is one nothing reads at run or test time (the funding
file, the security policy, the old README's screenshots, issue templates).
No test job runs, and the pre-push hook skips the suite.
- ``docs``: every file is inert or a document (the READMEs, the changelog and
their images).
- ``docs``: every file is inert or a document (the READMEs and their images).
No test job runs in CI (#666). Two Python tests read these files
(``tests/test_brand_assets.py``, ``tests/test_package_contents.py``), so
the pre-push hook runs those two and not the whole suite (#679).
the pre-push hook still runs the suite for them.
- ``release``: ``pyproject.toml`` is the only file, and its ``version`` line
the only line, that changed. CI runs the package-content check only.
- ``code``: anything else. A file on no list is code, and so is every case of
@@ -32,8 +31,7 @@ Usage:
``change_class.py --unless-inert <command...>``
The pre-push hook: runs the command unless pre-commit's pushed range
(``PRE_COMMIT_FROM_REF``..``PRE_COMMIT_TO_REF``) is inert, and exits
with the command's code. For a docs range it runs ``DOCS_TESTS`` in place
of the command. The command is looked up on ``PATH`` first, so a
with the command's code. The command is looked up on ``PATH`` first, so a
bare ``npm`` finds ``npm.cmd`` on Windows, which ``subprocess`` alone
does not do.
"""
@@ -47,10 +45,8 @@ from typing import Iterable, Optional
INERT_FILES = frozenset({".github/FUNDING.yml", "SECURITY.md"})
INERT_FOLDERS = ("images/", ".github/ISSUE_TEMPLATE/")
DOCS_FILES = frozenset({"README.md", "README-legacy.md", "CHANGELOG.md"})
DOCS_FILES = frozenset({"README.md", "README-legacy.md"})
DOCS_FOLDERS = ("assets/readme/", "assets/brand/")
# The only tests that open a docs file; a docs push runs these alone (#679).
DOCS_TESTS = ("tests.test_brand_assets", "tests.test_package_contents")
VERSION_FILE = "pyproject.toml"
VERSION_LINE = re.compile(r'version = "[^"]+"')
@@ -170,10 +166,6 @@ def main(argv: list[str]) -> int:
if found == "inert":
print("Skipped: this push only changes inert files (tools/ci).")
return 0
if found == "docs":
print("This push only changes docs: running the tests that read them.")
command = [sys.executable, "-m", "unittest", *DOCS_TESTS]
return subprocess.run(command, check=False).returncode
return run_command(argv[1:])
event = os.environ.get("EVENT_NAME", "")
found = "code"
+64 -70
View File
@@ -55,7 +55,7 @@
},
"prompt-bridge-adapter.js": {
"lines": 98,
"branches": 94,
"branches": 93,
"functions": 98,
"statements": 98
},
@@ -71,6 +71,12 @@
"functions": 98,
"statements": 98
},
"workspace-entry.js": {
"lines": 80,
"branches": 80,
"functions": 80,
"statements": 80
},
"save-to-library.js": {
"lines": 98,
"branches": 98,
@@ -101,15 +107,9 @@
"functions": 98,
"statements": 98
},
"workspace-entry.js": {
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
},
"workspace/activity-job-view.mjs": {
"lines": 97,
"branches": 88,
"branches": 87,
"functions": 98,
"statements": 97
},
@@ -145,7 +145,7 @@
},
"workspace/file-inspector.mjs": {
"lines": 97,
"branches": 94,
"branches": 93,
"functions": 93,
"statements": 97
},
@@ -217,7 +217,7 @@
},
"workspace/images-delete.mjs": {
"lines": 95,
"branches": 82,
"branches": 81,
"functions": 92,
"statements": 95
},
@@ -293,12 +293,6 @@
"functions": 98,
"statements": 98
},
"workspace/inspect-choice.mjs": {
"lines": 98,
"branches": 92,
"functions": 89,
"statements": 98
},
"workspace/inspect.mjs": {
"lines": 98,
"branches": 92,
@@ -341,9 +335,15 @@
"functions": 98,
"statements": 98
},
"workspace/older-images-notice.mjs": {
"lines": 80,
"branches": 70,
"functions": 80,
"statements": 80
},
"workspace/library-location.mjs": {
"lines": 94,
"branches": 92,
"branches": 91,
"functions": 93,
"statements": 94
},
@@ -427,7 +427,7 @@
},
"workspace/media-viewer.mjs": {
"lines": 98,
"branches": 95,
"branches": 93,
"functions": 98,
"statements": 98
},
@@ -437,12 +437,6 @@
"functions": 98,
"statements": 98
},
"workspace/older-images-notice.mjs": {
"lines": 82,
"branches": 91,
"functions": 81,
"statements": 82
},
"workspace/plural.mjs": {
"lines": 98,
"branches": 98,
@@ -486,27 +480,21 @@
"statements": 95
},
"workspace/review-link.mjs": {
"lines": 96,
"branches": 77,
"functions": 93,
"statements": 96
},
"workspace/review-options.mjs": {
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
"lines": 95,
"branches": 70,
"functions": 91,
"statements": 95
},
"workspace/review-state.mjs": {
"lines": 96,
"branches": 89,
"branches": 85,
"functions": 98,
"statements": 96
},
"workspace/review.mjs": {
"lines": 98,
"branches": 92,
"functions": 94,
"branches": 89,
"functions": 93,
"statements": 98
},
"workspace/saved-views.mjs": {
@@ -521,12 +509,6 @@
"functions": 98,
"statements": 98
},
"workspace/sticky-chrome.mjs": {
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
},
"workspace/system-appearance.mjs": {
"lines": 98,
"branches": 93,
@@ -541,7 +523,7 @@
},
"workspace/system-controls.mjs": {
"lines": 98,
"branches": 90,
"branches": 89,
"functions": 89,
"statements": 98
},
@@ -551,12 +533,6 @@
"functions": 94,
"statements": 95
},
"workspace/system-instructions.mjs": {
"lines": 97,
"branches": 88,
"functions": 98,
"statements": 97
},
"workspace/system-integrations.mjs": {
"lines": 97,
"branches": 90,
@@ -564,10 +540,10 @@
"statements": 97
},
"workspace/system-maintenance.mjs": {
"lines": 96,
"branches": 87,
"lines": 93,
"branches": 81,
"functions": 92,
"statements": 96
"statements": 93
},
"workspace/system-overview.mjs": {
"lines": 96,
@@ -575,21 +551,27 @@
"functions": 98,
"statements": 96
},
"workspace/system-skipped-tags.mjs": {
"lines": 98,
"branches": 89,
"functions": 98,
"statements": 98
},
"workspace/system-sources.mjs": {
"lines": 98,
"branches": 89,
"functions": 95,
"statements": 98
},
"workspace/system-instructions.mjs": {
"lines": 80,
"branches": 80,
"functions": 80,
"statements": 80
},
"workspace/system-skipped-tags.mjs": {
"lines": 80,
"branches": 80,
"functions": 80,
"statements": 80
},
"workspace/system-state.mjs": {
"lines": 98,
"branches": 95,
"branches": 94,
"functions": 98,
"statements": 98
},
@@ -600,10 +582,10 @@
"statements": 98
},
"workspace/system-thumbnail-location.mjs": {
"lines": 92,
"branches": 80,
"functions": 93,
"statements": 92
"lines": 80,
"branches": 65,
"functions": 75,
"statements": 80
},
"workspace/system-thumbnails.mjs": {
"lines": 98,
@@ -617,12 +599,6 @@
"functions": 98,
"statements": 98
},
"workspace/tag-cleanup-review.mjs": {
"lines": 96,
"branches": 85,
"functions": 98,
"statements": 96
},
"workspace/theme.mjs": {
"lines": 98,
"branches": 93,
@@ -688,5 +664,23 @@
"branches": 95,
"functions": 98,
"statements": 97
},
"workspace/sticky-chrome.mjs": {
"lines": 80,
"branches": 60,
"functions": 80,
"statements": 80
},
"workspace/inspect-choice.mjs": {
"lines": 98,
"branches": 92,
"functions": 89,
"statements": 98
},
"workspace/review-options.mjs": {
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
}
}
+1 -13
View File
@@ -19,9 +19,7 @@
* an image tagging job shows Tagged, Unchanged, Skipped and Errors, opens Tagged and Unchanged rows, and reads
* "Tagging log" and "Cancel tagging".
* - D101 (System S7): a finished duplicate search that found groups adds **Review groups** after Download report; it
* opens "Review duplicate image files" for this search. #618 (D210): a finished tag search that found tags adds
* **Review tags** the same way; it opens "Review tag cleanup" (tag-cleanup-review.mjs). A failed Tag cleanup apply's
* Review again goes to Maintenance (its plan needs a search's ticked tags).
* opens "Review duplicate image files" for this search.
* - D111: the kind's descriptor (activity-kinds.mjs `viewOf`) decides them for every kind: a thumbnail job counts
* Generated, Skipped and Errors; a kind without groups (the health check, a held legacy-page operation) shows no
* tiles and no Results, never another kind's zeros. A job without a known total has an indeterminate `<progress>`;
@@ -43,7 +41,6 @@ import { createInspectionController } from './inspection-state.mjs';
import { createPromptSender } from './prompt-sender.mjs';
import { imageKey } from './images-state.mjs';
import { OPERATION_TITLES, openDuplicatesReview, reviewPlan } from './maintenance-review.mjs';
import { hasTagFindings, openTagCleanupReview } from './tag-cleanup-review.mjs';
import { navigateTo } from './state.mjs';
export const DETAIL_INTERVAL_MS = 1000;
@@ -99,8 +96,6 @@ const OVERTAKEN = new Set(['plan-changed', 'storage-changed', 'plan-expired']);
export function reviewAgainOf(job) {
if (job.state !== 'failed') return null;
const failure = job.scope?.failure;
// #618: a Tag cleanup is planned from a search's ticked tags, never previewed alone: search again in Maintenance.
if (job.kind === 'maintenance' && job.scope?.operation === 'tag_cleanup') return { section: '#/system/maintenance' };
if (job.kind === 'maintenance' && OVERTAKEN.has(failure) && Object.hasOwn(OPERATION_TITLES, job.scope?.operation)) {
return { operation: job.scope.operation };
}
@@ -151,8 +146,6 @@ export function filterRows(rows, filter) {
/** #550: whether a job lists records (a maintenance plan of records), not files. */
export function listsRecords(job) {
// #618: a tag search's rows are tags.
if (job?.kind === 'tag_cleanup') return true;
return job?.kind === 'maintenance' && job.scope?.operation !== 'missing_links';
}
@@ -187,8 +180,6 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) {
const review = createReviewMetadataButton(scope); // D87
// System S7 (D101): a finished duplicate search that found groups reviews them.
const reviewGroups = createButton('Review groups', 'ca-primary');
// #618 (D210): a finished tag search that found tags reviews them.
const reviewTags = createButton('Review tags', 'ca-primary');
// S7 review M2: a failed apply whose plan the library overtook goes back to its review.
const reviewAgain = createButton('Review again', 'ca-primary');
@@ -370,8 +361,6 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) {
else review.remove();
if (hasDuplicateGroups(job)) { if (!reviewGroups.isConnected) download.after(reviewGroups); } // D101
else reviewGroups.remove();
if (hasTagFindings(job)) { if (!reviewTags.isConnected) download.after(reviewTags); } // D210
else reviewTags.remove();
if (reviewAgainOf(job)) { if (!reviewAgain.isConnected) download.after(reviewAgain); }
else reviewAgain.remove();
// Truth rule: a job that cannot be cancelled (a held legacy-page job) shows no Cancel.
@@ -477,7 +466,6 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) {
}
});
scope.listen(reviewGroups, 'click', () => openDuplicatesReview({ api, store, scope, jobId, trigger: reviewGroups }));
scope.listen(reviewTags, 'click', () => openTagCleanupReview({ api, store, scope, jobId, trigger: reviewTags }));
scope.listen(reviewAgain, 'click', () => {
const job = current();
const target = job ? reviewAgainOf(job) : null;
+1 -19
View File
@@ -13,8 +13,7 @@
* `scan` is exactly the D56 view and `image-tags` the D89 one. `thumbnails` counts Generated (green), Skipped and
* Errors (red). System S7: `maintenance` (a reviewed plan's apply) counts Changed, Protected and Errors and, when it
* failed, ends with the server's reason; `duplicates` (the search) counts Groups found; `duplicate_cleanup` counts
* Removed, Kept and Errors; #618 (D210): `tag_cleanup` (the tag search) counts Found and cannot be cancelled; S10:
* `lora_import` counts Imported, Linked to existing, Skipped, Images downloaded, Download
* Removed, Kept and Errors; S10: `lora_import` counts Imported, Linked to existing, Skipped, Images downloaded, Download
* errors and Errors and, when it failed, ends with the server's reason (the previous imports were kept); S9: `restore`
* ends with the server's line (what was restored, or why nothing changed). Any other kind (the health check, a held legacy-page operation, a kind this page does not know) gets
* the generic descriptor: title-based copy and no tiles or outcomes, so it never shows another kind's zeros (S1 review
@@ -47,11 +46,6 @@ export const groupsOf = job => {
const groups = job.counters?.groups_found ?? 0;
return `${number(groups)} ${noun(groups, 'group')} found`;
};
/** "232 tags found" (#618: a tag search). */
export const tagsFoundOf = job => {
const found = job.counters?.found ?? 0;
return `${number(found)} ${noun(found, 'tag')} found`;
};
/** "3 removed" (System S7: a duplicate cleanup). */
export const removedOf = job => counted(job, 'removed', 'removed');
/** "12 imported" (System S10: the LoRA reference import). */
@@ -236,18 +230,6 @@ export const KINDS = Object.freeze({
cancelLabel: 'Cancel search',
cancel: 'Cancel search',
}),
// #618 (D210): the tag search, one snapshot read the server cannot stop; its rows are tags (records), never opened.
tag_cleanup: Object.freeze({
...GENERIC,
pillVerb: 'Finding tags',
startToast: () => 'Tag search started.',
finishToast: namedFinish(() => 'Tag search', tagsFoundOf, tagsFoundOf),
line: tagsFoundOf,
kept: tagsFoundOf,
tiles: tiles([['found', 'Found', '']]),
outcomes: tiles([['found', 'Found']]),
log: 'Search log',
}),
// System S7: the reviewed duplicate cleanup; the kept copies open the viewer, the removed ones are gone.
duplicate_cleanup: Object.freeze({
...GENERIC,
-4
View File
@@ -17,8 +17,6 @@
* kept unless another is chosen). Each choice names its copy by `{group_id, root_index, path}`, so equal paths in two
* sources are never confused. The `p.small` says what removing a copy does, History keeping the removed paths in its
* run records. "Review duplicate cleanup" reviews the groups shown so far as a `duplicate_files` plan.
* - D210 (#618): "Review tag cleanup" (tag-cleanup-review.mjs) reviews its ticked tags as a `tag_cleanup` plan in the
* same D100 dialog; that plan's backup is always taken (`required`).
*
* Every request goes through the page's api client; every listener sits on the section's `scope`.
*/
@@ -53,8 +51,6 @@ export const OPERATION_TITLES = Object.freeze({
unused_components: 'Unused prompt components',
// D192 (#550): beyond the concept, System › Maintenance › Database.
pair_metadata: 'Pair category and tags',
// D210 (#618): beyond the concept; planned from a tag search's ticked tags (tag-cleanup-review.mjs).
tag_cleanup: 'Tag cleanup',
missing_links: 'Missing-file links',
duplicate_files: 'Duplicate image files',
// Reviewed and applied through the API and seen in Activity; Maintenance has no row for it (the concept has none).
+1 -18
View File
@@ -17,9 +17,7 @@
* reviews the import (`POST /lora/import/preview`, read-only) and the shared review dialog shows what it replaces,
* what saved pairs block, what it downloads and the backup box; Start runs the "LoRA reference import" Activity job.
* #355: its first row, "LoraManager", names the settings source, storage mode and library the server read (the
* settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images.
* #618 (D210): "Trigger words", after Found and only when a count is above 0, says how many trained-words entries
* become tags and how many are lists or sentences the import does not make tags. When
* settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images. When
* LoraManager's settings cannot be used, the plan has no token and the review says why and offers only Close.
*/
import { createButton } from '../shared/toolkit/core.js';
@@ -200,19 +198,6 @@ export function closeNote(plan) {
}
/** D107: the import review's rows from the server's plan. */
/**
* The "Trigger words" row (#618): how many trained-words entries become tags and how many are lists or sentences the
* import does not make tags; null when neither is above 0.
*/
function triggerWordsText(plan) {
const positive = value => (Number.isSafeInteger(value) && value > 0 ? value : 0);
const tags = positive(plan.trigger_tags);
const notTags = positive(plan.trigger_not_tags);
if (!tags && !notTags) return null;
const made = `${number(tags)} become tags`;
return notTags ? `${made} · ${number(notTags)} not made tags (lists or sentences)` : made;
}
export function importGrid(plan) {
const downloads = Number.isSafeInteger(plan.planned_downloads) ? plan.planned_downloads : 0;
const network = downloads
@@ -223,13 +208,11 @@ export function importGrid(plan) {
const readable = count(plan.with_metadata);
const local = count(plan.with_local_media);
const layout = layoutText(plan.layout);
const triggers = triggerWordsText(plan);
return [
...(layout ? [[LAYOUT_TERM, layout]] : []),
['Scope', plan.scope?.label || `${number(readable)} ${noun(readable, 'LoRA')}`],
['Found', `${number(found)} metadata ${noun(found, 'file')} · ${number(readable)} ${noun(readable, 'LoRA')} · `
+ `${number(local)} with local images`],
...(triggers ? [['Trigger words', triggers]] : []),
['Protected', protectedText(plan.protected)],
['Network', network],
['Backup', backupText(plan.backup)],
+7 -16
View File
@@ -3,16 +3,14 @@
*
* - The notice "Check first. Review changes. Then apply." with "Run health checks" (D123), then the surfaces
* "Database" and "Images & cache" with the concept's eight operations, in its order, labels and danger marks, plus
* D192 (#550, beyond the concept): "Pair category and tags" after "Unused prompt components", and D210 (#618, beyond
* the concept): "Tag cleanup" after it.
* D192 (#550, beyond the concept): "Pair category and tags" after "Unused prompt components".
* - Integrity & relationship checks → Check runs the same read-only health check and opens the Health report (D95);
* its "Review missing links" reviews a fresh Missing-file links plan, never a cleanup.
* - Duplicate prompt text, Optimize database, Unused prompt components, Pair category and tags (`pair_metadata`: fill
* old Pair prompts' empty category and tags from their saved pairs) and Missing-file links → Review plan open the
* D100 plan review (maintenance-review.mjs), which applies only what it showed, as an Activity job.
* - Duplicate image files → Find duplicates starts the duplicate search as an Activity job and opens it; its view
* offers Review groups (D101) once it found some. Tag cleanup → Find tags (D210, danger: it ends in deleting tags)
* starts the tag search the same way (`startFind`); its view offers Review tags once it found some.
* offers Review groups (D101) once it found some.
* - Thumbnail cache → Review options opens the S5 "Thumbnail maintenance" dialog (D99).
* - D102 (Q5): Metadata cache clears only the browser entries Prompt Manager owns as a cache (cache-ownership.js,
* #222). The inventory has none, so the row says "Nothing is cached in this browser." and its Review plan is
@@ -31,8 +29,6 @@ import { noun } from './plural.mjs';
export const DUPLICATES_KIND = 'duplicates';
export const FIND_FAILED = 'The duplicate search could not start. Try again.';
export const TAG_CLEANUP_KIND = 'tag_cleanup';
export const TAG_FIND_FAILED = 'The tag search could not start. Try again.';
export const NOTHING_CACHED_REASON = 'Nothing is cached in this browser.';
export const STORAGE_UNCHECKED_REASON = 'This browser did not allow checking its storage.';
export const METADATA_CACHE_DESCRIPTION = 'Clear only Prompt Manager metadata cached by this browser.';
@@ -48,9 +44,6 @@ export const MAINTENANCE_SURFACES = Object.freeze([
// D192 (#550): beyond the concept. Fills only empty fields, deletes nothing (no danger mark).
['Pair category and tags', 'Fill an empty category or tags on prompts older Pair node runs saved, from their saved ' +
'pairs. Only empty fields of never-edited prompts.', 'Review plan', 'pair_metadata'],
// D210 (#618): beyond the concept. Finds comma-list and unused tags; the review deletes only ticked ones (danger).
['Tag cleanup', 'Find tags that are whole comma lists or are used nowhere. Review them, then remove only what you ' +
'tick.', 'Find tags', TAG_CLEANUP_KIND, true],
]],
['Images & cache', [
['Missing-file links', 'Remove stale database links only. Files on disk are never deleted by this operation.', 'Review plan',
@@ -73,10 +66,10 @@ const ownership = () => window.CacheOwnership;
const browserStorage = () => window.localStorage;
const cacheStorage = () => ('caches' in window ? window.caches : null);
/** Start a search job of `kind` (duplicates, tag_cleanup) and open it; a refused start toasts busy, a failed one `failed`. */
export async function startFind({ store, scope, kind, failed, notify = showWorkspaceToast, navigate = navigateTo }) {
/** Start the duplicate search and open its job; a refused or failed start says why and stays. */
export async function findDuplicates({ store, scope, notify = showWorkspaceToast, navigate = navigateTo }) {
try {
const result = await store.start(kind);
const result = await store.start(DUPLICATES_KIND);
if (scope.signal.aborted) return;
if (result.busy !== undefined) {
notify(busyToast(result.busy));
@@ -84,7 +77,7 @@ export async function startFind({ store, scope, kind, failed, notify = showWorks
}
navigate(`#/activity/${result.job.id}`);
} catch {
if (!scope.signal.aborted) notify(failed);
if (!scope.signal.aborted) notify(FIND_FAILED);
}
}
@@ -164,9 +157,7 @@ export function mountMaintenance(container, { api, activity, scope, navigate = n
const reviewMissing = reviewMissingLinks({ api, store: activity, scope, notify, navigate });
const actions = {
health: button => runHealthAction({ api, activity, scope, button, onReviewMissing: reviewMissing, notify }),
duplicates: () => startFind({ store: activity, scope, kind: DUPLICATES_KIND, failed: FIND_FAILED, notify, navigate }),
[TAG_CLEANUP_KIND]: () => startFind({ store: activity, scope, kind: TAG_CLEANUP_KIND, failed: TAG_FIND_FAILED, notify,
navigate }),
duplicates: () => findDuplicates({ store: activity, scope, notify, navigate }),
thumbnails: button => openThumbnailReview({ api, store: activity, scope, trigger: button, navigate }),
};
const surfaces = MAINTENANCE_SURFACES.map(([heading, rows]) => {
-200
View File
@@ -1,200 +0,0 @@
/**
* Review tag cleanup (#618, D210): a finished tag search's findings, ticked one by one or a whole rule at a time, then
* reviewed as the `tag_cleanup` D100 plan (maintenance-review.mjs `reviewPlan`).
*
* The dialog has no rule table of its own: it draws whatever rules `GET /prompt_manager/maintenance/tag_cleanup/<job>`
* returns (each `{id, title, explanation, action_label, total, findings:[{tag_id, name, detail}]}`), so a later rule
* needs no change here. Top to bottom: the `role="status"` line ("N tags selected"); per rule with findings a checkbox
* "<title> (<total>)" that ticks or clears every listed tag of the rule (indeterminate while only some are), its
* explanation and what applying does, and a closed "Show tags" `details` whose rows are built when it first opens (a
* search may list thousands); when the server's cap cut the list, a line says to search again; the note that nothing is
* deleted until the cleanup is reviewed and applied; Cancel and "Review cleanup" (disabled while nothing is ticked).
* Nothing is ticked when it opens. Tag names are set as text and wrap anywhere (a comma tag can be hundreds of
* characters long).
*/
import { createButton } from '../shared/toolkit/core.js';
import { closeWorkspaceDialog, openContentDialog } from './workspace-dialogs.mjs';
import { REVIEW_FAILED, reviewPlan, reviewRefusal } from './maintenance-review.mjs';
import { showWorkspaceToast } from './toast.mjs';
import { navigateTo } from './state.mjs';
import { noun } from './plural.mjs';
export const FINDINGS_URL = '/prompt_manager/maintenance/tag_cleanup';
export const TAG_CLEANUP_OPERATION = 'tag_cleanup';
export const REVIEW_TITLE = 'Review tag cleanup';
export const REVIEW_LABEL = 'Review cleanup';
export const SHOW_TAGS = 'Show tags';
export const CLEANUP_NOTE = 'Nothing is deleted until you review and apply the cleanup. Prompts, pairs and images are kept; '
+ 'only the tag is removed from them.';
export const CAP_NOTE = 'Only the first 2,000 are listed. Clean these up, then search again.';
export const FINDINGS_FAILED = 'The tags to clean up could not be read. Nothing was changed.';
const number = value => value.toLocaleString('en-US');
function el(tag, text, className) {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (className) node.className = className;
return node;
}
/** A finished tag search that found tags to review (Activity's Review tags). */
export function hasTagFindings(job) {
return job?.kind === 'tag_cleanup' && job.state === 'finished' && (job.counters?.found ?? 0) > 0;
}
/** The rules the server returned that have findings to draw, in its order. */
export function shownRules(rules) {
return (Array.isArray(rules) ? rules : [])
.filter(rule => rule && typeof rule.id === 'string' && Array.isArray(rule.findings) && rule.findings.length > 0);
}
/** The selection: per rule, the tag ids it listed (in order) and the set of ticked ones (none at first). */
export function createSelection(rules) {
const listed = new Map();
const ticked = new Map();
for (const rule of shownRules(rules)) {
listed.set(rule.id, rule.findings.map(finding => finding.tag_id));
ticked.set(rule.id, new Set());
}
return { listed, ticked };
}
export function selectedCount(selection) {
let count = 0;
for (const set of selection.ticked.values()) count += set.size;
return count;
}
/** "N tags selected". */
export const statusText = count => `${number(count)} ${noun(count, 'tag')} selected`;
/** `all`, `some` or `none` of the rule's listed tags ticked. */
export function ruleState(selection, ruleId) {
const size = selection.ticked.get(ruleId)?.size ?? 0;
if (!size) return 'none';
return size === selection.listed.get(ruleId).length ? 'all' : 'some';
}
export const isTicked = (selection, ruleId, tagId) => selection.ticked.get(ruleId)?.has(tagId) === true;
/** Tick every listed tag of the rule, or clear them all. */
export function toggleRule(selection, ruleId, on) {
const set = selection.ticked.get(ruleId);
if (!set) return;
set.clear();
if (on) for (const tagId of selection.listed.get(ruleId)) set.add(tagId);
}
/** Tick or clear one tag the rule listed (any other id is ignored). */
export function toggleTag(selection, ruleId, tagId, on) {
const set = selection.ticked.get(ruleId);
if (!set || !selection.listed.get(ruleId).includes(tagId)) return;
if (on) set.add(tagId);
else set.delete(tagId);
}
/** The plan's `select`: each rule with ticks once, in the server's order, with its ticked ids in listed order. */
export function selectPayload(selection) {
const select = [];
for (const [rule, ids] of selection.listed) {
const set = selection.ticked.get(rule);
const tagIds = ids.filter(id => set.has(id));
if (tagIds.length) select.push({ rule, tag_ids: tagIds });
}
return select;
}
/** "Tags containing a comma (232)". */
export const ruleLabel = rule => `${rule.title} (${number(Number.isSafeInteger(rule.total) ? rule.total : rule.findings.length)})`;
/** "a, b · 3 prompts · 1 pair". */
export const findingLabel = finding => (finding.detail ? `${finding.name} · ${finding.detail}` : finding.name);
/** The rule's explanation and what applying it does, as one line. */
export const ruleText = rule => [rule.explanation, rule.action_label].filter(Boolean).join(' ');
/** The cap line when the server listed fewer tags than it found, else null. */
export const capNote = rule => (Number.isSafeInteger(rule.total) && rule.total > rule.findings.length ? CAP_NOTE : null);
function checkboxRow(text, className = 'review-confirm') {
const label = el('label', undefined, className);
const box = el('input');
box.type = 'checkbox';
label.append(box, el('span', text));
return { label, box };
}
/** One rule's block: its checkbox, its line, its lazily built tag rows and the cap line. */
function ruleBlock(rule, selection, scope, changed) {
const block = el('div', undefined, 'tag-cleanup-rule');
block.dataset.rule = rule.id;
const head = checkboxRow(ruleLabel(rule));
const rows = new Map();
const list = el('details');
list.append(el('summary', SHOW_TAGS));
const paint = () => {
const state = ruleState(selection, rule.id);
head.box.checked = state === 'all';
head.box.indeterminate = state === 'some';
for (const [tagId, box] of rows) box.checked = isTicked(selection, rule.id, tagId);
};
scope.listen(head.box, 'change', () => {
toggleRule(selection, rule.id, head.box.checked);
paint();
changed();
});
scope.listen(list, 'toggle', () => {
if (!list.open || rows.size) return;
const body = el('div', undefined, 'tag-cleanup-tags');
for (const finding of rule.findings) {
const row = checkboxRow(findingLabel(finding));
row.box.checked = isTicked(selection, rule.id, finding.tag_id);
rows.set(finding.tag_id, row.box);
scope.listen(row.box, 'change', () => {
toggleTag(selection, rule.id, finding.tag_id, row.box.checked);
paint();
changed();
});
body.append(row.label);
}
list.append(body);
});
block.append(head.label, el('p', ruleText(rule), 'small'), list);
const cap = capNote(rule);
if (cap) block.append(el('p', cap, 'small'));
return block;
}
/** Open "Review tag cleanup" for the finished tag search `jobId`. */
export async function openTagCleanupReview({ api, store, scope, jobId, trigger = null, notify = showWorkspaceToast,
navigate = navigateTo }) {
let body;
try {
body = await api.get(`${FINDINGS_URL}/${encodeURIComponent(jobId)}`, { signal: scope.signal, cache: 'no-store' });
} catch (error) {
if (!scope.signal.aborted) notify(reviewRefusal(error) === REVIEW_FAILED ? FINDINGS_FAILED : error.message);
return;
}
if (scope.signal.aborted) return;
const rules = shownRules(body?.rules);
const selection = createSelection(rules);
const status = el('p', statusText(0), 'small');
status.setAttribute('role', 'status');
const cancel = createButton('Cancel');
const review = createButton(REVIEW_LABEL);
review.disabled = true;
const actions = el('div', undefined, 'dialog-actions');
actions.append(cancel, review);
const changed = () => {
const count = selectedCount(selection);
status.textContent = statusText(count);
review.disabled = count === 0;
};
scope.listen(cancel, 'click', () => closeWorkspaceDialog());
scope.listen(review, 'click', () => {
if (review.disabled) return;
reviewPlan({ api, store, scope, operation: TAG_CLEANUP_OPERATION, trigger, hold: review,
options: { job_id: jobId, select: selectPayload(selection) }, notify, navigate });
});
const blocks = rules.map(rule => ruleBlock(rule, selection, scope, changed));
openContentDialog({ scope, title: REVIEW_TITLE, trigger,
nodes: [status, ...blocks, el('p', CLEANUP_NOTE, 'small'), actions] });
}
-2
View File
@@ -498,8 +498,6 @@ pre.prompt-text { font: inherit; font-size: 12px; line-height: 1.75; margin-bloc
/* D101: a duplicate copy's Keep label is its source and path, often long names with no space to break at; it wraps
inside its `.compare-item` so the review never scrolls sideways. */
.duplicate-groups .compare-item label { overflow-wrap: anywhere; /* D101 */ }
/* D210 (#618): a comma tag's name can be hundreds of characters with no space to break at; its row wraps the same way. */
.tag-cleanup-rule .review-confirm > span { min-inline-size: 0; overflow-wrap: anywhere; /* D210 */ }
/* D105: a review's grid values (the restore's backup file name, a safety backup's name) may be long names with no space
to break at; they wrap inside their column, so the concept's two equal columns hold at phone width. */
#modal-body > dl.meta-grid dd { overflow-wrap: anywhere; /* D105 */ }