* feat(review): add review queue schema with restore validation
Add the Needs review schema group (media_review_metadata,
media_review_items, media_review_decisions) beside the image annotation
group it cites. review_schema_error validates the catalog, columns,
foreign keys, row values and canonical 8 MiB evidence read-only;
migrate_review_state installs it in a SAVEPOINT after the annotation
group, and verify_database_file requires it under require_library_state.
A review group without a valid annotation group is refused. Decisions
null their pair and image navigation through indexes when those are
deleted. Old backups and annotation-era backups restore and gain the
group; browser fixtures clear the new tables on reset.
* feat(review): persist ambiguous sampler evidence from scans and new outputs
The output scan and the live monitor now queue every file the ingestion
resolver finds ambiguous for Needs review. The file is captured, its metadata
is read again from the capture and resolved with the default profile, and only
an ambiguous result is stored, bound to the capture's annotation byte record
and fenced by its storage epoch. Evidence holds one hashed projection per
selectable candidate; none, more than 16 or over 8 MiB is a limited item.
Recording is idempotent per bytes and evidence and never touches a decision.
Scan statuses, counters, outcome rows and legacy SSE events are unchanged; the
job scope gains review_items/review_errors and the log a Needs review line.
The monitor records after its fallback link, best effort.
* feat(review): explicit association decisions with compatible linking
Needs review gains its queue reads and decisions:
- GET /prompt_manager/review/items lists pending items oldest first with
the exact pending total and an HMAC keyset cursor bound to the storage
epoch and the review index revision.
- GET /prompt_manager/review/items/{id} adds the candidates (role texts,
label, selectability), the dependency fingerprint and the digest.
- POST /prompt_manager/review/items/{id}/decision applies a candidate only
for a capture of the item's bytes that the current file still hashes to
and whose evidence is unchanged, through the ingester's compatible-only
rules in the same transaction as the decision row; a conflict writes
nothing. Leave unresolved records the decision and links nothing.
ingest_resolved_pair keeps its contract; its body moves into
_ingest_resolved_pair_in, which runs in the caller's transaction.
Items keep the file's recorded spelling so targets keep their case on
Windows, and a rescan skips the copy and hash of a file whose size and
mtime match the bytes an item already cites.
* fix(review): build the spelling validation test from native paths
On Windows the locator is case-folded and uses backslashes, so the fixed
POSIX pair /out/a.png no longer folded to itself and the new spelling
check refused the good case. The test now spells a mixed-case native path
and folds it with os.path.normcase, and also refuses a locator of another
file.
* fix(review): Apply sees the file under every spelling and rechecks only its choice
Apply now finds the legacy rows of the same physical file however its root
is reached. The roots are real paths while the monitor links under the
directory it watches, so a symlinked or junctioned root, subst or a mapped
drive used to hide the monitor's row and Apply added a second, differently
linked row. Same-name rows are resolved to their physical identity
(normcase(realpath), else samefile); the dependency fingerprint covers all
of them, two rows refuse the choice, one row is enriched under the
ingester's compatible-only rules, and a same-name row the request did not
classify is a changed association.
Apply re-verifies only what the decision depends on: the bytes are still
ambiguous and still offer the chosen candidate. A resolver change that
rewords the reason or reorders candidates leaves pending items applicable.
The resolver version is one constant in prompt_pair_resolver, shared by
ingestion provenance and Needs review.
The transaction's byte check receives the re-hashed digest (or the body's
for Leave unresolved), every Apply refusal branch is tested with zero
writes, and the root listing and realpath calls run on a worker thread.
* fix(review): validate stored review evidence once per startup
Startup used to run the full review validation twice (the early guard and
the install) and the annotation group's row checks inside each, so every
evidence document was parsed and re-encoded twice. The early guard is now
catalog-only (a review group without annotation tables), and the install
validates the group once, trusting the annotation group it has just
validated. The evidence predicate no longer pattern-scans every document in
SQL, because the streamed canonical pass proves it, and the codec is built
once.
Measured on a database with 40,000 items of 4 KiB evidence: startup open
went from 7.7 s to 2.5 s. A test pins one evidence pass per reopen.
Restore and verify_database_file keep the full validation.
* fix(review): keep one capture worker for interactive requests
Needs review recording from the scan and the monitor shared the capture
store's two workers with the Tag dialog and Apply, so a busy scan could
answer a user's preview or decision with "Too many previews are open".
Background captures now never take the last worker or capture slot, and
wait up to two seconds for room before counting the file as not added.
Interactive captures are admitted or refused at once, as before.
* fix(review): refresh the recorded spelling when a file is seen under a new one
A case-only rename on Windows or macOS keeps size and mtime_ns, so the
rescan skipped the file and the item kept the old spelling. Its target was
then formatted from a name the directory no longer lists, the capture
refused it, and the item stayed pending with no way to apply it. The skip
path and a duplicate insert now record the current spelling for every item
at the locator and move the review index revision; item revisions do not
change, so an open decision stays valid. Tested under case-folding
semantics on every platform.
* fix(review): final capture store close and recoverable stale cursors
Closing the capture store at shutdown now runs under the store lock and is
final: a monitor recording or scan batch still in flight gets a capture
error instead of creating a new temp directory and restore subscription
after the cleanup.
A well-formed queue cursor this process cannot verify (opened before a
ComfyUI restart, whose cursor secret is per process) now answers 409
review-conflict with the current total, like any other stale page, instead
of an uncoded 400. Malformed cursors stay 400.
* fix(review): make only the shutdown cleanup final
The previous commit made every close of the capture store final, which
also refused the explicit closes that swap in a fresh store. Only the host's
on_cleanup hook is final now; an observe after it answers a coded capture
error instead of an unhandled 500.
* refactor(admin): move Needs review recording into its own mixin
_record_scanned_review, _record_review_sync, record_review_file and
_log_review_items move unchanged from py/api/admin.py to
py/api/review_recording.py (ReviewRecordingMixin), keeping admin.py from
growing further past the size ceiling. No behaviour change.
* fix(review): record the review fix round and the skip's residual risks in TESTING.md
The Needs review paragraphs now state the rescan skip's residual risks (an
in-place rewrite that keeps size and mtime_ns is never re-queued; a deleted
or moved file leaves its pending item counted), the physical identity rule
for Apply, the candidate-only recheck and shared resolver version, the
spelling refresh, background capture admission, the final shutdown close,
the stale-cursor answer and the measured startup validation cost.
* feat(review): bind queue cursors to the storage epoch only
A decision or a new item (the monitor records one per generation) no
longer makes an open cursor stale: the (created_at, id) keyset stays
ordered when items leave or are appended. A restore still answers
storage-changed and an unverifiable cursor review-conflict.
* feat(review): Needs review page, SAVED VIEWS row and Activity hook
The concept's Metadata review page at #/review: the notice with the
exact pending count, the queue's media cards (shared with Images through
image-card.mjs), and the Resolve the association panel with the sampler
context, the chosen path's prompt blocks, Leave for later and Apply
association. Apply takes a fresh capture; refusals keep the selection
and explain inline; an unanswered decision is resent once. SAVED VIEWS
lists Needs review after Favorites with its count (retires D50), and an
ended scan that recorded review items offers Review metadata in Activity
(D87). Queue items carry the card's media url.
* feat(review): re-read an open Needs review page when its queue changes
An open Needs review page now follows the queue without polling. A new
server-sent event stream, GET /prompt_manager/review/events, sends
"ready" when it opens and "change" after every committed queue change:
an item the scan or the monitor recorded, a spelling refresh, a decision
from any tab, and a restore. database/review_changes.py notifies after
the commit from whichever thread wrote it. The page re-reads its first
page on each event, keeps the open item, its choice and an unanswered
decision, and re-reads the SAVED VIEWS count with it. When the open item
left the queue, the next one opens with a note. A keepalive comment
every 25 s lets the server drop a closed tab; shutdown ends every stream.
Leaving the page mid-decision now releases that decision's capture.
D-NEW-F1 is renumbered D119 in markers and TESTING.md.
* test(review): Needs review page workflows
The review fixture now seeds a real monitor-fallback conflict (the
monitor pipeline links a new output to the most recent prompt, then
queues it), a limited item and a file under no current root, and can add
an output through the monitor or leave one for a metadata scan.
New workflows: Apply links the chosen pair to that file only; a real
association conflict leaves the links unchanged and explains; a limited
item and an unavailable file can only be left unresolved; a tag save
leaves the item pending; keyboard focus, labels and touch targets; an
open page shows items the monitor and a scan add and a decision made in
another tab; leaving the page releases captures, the change stream and
requests. The faked 409 conflict test is replaced by the real one.
* test(review): cover the card Tag button and raise the review floors
The card's Tag on Needs review now has a workflow, and the page's queue
change hook has no unused default. review.mjs and review-state.mjs
floors rise to their measured coverage; no other floor changes.
* feat(review): keep the loaded depth on live re-reads and read once per visit
A queue change re-read only the first 40 items, so the pages Load more had
shown vanished and the page jumped. Each re-read now reads page after page
until it holds as many items as were shown (a restore met after the first
page reads again from the start), so the cards and the scroll position stay.
The stream's ready made every visit read the queue twice. List reads now
answer the queue's version (library_epoch, review_revision) and ready names
the version read after subscribing; the page re-reads on ready only when the
queue it shows is older. The SAVED VIEWS count follows the page's total, so a
change costs no count read. A stream counts as open only once ready is sent.
* test(review): compare Needs review with the approved concept
review-concept.spec.mjs measures the whole Metadata review page as a tree
in the concept and in production, on the review fixture's new
concept-shaped queue (the concept's first three image names and sizes and
its first prompt). mapConceptReview applies only D29, D119, D3, production's
hooks and accessible names and sample data, and the page then matches at
1600x1100 and 390x844 in both themes. The gallery layout follows the
concept at every breakpoint, the SAVED VIEWS rows match with Needs review
after Favorites, the queue's Tag image dialog matches the needs-review
reference, and a dropped notice border or reordered actions fail.
The comparison found one gap: an unavailable file's card lost its media
area. Its empty media button now keeps the concept's 1.33 ratio (D119).
TESTING.md records the comparison, the extended D119 and a summary of the
image-tagging slice (routes, S1, capture limits, the record-changing job,
the no-download rule, the restart note). A ready whose version cannot be
read re-reads the queue (covered by a page test).
* test(review): give the multi-route shell comparison a fitting time budget
The dispatched CI run failed "shell geometry, tokens and controls match the
concept 390x844 light" on WebKit with a 30 s test timeout (no assertion
failed). Each of these tests makes twelve page loads with captures, hovers
and focus checks: 15-19 s on a CI WebKit runner on main, 22-31 s on this
run's loaded shard. With 2 CPUs and 3 workers it fails locally the same way
(6 of 12 timed out); with a 90 s budget, as the other multi-state concept
comparisons have, all 12 pass.
* fix(review): coalesce queue change events and answer queue thumbnails
- The change stream sends the first notice at once and collapses the
notices of the next 0.4 s into one trailing change, so a busy scan costs
an open page one re-read per 0.4 s at most (COALESCE_SECONDS).
- Queue items answer thumbnail_url, the same URL the Images listing builds
(one shared helper, media_thumbnail_url), or null without a thumbnail.
- The "duplicate and refused decision send nothing" test spies on
notify_review_change instead of reading the next event.
* fix(review): keep the live queue right through applies, Load more and lost streams
- A change heard while a decision is in flight is owed and read once the
decision is refused or unanswered (I1).
- Load more has its own read: during a re-read it waits and continues from
the re-read queue; a re-read started during Load more takes the click
over, and a failed re-read leaves Load more clickable (I2, M7).
- A stream the browser gave up on (503, proxy error) reopens after 3 s,
doubling to 30 s, with a quiet "Live updates are paused" line while it is
down (I3, D-NEW-F2).
- A hidden tab closes its stream and a visible one reopens it; the ready
version keeps that to at most one read (I4).
- Apply fences on the detail's epoch and a re-read under another epoch reads
the open item again (M3); leaving during the observe releases its capture
(M4); an unanswered decision that landed finishes as recorded (M5); cards
follow a re-read's url, target and availability and show thumbnails
(M6, M10).
- The unreadable-ready test asserts exactly one re-read (M1); the panel's
long-file-name wrap carries its D119 marker and TESTING.md entry (M8).
* docs(review): number the live-updates-paused deviation D120
* fix(review): refuse monitor recording beside record-changing jobs
System S1 (#289) gives every record change a registry admission class. The
scan already records Needs review items under its own records job. The
monitor's recording lasts one file and is not a job, so it now checks the
records admission: while a records or guarded job or hold runs it records
nothing, logs that the file waits for the next scan, and answers deferred.
The fallback link stands and the next "new" scan reads the ambiguous file
again, because a fallback link is not a resolved one.
JobRegistry.blocker and active iterate a snapshot of the jobs, since the
monitor's worker thread now asks them too.
* test(backup): wait for the restore, not a 5 s timer, in the thread test
test_database_is_usable_from_every_thread_after_restore let its worker
wait 5 s for the restore. On a stalled Windows runner (py3.11, where the
previous restore test also took 25 s instead of 0.3 s) the restore took
longer, the wait timed out, and the worker read the old database before
the restore ran. The worker now waits for the event under a 120 s bound
that only a hung test reaches, reports a timeout as an error, and the
main thread releases it even when the restore raises. With a restore
delayed by 6 s the old test fails and the new one passes.
* fix(activity): drop Cancel job from a job that had ended before Activity opened
Since #289 the Activity list removed an item's actions only when they were
isConnected. On the first render the item is not in the page yet, so a job
that had already ended when Activity opened kept its "Cancel job" (and a
running job's progress was moved after its actions, then back). The list
now asks parentNode instead. The review spec "a scan job with review items
offers Review metadata in Activity" failed on this before the change
(Expected 0 buttons on a finished job, Received 1) and passes after it.
* fix(review): store non-finite evidence as null and count pending items
canonical_evidence now follows main's non-finite policy (#303): NaN and
±Infinity are written as null instead of raising, so a NaN-stamped graph
never turns a review item limited. The System Overview reports the review
queue's pending total in needs_review.pending, read in the same snapshot
as the Library counts.
* fix(review): show the pending count on the System Overview review row
The Overview's review row now reads "N ambiguous image links" with the
concept's line, from needs_review.pending. Its Review metadata action
stays aria-disabled until the Needs review page ships. The system specs
and their concept comparison follow the real count.
* feat(review): open Needs review from the System Overview review row
Review metadata on the Overview's review row now opens #/review, the
concept's go-review, instead of staying aria-disabled.
* fix(system): answer the Overview and Statistics only after every read ended
asyncio.gather answered at the first failed read while its sibling
executor reads were still inside SQLite. In the suite the test teardown
then deleted the database under the running read, and py3.10 on Ubuntu
segfaulted in get_statistics (test_statistics_failure_is_an_error_envelope).
Both routes now wait for all their reads before answering.
* fix(review): queue only ambiguous files that nothing links, and heal the queue
The maintainer's live scan (19,908 files, scope "new") reported 4,677 files
under Needs review, but the queue held 10,232 items: every file the strict
resolver found ambiguous was queued, including the ones the legacy
browser-parser fallback then linked (all sampled "added" rows) and the ones
already linked to a known prompt (135 of 200 sampled "known" rows).
A file is now queued only when its final outcome is ambiguous and unlinked:
the resolver finds it ambiguous, the fallback links nothing and no saved row
links it already. An ambiguous file that a saved row links is reported as
unchanged ("Already linked to its prompt"), not as Needs review.
The queue heals itself. After each batch, the scan removes the pending items
of every listed file (read, or skipped as known) that a saved row now links.
The monitor does the same for each ambiguous output it links, and never
queues one. Only an undecided item is removed (pending, revision 0, no
decision row), so a decision is never deleted or changed and the schema
needs no new state.
The scan job's scope.review_items now counts this scan's files that are in
the pending queue after it, new or already there, so it agrees with the
review group's ambiguous rows and with the queue total. review_added and
review_settled are new, and the log gains "already in Needs review" and
"left Needs review · now linked" lines. A duplicate whose item is decided is
reported as "decided" and is not counted.
* fix(review): announce items that leave the queue, and seed only queueable files
#284 now queues a file only when its final outcome is ambiguous and unlinked,
and it removes the pending items of files that are now linked. That removal
is a queue change, so it calls notify_review_change after its commit, like
recording and decisions: an open Needs review page re-reads its queue, and
its count follows.
The review browser fixture wrote graphs that the scan's fallback links, and
it produced the conflict item through the monitor's fallback link. Neither is
queued any more. Its files now carry ComfyUI's Infinity stamp, which the
legacy parser cannot read, so they stay unlinked with the same two
candidates. The conflict item is queued first and its file is linked to
another prompt afterwards. "monitor" additions go through
record_review_file from a worker thread.
* fix(review): never queue an ambiguous file with nothing to choose
The maintainer's live queue held 39 items whose candidates all read
"unresolved" ("No positive / No negative"). An ambiguous result is now
reviewable only when at least two candidates are resolved with non-blank
positive text. With none the file could not be traced; with exactly one,
the untraced branches may still have made the file, so that text is not
certain either. Both are reported unresolved, never linked and never
queued (also the A1111 two-delimiter case, which has no candidates).
A rescan removes the pending items of such files whose own evidence
offers no choice, with the same safe delete as the linked settle
(pending, revision 0, no decision row). A limited item (over 16 candidates) that holds at least two
candidates is kept. The job scope gains review_untraced and the log
"= N images left Needs review · nothing to choose".
* test(review): seed the limited item from a graph with more candidates than stored
An A1111 block with two negative lines offers no candidate to choose, so
Needs review no longer queues it (#284). The fixture now records a graph of
17 samplers, which the recorder stores limited.
356 lines
18 KiB
JavaScript
356 lines
18 KiB
JavaScript
import '../api-client.js';
|
|
import { createButton, createScope } from '../shared/toolkit/core.js';
|
|
import { routes, mountRouter, summarizeStats, routeTitle, loadNavCounts,
|
|
LIBRARY_WRITE_COUNTS, NAV_COUNT_ROUTES, FAVORITE_WRITE_COUNTS, FAVORITE_COUNT_DELAY_MS, REVIEW_WRITE_COUNTS } from './state.mjs';
|
|
import { mountWorkspaceTheme } from './theme.mjs';
|
|
import { mountImages, onFavoriteChange } from './images.mjs';
|
|
import { mountLibrary, mountNewPromptAction, onLibraryWrite } from './library.mjs';
|
|
import { mountVocabulary } from './vocabulary.mjs';
|
|
import { createWorkspaceIcon } from './icons.mjs';
|
|
import { bindCanvasLink, canvasHref } from './topbar.mjs';
|
|
import { renderHeading, pageHeading } from './heading.mjs';
|
|
import { closeWorkspaceDialog } from './workspace-dialogs.mjs';
|
|
import { createSavedViews, openSaveViewDialog, openEditViewDialog, savedViewHash } from './saved-views.mjs';
|
|
import { createActivityStore } from './activity-store.mjs';
|
|
import { mountActivityPage, mountActivityTopbar } from './activity.mjs';
|
|
import { mountActivityJobView } from './activity-job-view.mjs';
|
|
import { mountInspect } from './inspect.mjs';
|
|
import { mountReview } from './review.mjs';
|
|
import { createPromptSender } from './prompt-sender.mjs';
|
|
import { mountSystem } from './system.mjs';
|
|
|
|
const { createApiClient, resolveUrl } = window.ApiClient;
|
|
|
|
function element(tag, text, className) {
|
|
const node = document.createElement(tag);
|
|
if (text !== undefined) node.textContent = text;
|
|
if (className) node.className = className;
|
|
return node;
|
|
}
|
|
|
|
function legacyLink(route) {
|
|
const link = element('a', route.action, 'workspace-link');
|
|
// A native card (System, Q12) links its workspace hash; a legacy tool's page goes through the mount prefix.
|
|
link.href = route.native ? route.href : resolveUrl(route.href);
|
|
return link;
|
|
}
|
|
|
|
function mountWorkspace() {
|
|
const scope = createScope();
|
|
const api = createApiClient();
|
|
const main = document.getElementById('workspace-main');
|
|
const primaryNav = document.getElementById('primary-nav');
|
|
const savedNav = document.getElementById('saved-nav');
|
|
const systemNav = document.getElementById('system-nav');
|
|
scope.listen(document.querySelector('.skip'), 'click', event => {
|
|
event.preventDefault();
|
|
main.focus();
|
|
});
|
|
// D4: the concept's Theme select; "System" keeps following ComfyUI, then the OS.
|
|
const theme = mountWorkspaceTheme({ root: document.body, scope });
|
|
const preference = document.getElementById('theme');
|
|
preference.value = theme.preference;
|
|
scope.listen(preference, 'change', () => theme.setPreference(preference.value));
|
|
// D6: ComfyUI ↗ opens the canvas; on Images with a resolved selection it sends that pair (a send is not an Activity job).
|
|
let images = null;
|
|
scope.cleanup(bindCanvasLink(document.querySelector('.topbar .canvas-link'), {
|
|
href: canvasHref(resolveUrl, window.location.pathname),
|
|
getSelectedPair: () => images?.selectedPair?.() ?? null,
|
|
sender: {open: (roles, trigger) => images?.sender.open(roles, trigger)},
|
|
}));
|
|
// The concept's nav(): icon, label text, then a `.nav-count` only for a loaded real count.
|
|
const navLinks = ids => ids.map(([id, icon]) => {
|
|
const route = routes.find(item => item.id === id);
|
|
const link = element('a');
|
|
link.append(createWorkspaceIcon(icon), document.createTextNode(route.label));
|
|
link.href = `#/${route.id}`;
|
|
link.dataset.route = route.id;
|
|
return link;
|
|
});
|
|
primaryNav.replaceChildren(...navLinks([['images', 'images'], ['library', 'library'], ['tags', 'tags'], ['inspect', 'upload']]));
|
|
// The concept's tools-and-system group: Activity, System, then (D28) the production Overview hub.
|
|
systemNav.replaceChildren(...navLinks([['activity', 'activity'], ['system', 'settings'], ['overview', 'overview']]));
|
|
// Activity (#249 Activity-1): one store of this session's jobs feeds the top-bar button and pill, the sidebar
|
|
// row's count and the Activity page, on every route.
|
|
const activity = createActivityStore({ api, scope, connect: url => new EventSource(resolveUrl(url)) });
|
|
mountActivityTopbar({ store: activity, scope });
|
|
activity.load();
|
|
const sidebar = document.querySelector('aside.sidebar');
|
|
// The route key a nav link carries in `data-route`: a saved view's is `saved/<id>`.
|
|
const routeKey = route => route.id === 'saved' ? `saved/${route.savedId}` : route.id;
|
|
let currentKey = null;
|
|
const markCurrent = () => {
|
|
for (const link of sidebar.querySelectorAll('nav [data-route]')) {
|
|
if (link.dataset.route === currentKey) link.setAttribute('aria-current', 'page');
|
|
else link.removeAttribute('aria-current');
|
|
}
|
|
};
|
|
// SAVED VIEWS (#249 D16): the concept's saved-nav rows (search icon, name, no count), loaded with the shell and
|
|
// re-read after every change. /* D49 */ no "PROPOSED" badge. The first rows are the concept's Favorites (star icon,
|
|
// count, D51) and Needs review (review icon, the exact pending count, ruling R5), kept across every re-read so
|
|
// their counts stay.
|
|
const [favoritesLink, reviewLink] = navLinks([['favorites', 'star'], ['review', 'review']]);
|
|
savedNav.replaceChildren(favoritesLink, reviewLink);
|
|
const savedViews = createSavedViews(api, scope.signal);
|
|
scope.cleanup(savedViews.subscribe(({ views }) => {
|
|
savedNav.replaceChildren(favoritesLink, reviewLink, ...views.map(view => {
|
|
const link = element('a');
|
|
link.append(createWorkspaceIcon('search'), document.createTextNode(view.name));
|
|
link.href = savedViewHash(view.id);
|
|
link.dataset.route = `saved/${view.id}`;
|
|
return link;
|
|
}));
|
|
markCurrent();
|
|
}));
|
|
savedViews.load();
|
|
/** The toolbar's Save view on a page: the concept's name dialog, then the store saves the page's full state. */
|
|
const saveView = (page, view) => (trigger, state) => openSaveViewDialog({ scope: view, trigger, q: state.q,
|
|
onSave: name => savedViews.create(page, name, state) });
|
|
// One read per count, so a write that refreshes Library and Tags never supersedes an Images read in flight.
|
|
const countRequests = new Map();
|
|
function refreshCounts(ids) {
|
|
for (const id of ids) {
|
|
countRequests.get(id)?.abort();
|
|
const request = new AbortController();
|
|
countRequests.set(id, request);
|
|
// Each badge lands as its own read settles; a count that failed to refresh is removed, never left stale.
|
|
loadNavCounts(api, request.signal, (_, count) => {
|
|
if (!request.signal.aborted) showCount(id, count);
|
|
}, [id]);
|
|
}
|
|
}
|
|
function showCount(id, count) {
|
|
const link = sidebar.querySelector(`nav [data-route="${id}"]`);
|
|
link?.querySelector('.nav-count')?.remove();
|
|
if (link && Number.isSafeInteger(count)) link.append(element('span', count.toLocaleString(), 'nav-count'));
|
|
}
|
|
/** A count a page has just read itself: it replaces the badge, and an older read in flight no longer lands. */
|
|
function setCount(id, count) {
|
|
countRequests.get(id)?.abort();
|
|
countRequests.delete(id);
|
|
showCount(id, count);
|
|
}
|
|
scope.cleanup(() => { for (const request of countRequests.values()) request.abort(); });
|
|
// A confirmed Library or vocabulary write cannot change the Images count, so only Library and Tags are re-read.
|
|
scope.cleanup(onLibraryWrite(() => refreshCounts(LIBRARY_WRITE_COUNTS)));
|
|
// Starring or unstarring anywhere (Images, Favorites, Library media) re-reads the Favorites count (D51), once
|
|
// after a run of quick toggles settles rather than once per click (#249 M1).
|
|
let favoriteCountTimer = 0;
|
|
scope.cleanup(onFavoriteChange(() => {
|
|
clearTimeout(favoriteCountTimer);
|
|
favoriteCountTimer = setTimeout(() => refreshCounts(FAVORITE_WRITE_COUNTS), FAVORITE_COUNT_DELAY_MS);
|
|
}));
|
|
scope.cleanup(() => clearTimeout(favoriteCountTimer));
|
|
// A metadata scan that ends may have added items to Needs review: re-read its count once per ended scan.
|
|
const runningScans = new Set();
|
|
scope.cleanup(activity.subscribe(() => {
|
|
let ended = false;
|
|
for (const job of activity.jobs()) {
|
|
if (job.kind !== 'scan') continue;
|
|
if (job.state === 'running') runningScans.add(job.id);
|
|
else if (runningScans.delete(job.id)) ended = true;
|
|
}
|
|
if (ended) refreshCounts(REVIEW_WRITE_COUNTS);
|
|
}));
|
|
refreshCounts(NAV_COUNT_ROUTES);
|
|
let viewScope;
|
|
let firstRender = true;
|
|
// D62: a page whose teardown must wait (Inspect, while a video is still starting) holds the next route until it
|
|
// settles; the latest route wins.
|
|
let leaveGuard = null, renderToken = 0;
|
|
scope.cleanup(() => viewScope?.dispose());
|
|
|
|
// The mounted System page: another of its sections is shown in place, keeping the shell and the drafts.
|
|
let system = null;
|
|
|
|
function render(route) {
|
|
const token = ++renderToken;
|
|
const hold = leaveGuard?.();
|
|
if (hold) {
|
|
hold.then(() => { if (token === renderToken && !scope.signal.aborted) renderNow(route); });
|
|
return;
|
|
}
|
|
renderNow(route);
|
|
}
|
|
|
|
function renderNow(route) {
|
|
leaveGuard = null;
|
|
// A shared page dialog never stays open over the next route.
|
|
closeWorkspaceDialog();
|
|
if (route.id === 'system' && system && currentKey === 'system') {
|
|
system.show(route.section);
|
|
return;
|
|
}
|
|
system = null;
|
|
viewScope?.dispose();
|
|
images = null;
|
|
viewScope = createScope();
|
|
const view = viewScope;
|
|
currentKey = routeKey(route);
|
|
markCurrent();
|
|
if (route.id === 'saved') {
|
|
openSavedView(route, view);
|
|
return;
|
|
}
|
|
renderPage(route, view);
|
|
}
|
|
|
|
/** A saved view opens its page with its state; the heading, breadcrumb and title are the view's name. */
|
|
async function openSavedView(route, view) {
|
|
main.replaceChildren();
|
|
await savedViews.settled();
|
|
if (view.signal.aborted) return;
|
|
// A view saved since the list loaded (another tab) is read once more before the link counts as gone.
|
|
if (!savedViews.find(route.savedId) && savedViews.status === 'ready') {
|
|
await savedViews.load();
|
|
if (view.signal.aborted) return;
|
|
}
|
|
const saved = savedViews.find(route.savedId);
|
|
if (saved) {
|
|
const page = routes.find(item => item.id === saved.page);
|
|
renderPage({...page, label:saved.name, title:saved.name}, view, saved);
|
|
mountEditAction(saved, view);
|
|
return;
|
|
}
|
|
if (savedViews.status === 'ready') {
|
|
// A removed or unknown view: the shell's default page, without a history entry for the dead link.
|
|
window.location.replace('#/images');
|
|
return;
|
|
}
|
|
const {description} = renderHeading(main, {title:route.label});
|
|
description.textContent = 'Saved views could not be loaded. Your saved data has not changed.';
|
|
description.setAttribute('role', 'alert');
|
|
const retry = createButton('Retry');
|
|
view.listen(retry, 'click', () => {
|
|
savedViews.load();
|
|
openSavedView(route, view);
|
|
});
|
|
main.append(retry);
|
|
}
|
|
|
|
// /* D51 */ The open view's Edit (maintainer ruling): first in the heading's actions. A rename re-reads the list and
|
|
// retitles the open page; a delete re-reads it and replaces the dead route with the view's plain page.
|
|
function mountEditAction(saved, view) {
|
|
// renderPage has just written the heading.
|
|
const edit = createButton('Edit');
|
|
pageHeading(main).actions.prepend(edit);
|
|
view.listen(edit, 'click', () => openEditViewDialog({ scope: view, trigger: edit, view: saved,
|
|
onRename: async name => {
|
|
const renamed = await savedViews.rename(saved.id, name);
|
|
if (view.signal.aborted) return;
|
|
saved = renamed;
|
|
retitle(renamed.name);
|
|
},
|
|
onDelete: async () => {
|
|
await savedViews.remove(saved.id);
|
|
window.location.replace(`#/${saved.page}`);
|
|
} }));
|
|
}
|
|
|
|
function retitle(name) {
|
|
// Only the mounted view retitles (its rename returns once aborted), so its heading is present.
|
|
pageHeading(main).h1.textContent = name;
|
|
document.getElementById('workspace-breadcrumb').textContent = name;
|
|
document.title = `${name} · Prompt Manager`;
|
|
}
|
|
|
|
function renderPage(route, view, saved = null) {
|
|
document.title = `${routeTitle(route)} · Prompt Manager`;
|
|
// The concept's heading(); each view fills its description and actions.
|
|
// The concept focuses its page title on a hashchange navigation (app.js 1168); the skip link focuses `main`.
|
|
const { description, h1 } = renderHeading(main, { title: route.label });
|
|
if (!firstRender) h1.focus();
|
|
firstRender = false;
|
|
document.getElementById('workspace-breadcrumb').textContent = routeTitle(route);
|
|
if (route.id === 'images' || route.id === 'favorites') {
|
|
mountNewPromptAction(main, api, view);
|
|
images = mountImages(main, api, view, {savedState:saved?.state, favorites:route.id === 'favorites',
|
|
onSaveView:saveView('images', view), activity});
|
|
return;
|
|
}
|
|
if (route.id === 'library') {
|
|
mountLibrary(main, api, view, {positiveId:route.positiveId, savedState:saved?.state, onSaveView:saveView('library', view)});
|
|
return;
|
|
}
|
|
if (route.id === 'tags') {
|
|
mountVocabulary(main, api, view);
|
|
return;
|
|
}
|
|
if (route.id === 'activity') {
|
|
// D56: `#/activity/<id>` is that job's own view; `#/activity` lists the session's jobs.
|
|
if (route.jobId) mountActivityJobView(main, { store: activity, scope: view, api, jobId: route.jobId });
|
|
else mountActivityPage(main, { store: activity, scope: view });
|
|
return;
|
|
}
|
|
if (route.id === 'review') {
|
|
// Needs review (ruling R5): a recorded decision re-reads the row's count, and the open page's total is the
|
|
// count (F3: a change the page hears of costs no count read).
|
|
mountReview(main, { api, scope: view, onDecision: () => refreshCounts(REVIEW_WRITE_COUNTS),
|
|
onTotal: total => setCount('review', total) });
|
|
return;
|
|
}
|
|
if (route.id === 'system') {
|
|
// The concept's System (app.js renderSystem): its heading description, section nav and Save row.
|
|
description.textContent = route.description;
|
|
system = mountSystem(main, api, view, { section: route.section, activity });
|
|
return;
|
|
}
|
|
if (route.id === 'inspect') {
|
|
// The concept's Inspect a file (app.js renderMetadata): a local file, read only in this browser.
|
|
description.textContent = route.description;
|
|
({ leaveGuard } = mountInspect(main, { parentScope: view, api, sender: createPromptSender({ scope: view }) }));
|
|
return;
|
|
}
|
|
description.textContent = 'A home for your prompts, images and creative history.';
|
|
const stats = element('section', undefined, 'overview-stats');
|
|
stats.setAttribute('aria-label', 'Library statistics');
|
|
main.append(stats);
|
|
const tools = element('section', undefined, 'surface');
|
|
tools.append(element('h2', 'Continue creating'), element('p', 'Your existing tools remain available while the new workspaces take shape.'));
|
|
const cards = element('div', undefined, 'tool-grid');
|
|
for (const target of routes.filter(item => item.href)) {
|
|
const card = element('article', undefined, 'tool-card');
|
|
card.append(element('h3', target.label), element('p', target.description, 'small'), legacyLink(target));
|
|
cards.append(card);
|
|
}
|
|
tools.append(cards);
|
|
main.append(tools);
|
|
async function loadStats() {
|
|
const status = element('p', 'Loading library statistics…');
|
|
status.setAttribute('role', 'status');
|
|
stats.replaceChildren(status);
|
|
try {
|
|
const result = await api.get('/prompt_manager/stats', { signal: view.signal });
|
|
if (view.signal.aborted) return;
|
|
const values = summarizeStats(result.stats);
|
|
const list = element('dl', undefined, 'stat-grid');
|
|
for (const [label, count] of values) {
|
|
const stat = element('div', undefined, 'stat');
|
|
stat.append(element('dt', label), element('dd', count.toLocaleString()));
|
|
list.append(stat);
|
|
}
|
|
stats.replaceChildren(list);
|
|
if (values.every(([, count]) => count === 0)) {
|
|
stats.append(element('p', 'Your library is empty. Add a prompt in the prompt library or configure sources in System.', 'empty-state'));
|
|
}
|
|
} catch (error) {
|
|
if (view.signal.aborted) return;
|
|
const alert = element('p', 'Library statistics could not be loaded. Your saved data has not changed.');
|
|
alert.setAttribute('role', 'alert');
|
|
const retry = createButton('Retry');
|
|
view.listen(retry, 'click', loadStats);
|
|
stats.replaceChildren(alert, retry);
|
|
}
|
|
}
|
|
loadStats();
|
|
}
|
|
scope.cleanup(mountRouter(window, render));
|
|
scope.listen(window, 'pagehide', () => scope.dispose());
|
|
return () => scope.dispose();
|
|
}
|
|
|
|
mountWorkspace();
|
|
window.addEventListener('pageshow', event => {
|
|
if (event.persisted) mountWorkspace();
|
|
});
|