* feat(library): set the category on many selected prompts (#437)
The Prompt library shelf gets the concept's Images selection checkbox on each
card and its .bulkbar (N selected, Set category, Clear), recorded as D148.
Set category opens the shared one-value dialog and posts
{prompt_ids, category, expected_epoch} to POST /prompt_manager/bulk/category:
the server checks the storage epoch the shelf was read under, then sets the
category on the Library parents in one BEGIN IMMEDIATE transaction, writing
only rows that change. A restored storage answers 409 storage-changed and
writes nothing. The legacy admin and images_filter bodies are unchanged.
This replaces the legacy admin page's bulk Set Category, a cutover
prerequisite (#334).
Closes #437
* feat(library): add tags to many selected prompts and select every loaded prompt (#442)
The Library selection bar (D148) gets Add tags and select-all of the loaded
shelf, the legacy admin page's bulk Add Tags and select-all checkbox.
Add tags posts {prompt_ids, tags, expected_epoch} to
POST /prompt_manager/bulk/tags: in one BEGIN IMMEDIATE transaction the server
checks the storage epoch, normalizes the names as image tags are, gives each
Library parent only the names it lacks (casefold), finds or inserts tag rows
by exact name only when some prompt gets them, and skips prompts that would
pass 20 tags. Prompt tags only. Both bulk/tags forms refuse a non-object body
with 400.
Ctrl/Cmd+A in the grid and "Select all N loaded" in the bar select every
loaded prompt; the offer follows each loaded batch.
Closes #442
* feat(vocabulary): tag search, tag sort and an Untagged prompts entry (#444)
Tags & categories gains a server-side tag search and sort (keyset pages,
cursor scoped to the query) and an "Untagged prompts" row whose Browse opens
the Library with tag_mode=untagged. Refine this view gets Tag match, saved
Library views keep it, and the routes echo the applied query so a stale
server is an error, never an unfiltered list. Recorded as D149.
Refs #444
* feat(library): filter prompts by output folder and browse tags with Any (#444)
Refine this view on the Prompt library gains the concept's Folder (folders
below an output root, read when the dialog opens) and a Tag match select
(All / Any). The listing takes folder and tag_mode, matches folders on the
normalized file_path under every spelling of each output root, echoes both
so a stale server is an error, and saved Library views keep them. Recorded
as D150.
Refs #444
* docs(library): record Add tags and select-all as D151 (#442)
* feat(library): archive paired and delete unpaired selected prompts on the server (#443)
A prompt_archive table marks Library parents hidden from the shelf; older
builds ignore it. New routes /prompt_manager/library/delete/preview,
/library/delete and /library/restore classify a selection (delete,
archive, protected, already archived, not found), execute exactly what was
reviewed under a records hold, take a verified safety backup (disk checked)
before any delete, and restore archived prompts. The shelf, search and the
shelf-facing counts honor the archive (?shelf=active|archived); archiving
repairs a stale prompt hash so scans find the archived row.
* feat(library): Delete… on the selection bar, Show archived prompts and Restore (#443)
The Library bar's Delete… previews the selection and opens the shared
review: what is deleted (in no saved pair), archived (paired: hidden,
restorable) or kept (tagged __protected__), the safety backup and what
cannot be undone. Show archived prompts (N) lists archived prompts with
Restore on their bar; an archived prompt's page shows an Archived notice
with Restore. TESTING.md records D152; the route snapshot gains the three
workspace routes.
* test(library): cover the Delete… review failure and close-only paths; record coverage floors (#443)
* fix(library): let saved-view defaults fill the missing #444 filters
libraryViewState passed `?? 'all'` and `?? ''` fallbacks that
normalizeViewState already applies to an undefined value. The redundant
branches were never taken in the page, which dropped saved-views.mjs below
its 95% branch floor. A unit now covers a shelf without the new filters.
Refs #444
* fix(library): lay out a loaded page of prompts without waiting for an animation frame (#443)
A starved renderer (headless WebKit under CPU load, a background tab) can
hold requestAnimationFrame for seconds. The shelf laid out each loaded page
only in its next frame, so the grid stayed empty after the first load or a
delete's reload while the caption already showed the new count. A loaded
batch is now laid out at once; measurements still flush per frame.
The regression test holds every animation frame and fails before the fix.
* test(saved-views): give the D153 Library view the tag_mode key (#444)
The Library saved-view state now holds tag_mode, and the API requires
every key, so main's new "Highest rated" spec posts it too.
Refs #444
* test(saved-views): give the D153 Library view the folder key (#444)
Refs #444
* fix(library): name the saved pair, not negative variants, as the archive reason (#443)
A prompt in a saved pair with no negative variants was described in the
Delete… review as "1 prompt with negative variants: hidden, restorable".
Paired prompts are archived because of the pair, so the Archive row now
reads "N prompts in a saved pair: hidden, restorable" and the first
sentence explains the pair. Found in the live test of #470.
* fix(library): nest Refine folders by path segment; backslash separates only on Windows (#444)
Live test B1: the Folder list indented a server list sorted as full-path
text, so "-" and "_" sorted before "/" and children landed under the wrong
parent (kiko/char under kiko-v6), with case variants interleaved. The
options are now a tree built by segment: each folder directly under its own
parent, case variants distinct siblings.
On POSIX a folder named "Metadata\Klein..." was listed but filtered to no
prompts, because normalize_folder read "\" as a separator. It now does so
only on Windows (ntpath), as the listing already did.
Refs #444
* fix(library): say why an archived prompt is archived, and name variants only when it has any (#443)
The archived prompt page's notice always said "This prompt and its
negative variants are hidden", also for a saved-pair prompt with none.
It now says the prompt is archived because it is in a saved pair, and
counts its negative variants only when there are any. From the live
test of #470.
* feat(library): delete a prompt in a saved pair permanently, with its own pairs (#482, server)
The Delete review's preview now marks which archive ids may be deleted
permanently (in a saved pair, and nobody else's negative), with a review
digest of the prompt and its pairs and the counts the review shows. The
write accepts an optional delete_paired_ids with their digests. Each is
deleted with its own saved pairs (image-pair links, then pairs, then the
prompt as #443 deletes it) only while its digest is unchanged. Any drift
archives it and counts it changed. Paired deletes are backed up and
disk-checked like deletes.
* feat(library): ask Archive or Delete permanently for prompts in a saved pair (#482, review)
The Delete… review asks, for prompts in a saved pair, Archive (checked
on every open, D152's review) or Delete permanently, with their saved
pairs, in a D90 radio row. The choice rewrites the grid, sentences, title
and primary in place (openReviewDialog setRows/setPrimary), and the body
carries the chosen ids with their review digests. On the archived shelf,
Show archived prompts now reads the concept's way back, "← Prompt
library", as a plain button. TESTING.md records D154.
* docs(testing): number #482's deviation D160 (D154-D159 are taken)
* Revert "docs(testing): number #482's deviation D160 (D154-D159 are taken)"
This reverts commit 96c2a293a4.
* docs(testing): number #482's deviation D160 (D154-D159 are taken)
* feat(library): Delete prompt… on a prompt's page (#481)
The recipe editor's actions read Create text revision, Archive variant…
(the selected negative variant's archive, renamed from Archive… so the two
danger buttons cannot be confused) and Delete prompt…, which closes the
editor and runs the Library's Delete… review for that prompt: the same
preview, saved-pair choice (Archive stays the default), backup and write.
A delete opens the Prompt library; an archive reads the page again.
Recorded as D161 in TESTING.md and in the editor concept comparison.
* fix(library): hold Edit metadata while a prompt's page delete runs (#481)
While the page's Delete… review or its write runs, Edit metadata is
aria-disabled and its click ignored, so no editor save can race the delete.
Adds tests for a failed review, a write answered after the page was left
(no toast, no jump, the shelf reads again) and heading focus after an
archive.
* feat(library): delete archived prompts from the archived shelf (#492)
The archived shelf's bar offers Delete… after Restore. Its review is the
permanent delete only (no Archive choice: the prompts are archived
already), with #482's grid, safety backup, review digests, records hold
and epoch fence. A prompt used as another prompt's negative stays
archived; one restored since the shelf was read is kept and counted.
The preview and delete routes take an optional shelf ('active' or
'archived'). The held write classifies the same shelf, so the permanent
delete is backed up; on this shelf the write archives and rewrites
nothing and counts every reviewed id it did not delete as changed.
* fix(library): say only 'Nothing was deleted.' on the archived shelf (#492)
Review LOWs: the archived shelf archives nothing, so its empty outcome no
longer says 'Nothing was deleted or archived.'; a mixed write (deleted,
drifted, protected, gone and restored ids) counts each once.
* fix(library): open the archived shelf's delete review on Cancel (#492)
Its only action is a permanent delete, so focus starts on Cancel
(openReviewDialog's focusCancel); the spec also pins that the copy says
the delete cannot be undone and removes the prompt's saved pairs.
322 lines
13 KiB
Python
322 lines
13 KiB
Python
"""Delete or archive selected Library prompts, and restore archived ones (#443).
|
|
|
|
The workspace Prompt library's Delete… (D152). The legacy ``POST
|
|
/prompt_manager/bulk/delete`` and ``DELETE /prompt_manager/delete/{id}`` are
|
|
separate and unchanged.
|
|
|
|
- ``POST /prompt_manager/library/delete/preview {prompt_ids, expected_epoch}``
|
|
classifies the selection (reads only, under a lease): the ids to ``delete``
|
|
(in no saved pair), to ``archive`` (paired), the ``protected`` ones (tagged
|
|
``__protected__``, kept), counts of ``already_archived`` and ``not_found``,
|
|
the ``image_links`` a delete removes, the safety ``backup`` policy and,
|
|
when a backup would be taken, the ``disk`` it needs.
|
|
- ``POST /prompt_manager/library/delete {archive_ids, delete_ids,
|
|
expected_epoch, backup}`` executes that review under a ``records`` hold
|
|
(refused 409 ``busy`` beside a scan, restore, maintenance, move or
|
|
Optimize). When a delete remains and a backup was promised (the reviewed
|
|
``backup`` was "on" or the policy is on now) it checks the disk (507
|
|
``insufficient-space``) and takes a verified safety backup (500
|
|
``backup-failed``); then one transaction deletes the reviewed deletes whose
|
|
fingerprint is unchanged since the backup and archives the paired ones.
|
|
- ``POST /prompt_manager/library/restore {prompt_ids, expected_epoch}``
|
|
removes the archive mark (under a lease).
|
|
|
|
A changed storage epoch answers 409 ``storage-changed``; nothing is written.
|
|
"""
|
|
|
|
import sqlite3
|
|
|
|
from aiohttp import web
|
|
|
|
try:
|
|
from ...database.library_commands import LibraryCommandError
|
|
from ...database.safety_backup import SafetyBackupFailed
|
|
except ImportError:
|
|
from database.library_commands import LibraryCommandError
|
|
from database.safety_backup import SafetyBackupFailed
|
|
|
|
from . import maintenance as _maintenance
|
|
from .admin import _prune_safety_backups
|
|
from .job_routes import busy_response
|
|
from .jobs import PROMPT_DELETE_JOB_KIND, JobBusy
|
|
from .prompts import parse_bulk_prompt_ids
|
|
|
|
PREVIEW_URL = "/prompt_manager/library/delete/preview"
|
|
DELETE_URL = "/prompt_manager/library/delete"
|
|
RESTORE_URL = "/prompt_manager/library/restore"
|
|
DELETE_TITLE = "Delete prompts (Library)"
|
|
_SELECTION_KEYS = frozenset({"prompt_ids", "expected_epoch"})
|
|
_DELETE_KEYS = frozenset({"archive_ids", "delete_ids", "expected_epoch", "backup"})
|
|
# #482: Delete permanently, with its digests; both or neither (a #443 body).
|
|
_PAIRED_KEYS = frozenset({"delete_paired_ids", "paired_digests"})
|
|
# #492: the shelf the Delete… runs on, optional on its own (default "active").
|
|
_SHELF_KEYS = frozenset({"shelf"})
|
|
STORAGE_CHANGED = "Prompt storage was restored; refresh the library"
|
|
|
|
|
|
def _failure(status, code, error, **extra):
|
|
return web.json_response(
|
|
{"success": False, "code": code, "error": error, **extra}, status=status
|
|
)
|
|
|
|
|
|
def _invalid(message):
|
|
return _failure(400, "invalid-request", message)
|
|
|
|
|
|
def _storage_changed(exc):
|
|
return _failure(409, exc.code, STORAGE_CHANGED, library_epoch=exc.epoch)
|
|
|
|
|
|
async def _body(request, keys, *groups):
|
|
"""The JSON object with exactly ``keys``, plus all or none of each group."""
|
|
try:
|
|
data = await request.json()
|
|
except ValueError:
|
|
raise ValueError("Expected a JSON object") from None
|
|
if not isinstance(data, dict):
|
|
raise ValueError("Expected a JSON object")
|
|
extra = set(data) - keys
|
|
partial = False
|
|
for group in groups:
|
|
if extra & group:
|
|
partial = partial or not group <= extra
|
|
extra -= group
|
|
if not keys <= set(data) or extra or partial:
|
|
raise ValueError("Request must contain exactly " + ", ".join(sorted(keys)))
|
|
return data
|
|
|
|
|
|
def _shelf(data):
|
|
"""#492: the shelf a Delete… was reviewed on."""
|
|
shelf = data.get("shelf", "active")
|
|
if shelf not in ("active", "archived"):
|
|
raise ValueError("shelf must be active or archived")
|
|
return shelf
|
|
|
|
|
|
def _paired_delete(data, archive_ids):
|
|
"""#482: the reviewed archive ids to delete with their pairs -> digest."""
|
|
if "delete_paired_ids" not in data:
|
|
return {}
|
|
ids = _reviewed_ids(data["delete_paired_ids"], "delete_paired_ids")
|
|
digests = data["paired_digests"]
|
|
if not isinstance(digests, dict):
|
|
raise ValueError("paired_digests must map prompt ids to digests")
|
|
if not set(ids) <= set(archive_ids):
|
|
raise ValueError("delete_paired_ids must be reviewed archive ids")
|
|
chosen = {}
|
|
for pid in ids:
|
|
digest = digests.get(str(pid))
|
|
if not isinstance(digest, str) or len(digest) != 64:
|
|
raise ValueError("Every delete_paired_ids entry needs its review digest")
|
|
chosen[pid] = digest
|
|
return chosen
|
|
|
|
|
|
def _reviewed_ids(value, name):
|
|
"""A reviewed id list: possibly empty, else as ``parse_bulk_prompt_ids``."""
|
|
if value == []:
|
|
return []
|
|
try:
|
|
return parse_bulk_prompt_ids(value)
|
|
except ValueError as exc:
|
|
raise ValueError(str(exc).replace("prompt_ids", name)) from None
|
|
|
|
|
|
class LibraryDeleteRoutesMixin:
|
|
"""Mixin providing the workspace Library's delete, archive and restore."""
|
|
|
|
def _register_library_delete_routes(self, routes):
|
|
routes.post(PREVIEW_URL)(self.preview_library_delete)
|
|
routes.post(DELETE_URL)(self.delete_library_prompts)
|
|
routes.post(RESTORE_URL)(self.restore_library_prompts)
|
|
|
|
async def preview_library_delete(self, request):
|
|
try:
|
|
data = await _body(request, _SELECTION_KEYS, _SHELF_KEYS)
|
|
ids = parse_bulk_prompt_ids(data["prompt_ids"])
|
|
shelf = _shelf(data)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
db = self.db
|
|
policy = self._safety_backup_policy()
|
|
try:
|
|
async with self._jobs.lease("Library delete review"):
|
|
review = await self._run_in_executor(
|
|
db.classify_library_delete,
|
|
ids,
|
|
expected_epoch=data["expected_epoch"],
|
|
shelf=shelf,
|
|
)
|
|
disk = None
|
|
if (review["delete"] or review["deletable"]) and policy == "on":
|
|
public, short, _size = await self._run_in_executor(
|
|
_maintenance.disk_plan,
|
|
db.model.db_path,
|
|
backup=True,
|
|
vacuum=False,
|
|
)
|
|
disk = {
|
|
**public,
|
|
"message": (
|
|
None
|
|
if short is None
|
|
else _maintenance.short_space_message(short)
|
|
),
|
|
}
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library delete review failed")
|
|
return _failure(500, "review-failed", "The delete could not be reviewed")
|
|
return web.json_response(
|
|
{
|
|
"success": True,
|
|
"library_epoch": review["library_epoch"],
|
|
"delete": review["delete"],
|
|
"archive": review["archive"],
|
|
"protected": review["protected"],
|
|
"already_archived": len(review["already_archived"]),
|
|
"not_archived": len(review["not_archived"]),
|
|
"not_found": len(review["not_found"]),
|
|
"image_links": review["image_links"],
|
|
# #482: the archive ids Delete permanently may delete with pairs.
|
|
"deletable": review["deletable"],
|
|
"review_digests": {
|
|
str(pid): digest for pid, digest in review["review_digests"].items()
|
|
},
|
|
"paired_counts": review["paired_counts"],
|
|
"paired_image_links": review["paired_image_links"],
|
|
"backup": policy,
|
|
"disk": disk,
|
|
}
|
|
)
|
|
|
|
async def delete_library_prompts(self, request):
|
|
try:
|
|
data = await _body(request, _DELETE_KEYS, _PAIRED_KEYS, _SHELF_KEYS)
|
|
shelf = _shelf(data)
|
|
archive_ids = _reviewed_ids(data["archive_ids"], "archive_ids")
|
|
delete_ids = _reviewed_ids(data["delete_ids"], "delete_ids")
|
|
if not archive_ids and not delete_ids:
|
|
raise ValueError("Nothing to delete or archive")
|
|
if len(archive_ids) + len(delete_ids) > 1000:
|
|
raise ValueError("At most 1000 prompts can be changed at once")
|
|
if set(archive_ids) & set(delete_ids):
|
|
raise ValueError("A prompt cannot be both archived and deleted")
|
|
if data["backup"] not in ("on", "off"):
|
|
raise ValueError("backup must be on or off")
|
|
paired = _paired_delete(data, archive_ids)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
busy = self._jobs.blocker(PROMPT_DELETE_JOB_KIND, admission="records")
|
|
if busy is not None:
|
|
return busy_response(JobBusy(busy))
|
|
try:
|
|
async with self._jobs.hold(
|
|
PROMPT_DELETE_JOB_KIND, DELETE_TITLE, admission="records"
|
|
) as job:
|
|
response = await self._held_library_delete(
|
|
self.db, data, archive_ids, delete_ids, paired, shelf
|
|
)
|
|
if response.status >= 400:
|
|
job.finish("failed")
|
|
return response
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
|
|
async def _held_library_delete(
|
|
self, db, data, archive_ids, delete_ids, paired, shelf="active"
|
|
):
|
|
epoch = data["expected_epoch"]
|
|
promised = data["backup"] == "on" or self._safety_backup_policy() == "on"
|
|
backup = None
|
|
try:
|
|
candidates = None
|
|
if delete_ids or paired:
|
|
review = await self._run_in_executor(
|
|
db.classify_library_delete,
|
|
[*delete_ids, *paired],
|
|
expected_epoch=epoch,
|
|
# #492: the same shelf, or archived ids would skip the backup.
|
|
shelf=shelf,
|
|
)
|
|
candidates = review["fingerprints"]
|
|
# #482: a permanent delete of a prompt in a saved pair is backed up too.
|
|
if (candidates or review["deletable"]) and promised:
|
|
_disk, short, _size = await self._run_in_executor(
|
|
_maintenance.disk_plan,
|
|
db.model.db_path,
|
|
backup=True,
|
|
vacuum=False,
|
|
)
|
|
if short is not None:
|
|
return _failure(
|
|
507,
|
|
"insufficient-space",
|
|
_maintenance.short_space_message(short),
|
|
)
|
|
backup = await self._run_in_executor(
|
|
_maintenance.take_safety_backup, db.model
|
|
)
|
|
result = await self._run_in_executor(
|
|
db.archive_or_delete_library_prompts,
|
|
archive_ids,
|
|
delete_ids,
|
|
expected_epoch=epoch,
|
|
candidates=candidates if candidates is not None else {},
|
|
delete_paired=paired,
|
|
shelf=shelf,
|
|
)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except SafetyBackupFailed as error:
|
|
self.logger.error("Safety backup before a Library delete failed")
|
|
return _failure(
|
|
500, "backup-failed", _maintenance.backup_failed_message(error)
|
|
)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library delete failed")
|
|
return _failure(500, "delete-failed", "The prompts could not be changed")
|
|
finally:
|
|
if backup is not None:
|
|
await self._prune_after_delete(db)
|
|
return web.json_response({"success": True, **result, "backup": backup})
|
|
|
|
async def _prune_after_delete(self, db):
|
|
try:
|
|
await self._run_in_executor(_prune_safety_backups, db.model.db_path)
|
|
except Exception: # pruning old copies never fails the delete
|
|
self.logger.exception("Could not prune old safety backups")
|
|
|
|
async def restore_library_prompts(self, request):
|
|
try:
|
|
data = await _body(request, _SELECTION_KEYS)
|
|
ids = parse_bulk_prompt_ids(data["prompt_ids"])
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
try:
|
|
async with self._jobs.lease("Library restore"):
|
|
result = await self._run_in_executor(
|
|
self.db.restore_library_prompts,
|
|
ids,
|
|
expected_epoch=data["expected_epoch"],
|
|
)
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library restore failed")
|
|
return _failure(500, "restore-failed", "The prompts could not be restored")
|
|
return web.json_response({"success": True, **result})
|