* 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.
259 lines
13 KiB
JavaScript
259 lines
13 KiB
JavaScript
/**
|
||
* Where the library lives (#249 System S6b, D129): the workspace banner, System › Overview's "Library location" row,
|
||
* the Move library review and its start.
|
||
*
|
||
* - The server says where the database is and why (`GET /prompt_manager/system/library` and the Overview's
|
||
* `location`): `default` (ComfyUI's user folder), `environment` (PROMPT_MANAGER_DATA_DIR), `config`
|
||
* (config.json's database path) or `node_folder`, where an update or reinstall can delete it.
|
||
* - D129: while a node-folder library is not kept there, the shell shows the concept's `.notice` (`h2` + `p` +
|
||
* `.row-actions`) above every page: "Keep it here" saves the choice on the server (the banner stops; the Overview row
|
||
* stays), "Move library" opens the review. The concept has no such notice; its markup and classes are the Sources
|
||
* notice's (app.js 680).
|
||
* - The review is the shared record-changing review (`openReviewDialog`): From, To, Size, what moves with it and what
|
||
* happens to the old files. Move library starts the server's exclusive "Move library" job, tracks it in Activity and
|
||
* opens its view; a refusal (another job running, no room, a library already there) says why and nothing starts.
|
||
* - When a Move library job ends, the banner and the Overview read the location again.
|
||
*/
|
||
import { createButton } from '../shared/toolkit/core.js';
|
||
import { busyToast } from './activity-scan.mjs';
|
||
import { closeWorkspaceDialog, openContentDialog, openReviewDialog } from './workspace-dialogs.mjs';
|
||
import { navigateTo } from './state.mjs';
|
||
import { showWorkspaceToast } from './toast.mjs';
|
||
|
||
export const LIBRARY_URL = '/prompt_manager/system/library';
|
||
export const MOVE_URL = `${LIBRARY_URL}/move`;
|
||
export const KEEP_URL = `${LIBRARY_URL}/keep`;
|
||
export const MOVE_KIND = 'library_move';
|
||
|
||
export const BANNER_TITLE = 'Your library is inside the node folder';
|
||
const BANNER_LEAD = 'Your library is stored inside the node folder, where an update or reinstall can delete it.';
|
||
/** Where Move library puts it, by the server's `target_source`. */
|
||
export const TARGET_TEXT = Object.freeze({
|
||
default: 'ComfyUI\'s user folder',
|
||
environment: 'the folder PROMPT_MANAGER_DATA_DIR names',
|
||
});
|
||
/** The notice's sentence: it names the actual target. */
|
||
export function bannerText(location) {
|
||
const target = TARGET_TEXT[location?.target_source] ?? TARGET_TEXT.default;
|
||
return `${BANNER_LEAD} Move it to ${target}: it is copied and verified first, and nothing is deleted.`;
|
||
}
|
||
export const BANNER_TEXT = bannerText({ target_source: 'default' });
|
||
export const KEEP_LABEL = 'Keep it here';
|
||
export const MOVE_LABEL = 'Move library';
|
||
export const ROW_TITLE = 'Library location';
|
||
export const START_FAILED = 'Move library could not start. Try again.';
|
||
export const KEEP_FAILED = 'Your choice could not be saved. Try again.';
|
||
|
||
/** Why the library is where it is, by `source`. */
|
||
export const SOURCE_TEXT = Object.freeze({
|
||
default: 'ComfyUI\'s user folder, which updates and reinstalls of the node leave alone',
|
||
environment: 'The folder PROMPT_MANAGER_DATA_DIR names',
|
||
config: 'The database path set in config.json',
|
||
node_folder: 'The node folder, where an update or reinstall can delete it',
|
||
});
|
||
|
||
/** A `problem` code as a sentence. */
|
||
export const PROBLEM_TEXT = Object.freeze({
|
||
'data-dir-not-absolute': 'PROMPT_MANAGER_DATA_DIR is not an absolute folder, so it was ignored.',
|
||
'data-dir-served': 'PROMPT_MANAGER_DATA_DIR names a folder whose files are served over the web, so it was ignored.',
|
||
'data-dir-empty': 'PROMPT_MANAGER_DATA_DIR has no library yet; Move library puts this one there.',
|
||
'move-unfinished': 'An earlier move did not finish; this library is still the one in use.',
|
||
'inside-node-folder': 'It is inside the node folder, where an update or reinstall deletes it, config.json and its '
|
||
+ 'CivitAI key included. Set database.default_path or PROMPT_MANAGER_DATA_DIR to a folder outside it.',
|
||
});
|
||
|
||
const number = value => Number(value).toLocaleString('en-US');
|
||
|
||
/** "1.6 GB" or "120.0 MB" or "512 KB". */
|
||
export function sizeText(bytes) {
|
||
if (!Number.isFinite(bytes) || bytes < 0) return 'Unknown';
|
||
if (bytes >= 2 ** 30) return `${(bytes / 2 ** 30).toLocaleString('en-US', { maximumFractionDigits: 1, minimumFractionDigits: 1 })} GB`;
|
||
if (bytes >= 2 ** 20) return `${(bytes / 2 ** 20).toLocaleString('en-US', { maximumFractionDigits: 1, minimumFractionDigits: 1 })} MB`;
|
||
return `${number(Math.ceil(bytes / 1024))} KB`;
|
||
}
|
||
|
||
/** Whether `location` is a well-formed server answer. */
|
||
export function isLocation(location) {
|
||
return Boolean(location) && typeof location === 'object' && typeof location.path === 'string'
|
||
&& Object.hasOwn(SOURCE_TEXT, location.source) && typeof location.movable === 'boolean';
|
||
}
|
||
|
||
/** The Overview row's description: the path, why it is there, the user's choice and any problem. */
|
||
export function locationDescription(location) {
|
||
const parts = [`${location.path} · ${SOURCE_TEXT[location.source]}.`];
|
||
if (location.movable && location.keep) parts.push('You chose to keep it here.');
|
||
const problem = PROBLEM_TEXT[location.problem];
|
||
if (problem) parts.push(problem);
|
||
return parts.join(' ');
|
||
}
|
||
|
||
/** The review's `[term, value]` rows. */
|
||
export function reviewGrid(location) {
|
||
return [
|
||
['From', location.path],
|
||
['To', `${location.target}/prompts.db`],
|
||
['Size', sizeText(location.size_bytes)],
|
||
['Moves with it', location.config_moves === false
|
||
? 'The database backups (config.json stays where PROMPT_MANAGER_CONFIG_PATH names it)'
|
||
: 'config.json and the database backups'],
|
||
['Old files', 'Renamed *.moved-to-…, never deleted'],
|
||
// #320 D201: previews kept in one folder do not move with the library (D8A).
|
||
...(typeof location.thumbnails_folder === 'string' && location.thumbnails_folder
|
||
? [['Thumbnails', `Stay in ${location.thumbnails_folder}. Move them in System › Sources & scans.`]] : []),
|
||
];
|
||
}
|
||
|
||
export const REVIEW_SENTENCE = 'The copy is verified before Prompt Manager switches to it. No other job can run until it '
|
||
+ 'finishes, and closing this page does not stop it.';
|
||
|
||
function el(tag, text, className) {
|
||
const node = document.createElement(tag);
|
||
if (text !== undefined) node.textContent = text;
|
||
if (className) node.className = className;
|
||
return node;
|
||
}
|
||
|
||
/**
|
||
* Start the Move library job, follow it in Activity and open its view. A busy server toasts the D57 link to the running
|
||
* job; any other refusal says the server's reason. Nothing is said once `scope` ended.
|
||
*/
|
||
export async function startLibraryMove({ api, activity, scope, notify = showWorkspaceToast, navigate = navigateTo }) {
|
||
try {
|
||
const { job } = await api.post(MOVE_URL, {}, { signal: scope.signal });
|
||
if (scope.signal.aborted) return null;
|
||
const tracked = activity.track(job);
|
||
navigate(`#/activity/${tracked.id}`);
|
||
return tracked;
|
||
} catch (error) {
|
||
if (scope.signal.aborted) return null;
|
||
if (error?.status === 409 && error?.code === 'busy') {
|
||
await activity.load();
|
||
if (!scope.signal.aborted) notify(busyToast(activity.running()[0] ?? null));
|
||
return null;
|
||
}
|
||
notify(typeof error?.code === 'string' && error.message ? error.message : START_FAILED);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** The Move library review over `location`; Move library starts the job. */
|
||
export function openMoveReview({ api, activity, scope, location, trigger = null, notify = showWorkspaceToast,
|
||
navigate = navigateTo }) {
|
||
return openReviewDialog({ scope, trigger, title: 'Move library', grid: reviewGrid(location), sentence: REVIEW_SENTENCE,
|
||
cancelLabel: 'Cancel', primary: { label: MOVE_LABEL },
|
||
onStart: () => { startLibraryMove({ api, activity, scope, notify, navigate }); } });
|
||
}
|
||
|
||
/** Save "Keep it here" (`keep` true) or take it back; resolves the new location, or null when it was not saved. */
|
||
export async function keepLibrary({ api, scope, keep = true, notify = showWorkspaceToast }) {
|
||
try {
|
||
const { location } = await api.post(KEEP_URL, { keep }, { signal: scope.signal });
|
||
return isLocation(location) ? location : null;
|
||
} catch (error) {
|
||
if (!scope.signal.aborted) notify(KEEP_FAILED);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** The details of a library that does not move: where it is, why, and what lives beside it. */
|
||
export function openLocationDetails({ scope, location, trigger = null }) {
|
||
const list = el('dl', undefined, 'meta-grid');
|
||
for (const [term, value] of [['Database', location.path], ['Why here', SOURCE_TEXT[location.source]],
|
||
['Beside it', 'config.json, the database backups and the logs'], ['Size', sizeText(location.size_bytes)]]) {
|
||
const entry = el('div');
|
||
entry.append(el('dt', term), el('dd', value));
|
||
list.append(entry);
|
||
}
|
||
const close = createButton('Close');
|
||
scope.listen(close, 'click', () => closeWorkspaceDialog());
|
||
const actions = el('div', undefined, 'dialog-actions');
|
||
actions.append(close);
|
||
const nodes = [list];
|
||
const problem = PROBLEM_TEXT[location.problem];
|
||
if (problem) nodes.push(el('p', problem, 'small'));
|
||
nodes.push(actions);
|
||
openContentDialog({ scope, title: ROW_TITLE, trigger, nodes });
|
||
}
|
||
|
||
/** D129: the Overview's "Library location" `.operation` row; Move library when it can move, else Details. */
|
||
export function locationRow(location, { api, activity, scope, notify = showWorkspaceToast, navigate = navigateTo }) {
|
||
const row = el('div', undefined, 'operation');
|
||
const text = el('div');
|
||
text.append(el('h3', ROW_TITLE), el('p', locationDescription(location)));
|
||
const actions = el('div', undefined, 'row-actions');
|
||
const action = createButton(location.movable ? MOVE_LABEL : 'Details');
|
||
scope.listen(action, 'click', () => {
|
||
if (location.movable) openMoveReview({ api, activity, scope, location, trigger: action, notify, navigate });
|
||
else openLocationDetails({ scope, location, trigger: action });
|
||
});
|
||
actions.append(action);
|
||
row.append(text, actions);
|
||
return row;
|
||
}
|
||
|
||
/** D129: the concept's `.notice` for a node-folder library: Keep it here and Move library. */
|
||
export function libraryNotice({ scope, location = null, onKeep, onMove }) {
|
||
const notice = el('div', undefined, 'notice');
|
||
const text = el('div');
|
||
text.append(el('h2', BANNER_TITLE), el('p', bannerText(location)));
|
||
const keep = createButton(KEEP_LABEL);
|
||
const move = createButton(MOVE_LABEL, 'ca-primary');
|
||
scope.listen(keep, 'click', () => onKeep(keep));
|
||
scope.listen(move, 'click', () => onMove(move));
|
||
const actions = el('div', undefined, 'row-actions');
|
||
actions.append(keep, move);
|
||
notice.append(text, actions);
|
||
return notice;
|
||
}
|
||
|
||
/** Calls `onEnded()` whenever a Move library job this page sees stops running. Returns the unsubscribe. */
|
||
export function onMoveEnded(activity, onEnded) {
|
||
const running = new Set();
|
||
return activity.subscribe(() => {
|
||
let ended = false;
|
||
for (const job of activity.jobs()) {
|
||
if (job.kind !== MOVE_KIND) continue;
|
||
if (job.state === 'running') running.add(job.id);
|
||
else if (running.delete(job.id)) ended = true;
|
||
}
|
||
if (ended) onEnded();
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Mount the banner in `container` (hidden until the server offers the move). It reads the location once, again when a
|
||
* Move library job ends, and hides for good this page once the user keeps the library where it is.
|
||
*/
|
||
export function mountLibraryBanner(container, { api, activity, scope, notify = showWorkspaceToast, navigate = navigateTo,
|
||
latestOnly = window.ApiClient.latestOnly, STALE = window.ApiClient.STALE }) {
|
||
const read = latestOnly({ lifetime: scope.signal });
|
||
const show = location => {
|
||
container.replaceChildren();
|
||
container.hidden = !(isLocation(location) && location.offer === true);
|
||
if (container.hidden) return;
|
||
container.append(libraryNotice({ scope, location,
|
||
onKeep: async button => {
|
||
button.setAttribute('aria-disabled', 'true');
|
||
const saved = await keepLibrary({ api, scope, notify });
|
||
if (scope.signal.aborted) return;
|
||
button.removeAttribute('aria-disabled');
|
||
if (saved) show(saved);
|
||
},
|
||
onMove: button => openMoveReview({ api, activity, scope, location, trigger: button, notify, navigate }) }));
|
||
};
|
||
async function load() {
|
||
try {
|
||
const answer = await read(signal => api.get(LIBRARY_URL, { signal, cache: 'no-store' }));
|
||
if (answer === STALE || scope.signal.aborted) return;
|
||
show(answer.location);
|
||
} catch {
|
||
// The banner is advisory: an unreadable location shows nothing (the Overview row reports it).
|
||
if (!scope.signal.aborted) show(null);
|
||
}
|
||
}
|
||
container.hidden = true;
|
||
scope.cleanup(onMoveEnded(activity, load));
|
||
load();
|
||
return { reload: load };
|
||
}
|