Files
ComfyAssets-ComfyUI_PromptM…/web/js/workspace/thumbnail-review.mjs
T
Vito 043403d09e feat(thumbnails): choose where thumbnails are kept and move them (#320) (#592)
* refactor(thumbnails): one resolver for where previews live on disk (#320)

Add py/api/preview_store.py: the store of a source, a preview's path,
URL parts to disk, containment (owns), a write generation and the lock
around every preview's final rename. Every preview reader, writer and
remover now asks it instead of joining <source>/thumbnails by hand:
serve, on-demand, capture (its path resolved when the write starts),
the after-scan queue, the thumbnail plans and job payloads, clear, the
temp sweep, History covers, the auto-tag listing and the owned-preview
lookups.

Source mode only: every path is the one built before, so nothing
changes on disk or on the wire. A structural test keeps new
thumbnails joins out of the backend.

* refactor(thumbnails): keep the after-scan queue's store rule and pin the write lock (#320)

A planned target keeps the plan's own containment rule (inside the
store, as the thumbnail job writes it); captures keep the serve rule.
The structural test also covers PREVIEW_FOLDER joins and the
repo-root modules; the write-lock test asserts the lock instead of
waiting on a timer; new tests cover nested roots in the after-scan
queue and a legacy upper-case preview served through the resolver.

* feat(thumbnails): keep previews in one folder, set from config.json (#320)

thumbnails.location in config.json can now name one folder for every
source's previews: <folder>/<source key>/<rel>_thumb<ext>. A source key is
a readable slug plus a short hash of the source's identity, stored in the
folder's marker (.promptmanager-thumbnails.json) with the install that
made it. Serving, on-demand and capture writes, listings, clear, delete,
duplicates, the temp sweep and History covers all follow it; a leftover in
<source>/thumbnails is never served and other text under thumbnails/ is
refused.

A missing, unplugged or foreign folder is unavailable (a probe checks it
every 5 s within 2 s; a stalled or failing store call flips it at once):
originals are served, nothing is written anywhere, the folder is never
re-created, and generate, convert and clear answer 409
location-unavailable. A bad config value is unavailable too, never a
fall-back to the sources.

No UI yet: POST /settings refuses thumbnail_location (409
location-needs-move); GET /settings reports it with its path, the
thumbnail status without one. Sources inside or around the folder and a
library move into it are refused.

* fix(thumbnails): never follow a marker or a link out of the thumbnail folder (#320)

Marker keys are data, not paths: only a single <slug>-<hex> folder name
is ever joined onto the thumbnail folder; anything else is dropped and
logged. Every preview write and delete passes one ownership check (below a
key folder, lexically and resolved, no link, junction or reparse point on
the way); make_parent refuses anything else and writes nothing while the
folder lacks this install's marker (an unmounted mount point). Clear never
descends into a junction.

The configured location is in force before any request (unchecked folder
mode is unavailable), and a startup check that fails leaves it invalid,
never the sources. Older listings that run on the event loop no longer
touch the store in folder mode. A leftover under another case of
thumbnails/ on a case-insensitive disk is refused too.

* test(memory): let the musl test fake os.confstr on Windows (#523)

The portability run on main fails since #523: Windows has no
os.confstr, so patching it without create=True raises before the test
runs.

* feat(thumbnails): move thumbnails between the sources and one folder (#320)

POST /images/thumbnails/plan reviews a move (what is copied, removed and
left, free space, too-long Windows paths, sources no longer listed) and
hands out a token; POST /jobs/thumbnails {mode: move} runs it as a
thumbnails job: hold automatic previews, copy and check every preview on
the job pool, switch with one config commit that records the old copies,
then remove them. Per-file errors still switch; a folder-wide error, a
cancel before the switch or a crash leaves nothing changed (a journal is
undone at the next start); old copies that could not go are removed by a
finishing job at the next start. Leaving a folder removes the previews of
this install's sources that are no longer listed (Q320-8).

Recreate folder and Use this folder answer an unavailable folder; the
Thumbnail maintenance scope prune removes the thumbnails of removed
sources.

* feat(system): choose where thumbnails are kept and move them (#320)

System › Sources & scans gains the Thumbnail location row (D196): Inside
each source or One folder, the folder path, the status line and Review
move…, whose review (D197) lists what is copied, removed and left before
Move thumbnails starts; a refused folder is explained under the field, a
folder of your own asks for a confirmation first. Activity shows a move
and a prune with their own tiles and step line (D198). An unavailable
folder shows a notice on Overview and Sources & scans with Recreate folder
or Use this folder (D199). Thumbnail maintenance offers Remove thumbnails
of removed sources in folder mode (D200), and Move library's review says
where the thumbnails stay (D201).

Closes #320

* fix(thumbnails): keep a move's own previews and never walk out of a store (#320)

A cleanup that waited from an earlier move never names a key folder the
new move just filled, so moving back keeps the previews. Removing empty
folders walks top-down and never into a link or junction. Any error
while copying undoes the copies; once the switch is committed, a journal
that cannot be removed no longer undoes it. Hand-edited cleanup entries
and marker keys never name a folder outside the stores; removal stops at
interpreter exit. The path field carries aria-invalid with its reason,
and a review that went stale reviews again.

* test(thumbnails): cover the prune scope, the Overview notice and the space refusal (#320)

The frontend coverage gate counted the new branches of thumbnail
maintenance, the Activity views, the notices' Change location and the
api-client's space refusal as uncovered; page and unit tests now drive
them.

* fix(thumbnails): report removals that fail and explain the quiet excepts (#320)

An old thumbnail the finishing move cannot remove (held open on Windows)
is now an error row of the job with its path, and logged; a failed copy's
temp that cannot go is logged with its path. Every except that only
passes says why, and the thread runners say their caller re-raises.

* fix(thumbnails): never plan or delete through a linked key folder (#320)

Review finding P1 on #591: in folder mode a source key folder that is a
link or junction to a folder outside was still handed to the planner, so
Convert outdated could remove an older-format file outside the thumbnail
folder. ensure_store now refuses a linked store before any planning, and
each removal of an old preview passes may_write at the moment it runs.

* fix(thumbnails): the temp sweep never walks into a link (#320)

Review finding P2 on #591: Clear thumbnails and the startup sweep removed
crashed-write temps with a plain os.walk, which on Windows walks into a
junction even without followlinks. The sweeper now skips a folder that is
a link, junction or reparse point (the top one too), and each temp passes
may_write before it is removed.

* fix(thumbnails): lock the folder marker across processes (#320)

Review finding P2 on #591: two installs sharing one thumbnail folder could
each read the marker, add a key and replace it, so the last writer
dropped the other's key. write_marker now re-reads, changes and replaces
the marker under a lock file made with O_CREAT | O_EXCL beside it (atomic
on shares, unlike flock); a lock older than 30 s, left by a writer that
died, is taken over, and a wait past 1.5 s fails as a TimeoutError like
an unreachable folder. Tested with three processes adding keys at once.

* test(thumbnails): cover the space refusal, Overview's Use this folder and the prune review (#320)

The frontend coverage floors of activity-kinds, system-overview and
thumbnail-review: a disk without the space shows the review but cannot
move (a fixture route fakes the free space), Use this folder on Overview
reloads the host values, the prune review's text and rows are pure
functions with unit tests, and Overview takes the System drafts it is
always mounted with.

* fix(thumbnails): never copy through a linked folder; refuse a target inside the folder in use (#320)

Moving back to Inside each source followed an existing linked folder in the
destination and could replace a file outside the source (Codex P1). A target
nested inside the thumbnail folder in use was accepted, and the old-copy
cleanup then removed the previews just copied there (Codex P2).

Every copy now checks the whole destination chain for links, also when the
folders exist, and the move refuses a folder inside the one in use with
location-inside-current. The cancelled branches no longer mix explicit and
implicit returns (code-quality note).

* fix(system): one full stop in the move-back review (#320)

* fix(thumbnails): a folder check answers for the folder as it is now (#320)

Probe.check() joined a check already running, or a finished one nobody had
collected. A folder deleted right after configure() woke the probe therefore
stayed available until the next probe, which failed the Overview notice spec in
the merge queue. It now waits for a running check and starts a new one, still
never two at once, and a stuck check still times out. The spec also asserts the
fixture's removal took effect.
2026-11-01 13:11:13 +00:00

180 lines
9.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Thumbnail review (#249 System S5 Task 14): the concept's "Thumbnail maintenance" dialog (`thumbnail-review`, app.js
* 1433–1437), opened by Sources' "Thumbnail generation → Review options", Overview's "Review thumbnails" and
* Appearance's "Convert outdated" (#317). It starts the `thumbnails` Activity job (S5 Task 12) with the chosen scope.
*
* - Scope: "Missing thumbnails only" (`missing`, the default), "Rebuild all (explicit opt-in)" (`rebuild`) or, #317,
* "Convert outdated (removes older formats)" (`convert`): previews in another format than the configured one are
* written again from their originals and the old files removed. Nothing converts unless chosen here.
* - D131: the concept's Quality and Preview size limit fields are gone: previews follow the server's thumbnail
* settings (System › Appearance, #317), so a `p.small` line after the plan line names them from the plan's answer
* ("Previews are written as WebP · quality 80 · 512 px. …").
* - D99: a `p.small[role=status]` line before the actions says what the server's plan counts for the chosen scope
* (`GET /images/thumbnails/plan?mode=`, read-only): "N previews to generate · M already up to date.", for a rebuild
* "Every preview is regenerated: N files.", for a conversion "N previews in an older format to convert.". N counts
* the files past the per-batch cap too: the job plans again after each batch (#317). Each scope is read once per dialog. The primary is "Start" (the
* concept's "Simulate thumbnail job"): it closes the dialog and starts the job through the Activity store, which
* toasts that it started; the job opens in Activity, where its progress lives. A start refused because another job
* holds the slot toasts the D57 busy link toast and stays.
*/
import { createButton } from '../shared/toolkit/core.js';
import { closeWorkspaceDialog, field, openContentDialog } from './workspace-dialogs.mjs';
import { busyToast } from './activity-scan.mjs';
import { showWorkspaceToast } from './toast.mjs';
import { navigateTo } from './state.mjs';
import { noun } from './plural.mjs';
import { sizeText } from './system-thumbnail-location.mjs';
export const THUMBNAIL_PLAN_URL = '/prompt_manager/images/thumbnails/plan';
export const THUMBNAILS_KIND = 'thumbnails';
export const SCOPE_OPTIONS = Object.freeze([['missing', 'Missing thumbnails only'], ['rebuild', 'Rebuild all (explicit opt-in)'],
['convert', 'Convert outdated (removes older formats)']]);
export const PLAN_LOADING = 'Counting previews…';
export const PLAN_FAILED = 'The previews could not be counted.';
export const START_FAILED = 'Thumbnail generation could not start. Try again.';
export const SETTINGS_UNKNOWN = 'Previews follow the thumbnail settings in System › Appearance.';
const FORMAT_LABELS = Object.freeze({ webp: 'WebP', jxl: 'JPEG XL', jpeg: 'JPEG' });
// #320 D200: offered only while previews are kept in one folder (31A).
export const PRUNE_OPTION = Object.freeze(['prune', 'Remove thumbnails of removed sources']);
const MODES = new Set([...SCOPE_OPTIONS.map(([value]) => value), PRUNE_OPTION[0]]);
const count = value => value.toLocaleString('en-US');
const isCount = value => Number.isSafeInteger(value) && value >= 0;
/** D131: the server's thumbnail settings from the plan's `{format, quality, size}`. */
export function settingsText(plan) {
const label = FORMAT_LABELS[plan?.format];
if (!label || !isCount(plan.quality) || !isCount(plan.size)) return SETTINGS_UNKNOWN;
return `Previews are written as ${label} · quality ${plan.quality} · ${count(plan.size)} px. Change this in System › Appearance.`;
}
/** D200: what a prune removes, in `plan.folder` (the thumbnail folder). */
export function pruneText(plan) {
return `Only Prompt Manager’s thumbnails in their folders inside ${plan?.folder || 'the thumbnail folder'} are `
+ 'removed. If a source comes back, its thumbnails are made again as you browse.';
}
/** D200: one `[key, "N thumbnails · size"]` per removed source of a prune plan. */
export function pruneEntries(plan) {
const sources = Array.isArray(plan?.sources) ? plan.sources : [];
return sources.map(source => [source.key, `${count(source.files)} ${noun(source.files, 'thumbnail')} · `
+ `${sizeText(source.bytes)}`]);
}
/** D99: the plan line for the server's `{mode, targets, fresh, remaining}`; an answer without counts failed. */
export function planText(plan) {
if (plan?.mode === 'prune') return typeof plan.line === 'string' && plan.line ? plan.line : PLAN_FAILED;
if (!plan || !MODES.has(plan.mode) || ![plan.targets, plan.fresh, plan.remaining].every(isCount)) {
return PLAN_FAILED;
}
// #317: the cap bounds one batch, not the job, which plans again until nothing is left: the line counts it all.
const work = plan.targets + plan.remaining;
if (plan.mode === 'rebuild') return `Every preview is regenerated: ${count(work)} ${noun(work, 'file')}.`;
if (plan.mode === 'convert') {
if (!work) return 'No previews in an older format.';
return `${count(work)} ${noun(work, 'preview')} in an older format to convert.`;
}
return `${count(work)} ${noun(work, 'preview')} to generate · ${count(plan.fresh)} already up to date.`;
}
/**
* Start the thumbnail job with `options` (`{mode}`) and open its view; a refused or failed start says
* why and stays. Nothing is said once the section that started it is gone.
*/
export async function startThumbnails({ store, scope, options, notify = showWorkspaceToast, navigate = navigateTo }) {
try {
const result = await store.start(THUMBNAILS_KIND, options);
if (scope.signal.aborted) return;
if (result.busy !== undefined) {
notify(busyToast(result.busy));
return;
}
navigate(`#/activity/${result.job.id}`);
} catch {
if (!scope.signal.aborted) notify(START_FAILED);
}
}
function el(tag, text, className) {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (className) node.className = className;
return node;
}
function select(options, value) {
const node = el('select');
node.append(...options.map(([optionValue, label]) => {
const option = el('option', label);
option.value = optionValue;
return option;
}));
node.value = value;
return node;
}
/**
* Open "Thumbnail maintenance" on the section's `scope`, on scope `mode` (`missing` unless given). `store` is the page's
* Activity store; `trigger` gets focus back when the dialog closes.
*/
export function openThumbnailReview({ api, store, scope, trigger = null, mode: initial = 'missing', notify = showWorkspaceToast,
navigate = navigateTo, location = null }) {
const folderMode = location?.mode === 'folder';
const options = folderMode ? [...SCOPE_OPTIONS, PRUNE_OPTION] : SCOPE_OPTIONS;
const allowed = new Set(options.map(([value]) => value));
const mode = select(options, allowed.has(initial) ? initial : 'missing');
const line = el('p', PLAN_LOADING, 'small');
line.setAttribute('role', 'status');
const settings = el('p', SETTINGS_UNKNOWN, 'small');
// D200: what the prune removes, under the plan line.
const pruneDetail = el('p', '', 'small');
const pruneGrid = el('dl', undefined, 'meta-grid');
pruneDetail.hidden = pruneGrid.hidden = true;
const cancel = createButton('Cancel');
const start = createButton('Start', 'ca-primary');
const actions = el('div', undefined, 'dialog-actions');
actions.append(cancel, start);
// The plan per scope: a promise of its answer (null when it failed).
const plans = new Map();
let open = true;
const readPlan = chosen => api.get(`${THUMBNAIL_PLAN_URL}?${new URLSearchParams({ mode: chosen })}`,
{ signal: scope.signal, cache: 'no-store' }).catch(() => null);
async function paint() {
const chosen = mode.value;
if (!plans.has(chosen)) plans.set(chosen, readPlan(chosen));
const pending = plans.get(chosen);
line.textContent = PLAN_LOADING;
const plan = await pending;
// A later choice painted its own line meanwhile, or the dialog closed.
if (!open || scope.signal.aborted || mode.value !== chosen) return;
line.textContent = planText(plan);
const prune = chosen === 'prune';
settings.hidden = prune;
const entries = pruneEntries(plan);
pruneDetail.hidden = pruneGrid.hidden = !prune || !entries.length;
if (prune) {
pruneDetail.textContent = pruneText(plan);
pruneGrid.replaceChildren(...entries.map(([key, text]) => {
const entry = el('div');
entry.append(el('dt', key), el('dd', text));
return entry;
}));
} else {
settings.textContent = settingsText(plan);
}
}
scope.listen(mode, 'change', paint);
scope.listen(cancel, 'click', () => closeWorkspaceDialog());
scope.listen(start, 'click', () => {
const options = { mode: mode.value };
closeWorkspaceDialog();
startThumbnails({ store, scope, options, notify, navigate });
});
openContentDialog({ scope, title: 'Thumbnail maintenance', trigger,
nodes: [field('Scope', mode, 'thumb-mode'), line, settings, ...(folderMode ? [pruneDetail, pruneGrid] : []), actions],
onClose: () => { open = false; } });
paint();
}