Files
ComfyAssets-ComfyUI_PromptM…/tests/browser/workspace_visual_fixture.py
T
Vito e9996996e2 feat(views): saved views and Favorites on Images and Library (#268)
* feat(views): saved-views store and API

Add a saved_views table (page images|library, trimmed 1-100 character
name, whitelisted JSON state of at most 4 KB, position, timestamps)
installed through the same validated-savepoint migration as image
favorites. It is optional in old backups and required in a migrated
restore stage; restore rejects a tampered definition, extra indexes and
any row that would fail write validation.

Routes under /prompt_manager/saved-views: GET lists views by position,
POST {page,name,state} returns 201 {success, view}, PATCH /{id} {name}
renames and DELETE /{id} removes, both 404 for an unknown id. The state
must hold exactly the page's toolbar and Refine-this-view keys (Images:
q, category, sort, source, folder, media, tags; Library: q, category,
sort, tags) with their types and sort/media values; anything else is a
400.

Refs #249

* feat(views): Save view, the SAVED VIEWS sidebar and opening a view

The shared toolbar gains the concept's Save view between sort and Filters
on Images and the Prompt library. It opens the concept's simpleInput
("Save this view", "View name", default "Search: <q>" or "My workspace
view", Cancel / Save); an empty name is "Saved view". A save posts the
page's full whitelisted state (toolbar value plus Refine filters) and
toasts "Saved view added to the sidebar.".

The shell adds the concept's SAVED VIEWS label and nav#saved-nav, loaded
with the shell and re-read after every save. Rows use the concept's
links() markup (search icon, name, no count) and link #/saved/<id>.
Opening one mounts its page with the saved state through the page's own
filters, so the toolbar and "Filters · N" (D44) show it; the h1,
breadcrumb and title are the view's name. A removed Source or Folder is
dropped to its default after discovery, so no listing read is rejected;
an unknown id re-reads the list once, then opens Images; a failed list
read offers Retry.

D16 is retired: images-concept and library-concept no longer map Save
view out. New deviations: D49 (no PROPOSED badge) and D50 (no Needs
review row); shell-concept maps Favorites out until Task 3 and compares
a saved row against the concept's. Browser fixtures now wipe
saved_views.

* feat(views): Edit rename/delete and the Favorites saved view

- Favorites is the first SAVED VIEWS row (star icon, name, real count).
  The count is the Favorites listing's own limit=1 total, follows the
  nav-count rules and is re-read after every confirmed star or unstar.
- #/favorites opens Images filtered to favorites. The workspace listing
  takes favorites=1: each selected root's favorites are read through the
  image_favorites primary key and matched against the cached scan with the
  toggle's case folding; a failed read is an error, never an unfiltered
  page. The cursor scope includes the flag.
- Saved Images state gains a required favorites boolean, so Save view on
  Favorites reopens the favorites.
- An open saved view's heading leads with Edit: "Edit saved view" with
  View name, Delete... (danger), Cancel and Save. Delete... confirms in the
  same dialog (never window.confirm). Toasts "Saved view renamed." and
  "Saved view deleted."; a delete returns to the view's plain page.
- shell-concept no longer maps Favorites out (Needs review stays, D50).
  Recorded as D51 in TESTING.md.

* fix(views): open stale saved views safely and finish the review fixes

Startup and restore now check only the saved_views structure (table,
columns, types, sizes, a JSON object state) and never the value rules,
so a row saved under older rules no longer stops the database from
opening. Reads normalize each view: missing keys take their defaults,
unknown keys are dropped, invalid values default and the name is made
displayable. POST and PATCH still validate strictly.

Only request validation (SavedViewInvalid) maps to 400; database and
internal errors are a logged generic 500. A saved view no longer
replaces the plain Images or Library return state, a toolbar change
while sources load keeps a saved Source and Folder, a state over 4 KB
is refused in the browser with its own toast, the delete confirmation
skips its failure toast after the page is gone, the Edit dialog reuses
the shared field helper, and quick star toggles coalesce into one
Favorites count read.

* test(views): cover leaving a pending saved view and add its coverage floor

A saved view left while the list or a rename is still pending leaves
the next page alone; the shell drops two unreachable heading guards.
workspace/saved-views.mjs gets its frontend coverage baseline entry;
no existing floor changes.

* fix(views): a corrupt saved-view state no longer blocks startup

At startup a saved_views row whose state is not a JSON object is
logged as a warning by id only and left in place. The listing and
rename skip it, so its #/saved/<id> link behaves like a missing view.
Restore stays strict and still rejects a backup holding such a row.
2026-10-21 09:10:18 -07:00

164 lines
5.6 KiB
Python

"""Deterministic original artwork and saved prompts for workspace visual checks."""
from __future__ import annotations
import json
import os
from pathlib import Path
import shutil
from typing import TYPE_CHECKING
from PIL import Image, ImageDraw
from PIL.PngImagePlugin import PngInfo
from utils.hashing import generate_prompt_hash
if TYPE_CHECKING:
from py.api import PromptManagerAPI
_POSITIVES = (
(
"Amber geometry\nLayered sandstone arches, warm afternoon light, "
"precise silhouettes."
),
(
"Tidal observatory\nCobalt circles over a quiet sea, "
"a pale horizon and measured reflections."
),
(
"Forest atlas\nOverlapping emerald triangles, paper textures "
"and a soft misty background."
),
(
"Rose pavilion\nCoral blocks and floating windows, "
"balanced shadows on a terracotta plaza."
),
"Violet orbit\nConcentric rings, lavender haze and a tiny silver moon.",
"A study in very long creative context\n"
+ "Preserve every geometric detail, layered color relationship and quiet edge. "
* 18
+ "unbroken-"
+ "context" * 40,
)
_NEGATIVES = (
("blurred edges, watermark", "flat lighting, clipped highlights", ""),
("low contrast, noise", "distorted horizon"),
("oversaturated foliage", "soft geometry"),
("unbalanced composition",),
("banding, harsh gradients",),
("cropped details, illegible marks",),
)
def _write_art(path: Path, index: int, positive: str, negative: str) -> None:
sizes = ((720, 480), (480, 720), (560, 560), (900, 400))
palettes = (
("#252c46", "#e0a75e", "#b76445"),
("#153b57", "#64bfc6", "#dfdba8"),
("#1d4947", "#71ac83", "#d5d8aa"),
("#523547", "#ef9c87", "#bc6764"),
("#342b59", "#a79bd6", "#e5c0bf"),
("#303d4d", "#b1c4c5", "#d6a05f"),
)
width, height = sizes[index % len(sizes)]
background, accent, highlight = palettes[index // 4]
graph = {
"1": {"class_type": "CLIPTextEncode", "inputs": {"text": positive}},
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": negative}},
"3": {
"class_type": "KSampler",
"inputs": {"positive": ["1", 0], "negative": ["2", 0]},
},
"4": {"class_type": "SaveImage", "inputs": {"images": ["3", 0]}},
}
info = PngInfo()
info.add_text("prompt", json.dumps(graph))
path.parent.mkdir(parents=True, exist_ok=True)
with Image.new("RGB", (width, height), background) as image:
draw = ImageDraw.Draw(image)
draw.rectangle((0, height * 3 // 4, width, height), fill=highlight)
radius = min(width, height) // 3
center_x, center_y = width // 2 + (index % 3 - 1) * 25, height // 2
draw.ellipse(
(
center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius,
),
fill=accent,
)
draw.polygon(
(
(width // 8, height * 7 // 8),
(width // 2, height // 4),
(width * 7 // 8, height * 7 // 8),
),
outline=highlight,
width=8,
)
draw.line(
(width // 6, height // 3, width * 5 // 6, height // 3),
fill=highlight,
width=4,
)
image.save(path, pnginfo=info)
stamp = 1_760_000_000 - index * 60
os.utime(path, (stamp, stamp))
def seed_workspace_visual(api: PromptManagerAPI, root: Path) -> None:
"""Replace only the owned browser harness records and media roots."""
with api.db.model.get_connection() as conn:
for table in (
"saved_views",
"image_favorites",
"image_prompt_pairs",
"prompt_pair_tags",
"prompt_pairs",
"generated_images",
"prompt_tags",
"tags",
"prompts",
):
conn.execute(f"DELETE FROM {table}")
for name in ("output", "input"):
shutil.rmtree(root / name)
(root / name).mkdir()
for parent_index, (positive, negatives) in enumerate(zip(_POSITIVES, _NEGATIVES)):
category = ("Architecture", "Landscape", "Abstract")[parent_index % 3]
tags = ["geometric", ("warm", "cool")[parent_index % 2]]
if parent_index == 5:
tags.append("long-context-" + "detail" * 28)
prompt_id = api.db.save_prompt(
positive,
category=category,
tags=tags,
prompt_hash=generate_prompt_hash(positive),
rating=parent_index if parent_index else None,
)
for variant_index, negative in enumerate(negatives):
api.db.save_prompt_pair(
positive,
negative,
title=f"Composition {variant_index + 1}",
category=category,
tags=tags,
)
for offset in range(4):
index = parent_index * 4 + offset
directory = ("output", "input")[offset % 2]
filename = f"study-{index + 1:02}.png"
if index == 23:
filename = (
"a-very-long-geometric-composition-"
+ "layered-context-" * 9
+ ".png"
)
path = root / directory / category.lower() / filename
_write_art(path, index, positive, negatives[offset % len(negatives)])
api.db.link_image_to_prompt(prompt_id, str(path))
api._generate_gallery_thumbnails_sync(api._get_all_output_dirs(), (150, 150))
api.invalidate_gallery_cache()