Files
ComfyAssets-ComfyUI_PromptM…/web/js/workspace/system-maintenance.mjs
T
Vito 9ab25f9aaa feat(system): Maintenance UI (System S7) (#322)
* fix(gallery): clear only Prompt Manager cache entries (#222)

The legacy gallery's Clear cache deleted every localStorage key starting
pm_ or promptManager_ (the workspace theme and the dismissed update notice
among them) and every CacheStorage cache whose name held gallery or
thumbnail, which on ComfyUI's shared origin can belong to another tool.

web/js/cache-ownership.js names what a clear may remove from an inventory
of the real writers: every key Prompt Manager writes is a preference and no
page opens CacheStorage or IndexedDB, so nothing is removed and the toast
says so. A test fails when a new storage writer is not classified. The
server thumbnail clear stays its own request; a refused or unreachable
server changes nothing and is reported, and refused browser storage is
reported as such.

* feat(system): run reviewed maintenance natively

System › Maintenance is native: the concept's notice and its Database and
Images & cache surfaces replace the hand-off.

- Integrity & relationship checks runs the health check; the report's
  Review missing links reviews a fresh Missing-file links plan.
- Review plan shows the server's read-only plan (D100): scope, protected,
  backup policy and media lines, the listed records, how long the review
  holds and the backup box; Apply reviewed operation sends only its token
  and opens the job in Activity. busy names the running job, plan-used links
  the job that applied it, an expired or replaced review is reviewed again,
  and a lost answer says Outcome not confirmed and points to Activity.
- Find duplicates starts the search; its view offers Review groups (D101):
  ten groups at a time, Keep radios per copy, each keeper sent as
  {group_id, root_index, path}; the dialog says History keeps the removed
  paths in its run records.
- Thumbnail cache opens the thumbnail dialog; Metadata cache is disabled
  with its reason while nothing is owned (D102, Q5).
- Activity descriptors for maintenance, duplicates and duplicate_cleanup.
- The legacy duplicates dialog's View Full names its source (?root=).

* test(system): compare Maintenance with the concept

system-maintenance-concept.spec compares System › Maintenance, the plan
dialog of each operation and the duplicates dialog with the concept in both
themes and both viewports, mapped only by D100–D102, and proves a mutated
row, label, danger mark or token is noticed. The duplicates dialog's Review
duplicate cleanup is the concept's plain button.

* test(system): Maintenance no longer hands off; raise coverage floors

The System shell test expected Maintenance's D94 hand-off; the section is
native now. coverage:update sets the new modules' floors from the
measured run (cache-ownership 94, maintenance-review 94,
system-maintenance 92 lines) and raises the floors other files passed.

* test(admin): close the preview worker after the last job in teardown

A scan publishes its last event, which ends the stream the test reads,
before it hands its missing previews to the automatic worker. That
hand-off can run after tearDownAsync closed the worker, so it starts a new
one whose .part files were still open when the final drain checked for
open handles (py3.10 on ubuntu, test_scan_reads_metadata_on_several_threads).
The drain now closes the worker for good once every job has ended.

* fix(system): address the S7 final review

- I1: an apply answer is a refusal only when our server sent it (a known
  code, or a 4xx whose body says success:false); a proxy's 5xx, an
  unreadable 2xx or a dropped connection says Outcome not confirmed and
  reads Activity again. ApiError gains 'refused'; the server's own
  pre-start failure is coded 'apply-failed'.
- M1: the lost-response test lets the apply run, then drops its answer.
- M2: a failed apply records its code in the job's scope; Activity offers
  Review again for an overtaken plan (Maintenance for a duplicate cleanup
  whose sources changed).
- M3: a failed duplicate cleanup toasts the server's reason.
- M4: a review button holds while its preview is read (one preview per
  double press).
- M5: the storage guard also catches bracket and property assignment and
  CacheStorage/IndexedDB opens; why the Toolkit build is skipped is
  written down.
- M6: a refused storage listing says so on the Metadata cache row.
- M7, M8: D100 text corrected; workflow_storage has its title.
- M9: a busy start names the job the server named.

* test: follow #319 in the Maintenance tests

- The thumbnail dialog has only Scope since #319.
- The admin teardown refuses new preview workers on its own API instead
  of closing with final=True, which since #319 also shuts the process-wide
  encoders that later test modules use.

* fix(system): keep the server's search-again line on a duplicate review

A duplicate cleanup review the server refuses with 409 sources-changed
showed the generic "could not be reviewed" message; it now shows the
server's "The sources changed since the search. Search for duplicates
again."

* fix(system): a plan with nothing to do offers only Close

A reviewed maintenance plan whose scope is 0 records ("No duplicate
prompt text") offered Apply reviewed operation, which started an empty
job. It now shows its rows, "There is nothing to apply; nothing was
changed." and a Close button.

* fix(system): wrap long copy paths in the duplicates review

A Keep label is the copy's source and path, and dataset folders often have
long names with no space to break at, so the review scrolled sideways.
The label now wraps anywhere inside its compare item (D101).
2026-10-25 05:51:57 -07:00

162 lines
9.0 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.
/**
* System › Maintenance (#249 System S7 Task 19): the concept's `renderSystem` "maintenance" body (app.js 688–690).
*
* - 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.
* - 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 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.
* - 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
* aria-disabled; with owned entries it reviews and clears exactly those.
*/
import '../cache-ownership.js';
import { navigateTo } from './state.mjs';
import { showWorkspaceToast } from './toast.mjs';
import { operationRow } from './system-controls.mjs';
import { healthNotice, runHealthAction } from './system-overview.mjs';
import { openThumbnailReview } from './thumbnail-review.mjs';
import { busyToast } from './activity-scan.mjs';
import { openReviewDialog } from './workspace-dialogs.mjs';
import { reviewPlan } from './maintenance-review.mjs';
import { noun } from './plural.mjs';
export const DUPLICATES_KIND = 'duplicates';
export const FIND_FAILED = 'The duplicate 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.';
/** The concept's two surfaces and their rows: `[title, description, label, action, danger]`. */
export const MAINTENANCE_SURFACES = Object.freeze([
['Database', [
['Integrity & relationship checks', 'Validate foreign keys, text hashes, pair uniqueness and image associations.', 'Check', 'health'],
['Duplicate prompt text', 'Review canonical text reuse and dependency-safe merging.', 'Review plan', 'duplicate_prompts'],
['Optimize database', 'Reclaim unused SQLite space. This does not delete prompts or media.', 'Review plan', 'optimize'],
['Unused prompt components', 'Preview unreferenced components. Pair references and history remain protected.', 'Review plan',
'unused_components', true],
]],
['Images & cache', [
['Missing-file links', 'Remove stale database links only. Files on disk are never deleted by this operation.', 'Review plan',
'missing_links', true],
['Duplicate image files', 'Find matching file content, review groups and choose what to keep. Separate from duplicate prompt text.',
'Find duplicates', 'duplicates'],
['Thumbnail cache', 'Generate missing thumbnails or explicitly rebuild all.', 'Review options', 'thumbnails'],
['Metadata cache', METADATA_CACHE_DESCRIPTION, 'Review plan', 'metadata_cache'],
]],
]);
function el(tag, text, className) {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (className) node.className = className;
return node;
}
const ownership = () => window.CacheOwnership;
const browserStorage = () => window.localStorage;
const cacheStorage = () => ('caches' in window ? window.caches : null);
/** 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(DUPLICATES_KIND);
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(FIND_FAILED);
}
}
/**
* D102: the Metadata cache row's description: the concept's, plus the reason its review is unavailable. A browser that
* refused to list its storage is never claimed empty.
*/
export function metadataCacheDescription(entries) {
if (entries.keys.length + entries.caches.length > 0) return METADATA_CACHE_DESCRIPTION;
return `${METADATA_CACHE_DESCRIPTION} ${entries.denied ? STORAGE_UNCHECKED_REASON : NOTHING_CACHED_REASON}`;
}
/** D102: review the owned browser entries, then clear exactly those and say what happened. */
export function openMetadataCacheReview({ scope, entries, trigger = null, notify = showWorkspaceToast,
cache = ownership(), onCleared = () => {} }) {
const count = entries.keys.length + entries.caches.length;
openReviewDialog({ scope, trigger, title: 'Review maintenance plan', heading: 'Metadata cache',
grid: [['Scope', `${count.toLocaleString('en-US')} cached ${noun(count, 'entry', 'entries')} in this browser`],
['Protected', 'Preferences and other tools’ data in this browser'],
['Backup', 'Not needed: the database is not changed'],
['Media on disk', 'No files are removed']],
sentence: [...entries.keys, ...entries.caches].join(' · '),
cancelLabel: 'Cancel', primary: { label: 'Clear browser cache' },
onStart: async () => {
const result = await cache.clearOwned({ storage: browserStorage, cacheStorage: cacheStorage() });
if (scope.signal.aborted) return;
notify(cache.clearMessage(result));
onCleared();
} });
}
/** The Metadata cache row: aria-disabled with its reason while nothing is owned (D102). */
function metadataCacheRow({ scope, notify, cache }) {
const row = operationRow({ scope, title: 'Metadata cache', description: METADATA_CACHE_DESCRIPTION, label: 'Review plan',
onClick: async button => {
if (button.getAttribute('aria-disabled') === 'true') return;
const entries = await cache.ownedEntries({ storage: browserStorage, cacheStorage: cacheStorage() });
if (scope.signal.aborted) return;
if (entries.keys.length + entries.caches.length === 0) {
paint(entries);
return;
}
openMetadataCacheReview({ scope, entries, trigger: button, notify, cache, onCleared: refresh });
} });
const button = row.querySelector('.row-actions > button');
const description = row.querySelector('p');
function paint(entries) {
description.textContent = metadataCacheDescription(entries);
if (entries.keys.length + entries.caches.length > 0) button.removeAttribute('aria-disabled');
else button.setAttribute('aria-disabled', 'true');
}
function refresh() {
cache.ownedEntries({ storage: browserStorage, cacheStorage: cacheStorage() }).then(entries => {
if (!scope.signal.aborted) paint(entries);
});
}
paint({ keys: [], caches: [] });
refresh();
return row;
}
/**
* The Maintenance section's mount (`mountSystem`'s `sections.maintenance`): the notice and the two surfaces. `activity`
* is the page's Activity store.
*/
export function mountMaintenance(container, { api, activity, scope, navigate = navigateTo, notify = showWorkspaceToast,
cache = ownership() }) {
const reviewMissing = (trigger, pressed = trigger) => reviewPlan({ api, store: activity, scope, operation: 'missing_links',
trigger, hold: pressed, notify, navigate });
const actions = {
health: button => runHealthAction({ api, activity, scope, button, onReviewMissing: reviewMissing, notify }),
duplicates: () => findDuplicates({ store: activity, scope, notify, navigate }),
thumbnails: button => openThumbnailReview({ api, store: activity, scope, trigger: button, navigate }),
};
const surfaces = MAINTENANCE_SURFACES.map(([heading, rows]) => {
const surface = el('section', undefined, 'surface');
surface.append(el('h2', heading), ...rows.map(([title, description, label, action, danger = false]) => {
if (action === 'metadata_cache') return metadataCacheRow({ scope, notify, cache });
const onClick = actions[action]
?? (button => reviewPlan({ api, store: activity, scope, operation: action, trigger: button, notify, navigate }));
return operationRow({ scope, title, description, label, danger, onClick });
}));
return surface;
});
return [healthNotice({ api, activity, scope, navigate, notify, onReviewMissing: reviewMissing }), ...surfaces];
}