* 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.
624 lines
38 KiB
JavaScript
624 lines
38 KiB
JavaScript
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||
import { test, expect } from './fixtures.mjs';
|
||
import { seedConcept } from './concept-inventory.mjs';
|
||
|
||
// System › Overview (#249 System S2 Task 6) on the concept-shaped real fixture: the metrics, rows, Statistics dialog and
|
||
// Health report read the server, never sample values (D93, D95, D96). The hooks are workspace_system_fixture.py's.
|
||
const workspace = '/prompt_manager/workspace';
|
||
const OVERVIEW_URL = '/prompt_manager/system/overview';
|
||
const THUMBNAILS_URL = '/prompt_manager/images/thumbnails/status';
|
||
const number = value => value.toLocaleString('en-US');
|
||
|
||
test.beforeEach(async ({ page, request, browserName }) => {
|
||
await startCoverage(page, browserName);
|
||
page.manifest = await seedConcept(request);
|
||
await expect(await request.post('/__test__/system/reset')).toBeOK();
|
||
await expect(await request.post('/__test__/jobs/restart')).toBeOK();
|
||
page.systemErrors = [];
|
||
page.on('pageerror', error => page.systemErrors.push(error.message));
|
||
});
|
||
|
||
test.afterEach(async ({ page, request, browserName }) => {
|
||
await saveCoverage(page, browserName);
|
||
await request.post('/__test__/release');
|
||
await request.post('/__test__/system/reset');
|
||
expect(page.systemErrors).toEqual([]);
|
||
});
|
||
|
||
async function serverJson(request, url) {
|
||
const response = await request.get(url);
|
||
await expect(response).toBeOK();
|
||
return response.json();
|
||
}
|
||
|
||
const layoutOf = page => page.locator('#workspace-main .settings-layout');
|
||
|
||
async function openOverview(page) {
|
||
await page.goto(`${workspace}#/system/overview`);
|
||
await expect(layoutOf(page).locator(':scope > .summary-metrics')).toBeVisible();
|
||
return layoutOf(page);
|
||
}
|
||
|
||
/** The rows of one Overview surface: `[h3, p, button]`. */
|
||
function rowsOf(layout, heading) {
|
||
return layout.locator('.two-col > section.surface').filter({ has: layout.page().getByRole('heading', { name: heading, exact: true }) })
|
||
.locator('.operation').evaluateAll(rows => rows.map(row => [row.querySelector('h3').textContent,
|
||
row.querySelector('p').textContent, row.querySelector('.row-actions button').textContent]));
|
||
}
|
||
|
||
test('overview shows real counts and Not checked', async ({ page, request }) => {
|
||
const writes = [];
|
||
page.on('request', item => { if (!['GET', 'HEAD', 'OPTIONS'].includes(item.method())) writes.push(item.url()); });
|
||
const overview = await serverJson(request, OVERVIEW_URL);
|
||
const thumbnails = await serverJson(request, THUMBNAILS_URL);
|
||
// The concept fixture: six positives, their saved negatives and 24 linked images, all with thumbnails.
|
||
expect([overview.library.positive_prompts, overview.images.indexed, thumbnails.pending]).toEqual([6, 24, 0]);
|
||
// I2: the Overview never walks the sources for thumbnails; the row reads the status route itself.
|
||
expect(overview).not.toHaveProperty('thumbnails');
|
||
// The fixture records no ambiguous file: the Needs review queue is empty.
|
||
expect(overview.needs_review).toEqual({ pending: 0 });
|
||
const layout = await openOverview(page);
|
||
expect(await layout.locator('.summary-metrics > .metric').evaluateAll(items => items.map(item =>
|
||
[item.querySelector('strong').textContent, item.querySelector('span').textContent]))).toEqual([
|
||
[number(overview.library.positive_prompts), 'Positive prompts'],
|
||
[number(overview.library.negative_variants), 'Negative variants'],
|
||
[number(overview.images.indexed), 'Images'],
|
||
['Not checked', 'Database integrity'],
|
||
]);
|
||
expect(await rowsOf(layout, 'Library health')).toEqual([
|
||
['0 ambiguous image links', 'Review metadata before assigning a positive / negative pair.', 'Review metadata'],
|
||
['Backup status', 'No retained backup record.', 'View backups'],
|
||
['No missing thumbnails', 'Generate only missing previews when necessary.', 'Review thumbnails'],
|
||
]);
|
||
expect(await rowsOf(layout, 'Workspace preferences')).toEqual([
|
||
['One display configuration', 'Grid and density settings are shared across views.', 'Appearance'],
|
||
['2 output sources', 'Monitoring and enrichment share one source list.', 'Manage sources'],
|
||
['Statistics', 'Runs and ratings by category, with library totals.', 'Explore'],
|
||
]);
|
||
expect(writes).toEqual([]);
|
||
});
|
||
|
||
test('Run health checks opens Health report and updates metric 4', async ({ page, request }) => {
|
||
await page.goto(`${workspace}#/system/maintenance`);
|
||
const layout = layoutOf(page);
|
||
await expect(layout.locator(':scope > .notice h2')).toHaveText('Check first. Review changes. Then apply.');
|
||
// The rest of Maintenance is still the existing tools' (D94).
|
||
await expect(layout.locator(':scope > section.handoff h2')).toHaveText('Your current tools are ready');
|
||
const run = layout.getByRole('button', { name: 'Run health checks', exact: true });
|
||
await run.click();
|
||
const dialog = page.locator('dialog#modal[open]');
|
||
await expect(dialog.locator('#modal-title')).toHaveText('Health report');
|
||
const { report } = await serverJson(request, '/prompt_manager/system/health');
|
||
expect(report.status).toBe('incomplete');
|
||
expect(await dialog.locator('.operation-list > .operation').evaluateAll(rows => rows.map(row =>
|
||
[row.querySelector('h3').textContent, row.querySelector('span.chip').textContent]))).toEqual([
|
||
['Integrity check', 'Passed'], ['Foreign keys & pair references', 'Passed'], ['Canonical hashes', 'Passed'],
|
||
['Pair uniqueness', 'Passed'], ['Missing files · output', 'Passed'], ['Missing files · input', 'Passed'],
|
||
['Ambiguous metadata', 'Not available yet'], ['Consistency', 'Passed'],
|
||
]);
|
||
await expect(dialog.locator('#modal-body > p.small')).toHaveText(/^Checked .+\. Some checks could not run, so this report is incomplete\.$/);
|
||
await expect(dialog.locator('.dialog-actions button')).toHaveText(['Close', 'Review missing links']);
|
||
await dialog.getByRole('button', { name: 'Close', exact: true }).click();
|
||
await expect(page.locator('dialog#modal[open]')).toHaveCount(0);
|
||
await expect(run).toBeFocused();
|
||
await page.locator('#workspace-main .section-nav').getByRole('button', { name: 'Overview', exact: true }).click();
|
||
await expect(layout.locator('.metric').nth(3).locator('strong')).toHaveText('Incomplete');
|
||
|
||
// A missing file and an unmounted source: the report counts the readable sources and names the other one.
|
||
await expect(await request.post('/__test__/system/missing-file')).toBeOK();
|
||
await expect(await request.post('/__test__/system/missing-source')).toBeOK();
|
||
await page.locator('#workspace-main .section-nav').getByRole('button', { name: 'Maintenance', exact: true }).click();
|
||
await layout.getByRole('button', { name: 'Run health checks', exact: true }).click();
|
||
await expect(dialog.locator('.operation').filter({ hasText: 'Missing files' }).locator('.chip'))
|
||
.toHaveText(['1 link needs review', 'Passed', 'Not available']);
|
||
await expect(dialog.locator('.operation h3').filter({ hasText: 'Missing files' }))
|
||
.toHaveText(['Missing files · output', 'Missing files · input', 'Missing files · unmounted-drive']);
|
||
// Review missing links goes to Maintenance, where the cleanup's existing tool is linked.
|
||
await dialog.getByRole('button', { name: 'Review missing links', exact: true }).click();
|
||
await expect(page.locator('dialog#modal[open]')).toHaveCount(0);
|
||
await expect(page).toHaveURL(`${workspace}#/system/maintenance`);
|
||
await page.locator('#workspace-main .section-nav').getByRole('button', { name: 'Overview', exact: true }).click();
|
||
await expect(layout.locator('.metric').nth(3).locator('strong')).toHaveText('1 issue');
|
||
});
|
||
|
||
test('a health check that fails says so and keeps the last result', async ({ page, request }) => {
|
||
await expect(await request.post('/__test__/system/fail', { data: { path: '/prompt_manager/system/health' } })).toBeOK();
|
||
await page.goto(`${workspace}#/system/maintenance`);
|
||
const run = layoutOf(page).getByRole('button', { name: 'Run health checks', exact: true });
|
||
await run.click();
|
||
await expect(page.locator('#workspace-toast')).toHaveText('The health check could not finish. Nothing was changed.');
|
||
await expect(page.locator('dialog#modal[open]')).toHaveCount(0);
|
||
await expect(run).not.toHaveAttribute('aria-disabled', 'true');
|
||
await openOverview(page);
|
||
await expect(layoutOf(page).locator('.metric').nth(3).locator('strong')).toHaveText('Not checked');
|
||
});
|
||
|
||
test('thumbnail row reflects the status endpoint', async ({ page, request }) => {
|
||
await expect(await request.post('/__test__/system/unthumbnailed', { data: { count: 3 } })).toBeOK();
|
||
const status = await serverJson(request, '/prompt_manager/images/thumbnails/status');
|
||
expect(status.pending).toBe(3);
|
||
const layout = await openOverview(page);
|
||
const row = layout.locator('.operation').filter({ has: page.getByRole('button', { name: 'Review thumbnails', exact: true }) });
|
||
await expect(row.locator('h3')).toHaveText('3 missing thumbnails');
|
||
// Until the thumbnail review dialog (S5), Review thumbnails opens Sources.
|
||
await row.getByRole('button', { name: 'Review thumbnails', exact: true }).click();
|
||
await expect(page).toHaveURL(`${workspace}#/system/sources`);
|
||
});
|
||
|
||
test('the thumbnail row paints when its own status read answers', async ({ page, request }) => {
|
||
const held = async () => (await serverJson(request, '/__test__/hold')).held[THUMBNAILS_URL] ?? 0;
|
||
await expect(await request.post('/__test__/hold', { data: { path: THUMBNAILS_URL } })).toBeOK();
|
||
const layout = await openOverview(page);
|
||
const row = layout.locator('.operation').filter({ has: page.getByRole('button', { name: 'Review thumbnails', exact: true }) });
|
||
// The other values do not wait for the walk of every source.
|
||
await expect(row.locator('h3')).toHaveText('Checking thumbnails…');
|
||
await expect(layout.locator('.summary-metrics > .metric')).toHaveCount(4);
|
||
await expect.poll(held).toBe(1);
|
||
await expect(await request.post('/__test__/release')).toBeOK();
|
||
await expect(row.locator('h3')).toHaveText('No missing thumbnails');
|
||
});
|
||
|
||
test('a failed thumbnail read is unavailable, never zero', async ({ page }) => {
|
||
await page.route(`**${THUMBNAILS_URL}`, route => route.fulfill({ status: 500, contentType: 'application/json',
|
||
body: JSON.stringify({ success: false, error: 'Injected failure' }) }));
|
||
const layout = await openOverview(page);
|
||
const row = layout.locator('.operation').filter({ has: page.getByRole('button', { name: 'Review thumbnails', exact: true }) });
|
||
await expect(row.locator('h3')).toHaveText('Thumbnail status unavailable');
|
||
await expect(layout.getByRole('alert')).toHaveCount(0);
|
||
await expect(layout.locator('.metric').nth(2).locator('strong')).toHaveText('24');
|
||
});
|
||
|
||
test('ambiguous row reads the pending count and Review metadata opens Needs review', async ({ page }) => {
|
||
const layout = await openOverview(page);
|
||
const row = layout.locator('.operation').filter({ hasText: 'ambiguous image links' });
|
||
await expect(row.locator('h3')).toHaveText('0 ambiguous image links');
|
||
await expect(row.locator('p')).toHaveText('Review metadata before assigning a positive / negative pair.');
|
||
const review = row.getByRole('button', { name: 'Review metadata', exact: true });
|
||
await expect(review).not.toHaveAttribute('aria-disabled');
|
||
await review.click();
|
||
// The concept's go-review: the Needs review page.
|
||
await expect(page).toHaveURL(`${workspace}#/review`);
|
||
await expect(page.getByRole('heading', { name: 'Metadata review', exact: true })).toBeVisible();
|
||
});
|
||
|
||
test('View backups / Appearance / Manage sources switch sections', async ({ page }) => {
|
||
for (const [label, section, pressed] of [['View backups', 'backups', 'Backup & export'], ['Appearance', 'appearance', 'Appearance'],
|
||
['Manage sources', 'sources', 'Sources & scans']]) {
|
||
const layout = await openOverview(page);
|
||
await layout.getByRole('button', { name: label, exact: true }).click();
|
||
await expect(page).toHaveURL(`${workspace}#/system/${section}`);
|
||
await expect(page.locator('#workspace-main .section-nav [aria-pressed="true"]')).toHaveText(pressed);
|
||
await expect(layout.locator(':scope > .summary-metrics')).toHaveCount(0);
|
||
}
|
||
});
|
||
|
||
test('statistics dialog lists runs by category and library totals', async ({ page, request }) => {
|
||
const statistics = await serverJson(request, '/prompt_manager/system/statistics');
|
||
expect(statistics.by_category.length).toBeGreaterThan(1);
|
||
const layout = await openOverview(page);
|
||
const explore = layout.getByRole('button', { name: 'Explore', exact: true });
|
||
await explore.click();
|
||
const dialog = page.locator('dialog#modal[open]');
|
||
await expect(dialog.locator('#modal-title')).toHaveText('Usage statistics');
|
||
const tables = dialog.locator('#modal-body > table');
|
||
await expect(tables.locator('caption')).toHaveText(['Runs by category', 'Library totals']);
|
||
await expect(tables.first().locator('thead th')).toHaveText(['Category', 'Runs', 'Avg. rating']);
|
||
const cells = table => table.locator('tbody tr').evaluateAll(rows => rows.map(row => [...row.cells].map(cell => cell.textContent)));
|
||
expect(await cells(tables.first())).toEqual(statistics.by_category.map(row => [row.category ?? 'Uncategorized',
|
||
number(row.runs), row.average_rating === null ? 'Not rated' : `${number(row.average_rating)} / 5`]));
|
||
expect(await cells(tables.nth(1))).toEqual([['Prompts', number(statistics.totals.total_prompts)],
|
||
['Tags', number(statistics.totals.total_tags)], ['Images', number(statistics.totals.total_images)],
|
||
['Rated images', number(statistics.rated_images)]]);
|
||
await page.keyboard.press('Escape');
|
||
await expect(explore).toBeFocused();
|
||
// A statistics read that fails says so; the Overview stays.
|
||
await expect(await request.post('/__test__/system/fail', { data: { path: '/prompt_manager/system/statistics' } })).toBeOK();
|
||
await explore.click();
|
||
await expect(page.locator('#workspace-toast')).toHaveText('Statistics could not be loaded. Your saved data has not changed.');
|
||
await expect(page.locator('dialog#modal[open]')).toHaveCount(0);
|
||
});
|
||
|
||
test('load failure shows Retry and no zeros', async ({ page, request }) => {
|
||
await expect(await request.post('/__test__/system/fail', { data: { path: OVERVIEW_URL } })).toBeOK();
|
||
await page.goto(`${workspace}#/system/overview`);
|
||
const layout = layoutOf(page);
|
||
await expect(layout.getByRole('alert')).toHaveText('The overview could not be loaded. Your saved data has not changed.');
|
||
await expect(layout.locator('.metric')).toHaveCount(0);
|
||
await expect(layout).not.toContainText('0');
|
||
await layout.getByRole('button', { name: 'Retry', exact: true }).click();
|
||
await expect(layout.locator('.summary-metrics > .metric')).toHaveCount(4);
|
||
await expect(layout.getByRole('alert')).toHaveCount(0);
|
||
});
|
||
|
||
test('out-of-order overview responses never repaint a newer section', async ({ page, request }) => {
|
||
const held = async () => (await serverJson(request, '/__test__/hold')).held[OVERVIEW_URL] ?? 0;
|
||
await expect(await request.post('/__test__/hold', { data: { path: OVERVIEW_URL } })).toBeOK();
|
||
await page.goto(`${workspace}#/system/overview`);
|
||
const layout = layoutOf(page);
|
||
await expect(layout.getByRole('status')).toHaveText('Loading the overview…');
|
||
await expect.poll(held).toBe(1);
|
||
// Leave for Appearance, come back (a second read), then leave again before either answers.
|
||
const nav = page.locator('#workspace-main .section-nav');
|
||
await nav.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||
await nav.getByRole('button', { name: 'Overview', exact: true }).click();
|
||
await expect.poll(held).toBe(2);
|
||
// Integrations still hands off (S10), so its body is one known panel.
|
||
await nav.getByRole('button', { name: 'Integrations', exact: true }).click();
|
||
await expect(await request.post('/__test__/release')).toBeOK();
|
||
await expect.poll(held).toBe(0);
|
||
// Both late answers reached a section that had left: Integrations keeps its own body.
|
||
await expect(layout.locator(':scope > section.handoff')).toBeVisible();
|
||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||
await expect(layout.locator('.summary-metrics')).toHaveCount(0);
|
||
expect(await layout.evaluate(node => [...node.children].map(child => child.className))).toEqual(['surface handoff', 'save-row']);
|
||
// Back on Overview, one fresh read paints one set of metrics.
|
||
await nav.getByRole('button', { name: 'Overview', exact: true }).click();
|
||
await expect(layout.locator('.summary-metrics')).toHaveCount(1);
|
||
await expect(layout.locator('.two-col')).toHaveCount(1);
|
||
});
|
||
|
||
// System › Appearance (#249 System S3 Task 8): the browser display defaults (`gallerySettings`, preferences.mjs) and the
|
||
// two host fields behind the one Save row, and the consumers that read them on their next visit.
|
||
const SETTINGS_URL = '/prompt_manager/settings';
|
||
const INSPECT_PATH = '/prompt_manager/images/inspect/';
|
||
const statusOf = page => page.locator('#workspace-main #settings-status');
|
||
const saveOf = page => page.locator('#workspace-main .save-row > button');
|
||
const storedSettings = page => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings') || 'null'));
|
||
const imageCards = page => page.locator('#workspace-main article.media-card');
|
||
const panel = page => page.getByRole('complementary', { name: 'Selected image details', exact: true });
|
||
|
||
async function openAppearance(page) {
|
||
await page.goto(`${workspace}#/system/appearance`);
|
||
await expect(page.locator('#workspace-main .settings-layout > section.surface > h2')).toHaveText('Browsing & display');
|
||
// The host rows are enabled once the server settings answered.
|
||
await expect(page.locator('#timeout')).toBeEnabled();
|
||
}
|
||
|
||
async function saveAppearance(page, text) {
|
||
await expect(saveOf(page)).not.toHaveAttribute('aria-disabled', 'true');
|
||
await saveOf(page).click();
|
||
await expect(statusOf(page)).toHaveText(text);
|
||
}
|
||
|
||
/** Set toggles (by row id) through their Toolkit switches. */
|
||
async function toggle(page, values) {
|
||
for (const [id, checked] of Object.entries(values)) await page.locator(`#${id}`).setChecked(checked, { force: true });
|
||
}
|
||
|
||
/**
|
||
* A request barrier: one request issued and answered after everything the page has asked for so far, so a read the
|
||
* last action started has been seen (Playwright reports a page's requests in order).
|
||
*/
|
||
async function requestBarrier(page) {
|
||
expect(await page.evaluate(url => fetch(url, { cache: 'no-store' }).then(response => response.ok), SETTINGS_URL)).toBe(true);
|
||
}
|
||
|
||
async function openImages(page) {
|
||
await page.goto(`${workspace}#/images`);
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
}
|
||
|
||
test('defaults apply to a new visit but not to the current view or a saved view', async ({ page, request }) => {
|
||
const created = await request.post('/prompt_manager/saved-views', { data: { page: 'images', name: 'Everything',
|
||
state: { q: '', category: '', sort: 'newest', source: 'all', folder: '', media: 'all', tags: [], favorites: false } } });
|
||
expect(created.status()).toBe(201);
|
||
const view = (await created.json()).view;
|
||
try {
|
||
await openImages(page);
|
||
// The current view: the toolbar sets List.
|
||
await page.getByRole('group', { name: 'Image layout' }).getByRole('button', { name: 'List', exact: true }).click();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'list');
|
||
await openAppearance(page);
|
||
await expect(page.locator('#default-view')).toHaveValue('grid');
|
||
await page.locator('#default-view').selectOption('masonry');
|
||
await page.locator('#density').selectOption('compact');
|
||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
const stored = await storedSettings(page);
|
||
expect([stored.workspaceLayout, stored.workspaceDensity]).toEqual(['masonry', 'compact']);
|
||
// Back in Images (the page session's last visit): the current view keeps its own layout and size.
|
||
await page.locator('#primary-nav a[data-route="images"]').click();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'list');
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-density', 'comfortable');
|
||
// The saved view opens as before.
|
||
await page.goto(`${workspace}#/saved/${view.id}`);
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'grid');
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-density', 'comfortable');
|
||
// A new visit starts from the defaults.
|
||
await openImages(page);
|
||
await page.reload();
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'masonry');
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-density', 'compact');
|
||
await expect(page.getByRole('group', { name: 'Image layout' }).getByRole('button', { name: 'Masonry', exact: true }))
|
||
.toHaveAttribute('aria-pressed', 'true');
|
||
} finally {
|
||
await request.delete(`/prompt_manager/saved-views/${view.id}`);
|
||
}
|
||
});
|
||
|
||
test('the defaults reach the Images page only; embedded galleries keep their own presentation', async ({ page }) => {
|
||
await openAppearance(page);
|
||
await page.locator('#default-view').selectOption('list');
|
||
await page.locator('#density').selectOption('compact');
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
// The prompt history's shared gallery has no toolbar to change them, so it opens as it always did.
|
||
await page.goto(`${workspace}#/library/${page.manifest.prompts[0].positive_id}`);
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
await expect(page.locator('#workspace-main .image-grid')).toHaveAttribute('data-layout', 'grid');
|
||
await expect(page.locator('#workspace-main .image-grid')).toHaveAttribute('data-density', 'comfortable');
|
||
// The Images page starts from them.
|
||
await page.locator('#primary-nav a[data-route="images"]').click();
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'list');
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-density', 'compact');
|
||
});
|
||
|
||
test('metadata off shows an explicit load and loads once on request', async ({ page }) => {
|
||
await openAppearance(page);
|
||
await toggle(page, { 'metadata-auto': false });
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
const reads = [];
|
||
page.on('request', item => { if (new URL(item.url()).pathname.startsWith(INSPECT_PATH)) reads.push(item.url()); });
|
||
await openImages(page);
|
||
const first = imageCards(page).first();
|
||
await first.locator('.image-card-actions button').first().click();
|
||
await expect(panel(page).getByRole('status')).toHaveText('Metadata loads when you ask for it.');
|
||
const load = panel(page).getByRole('button', { name: 'Load metadata', exact: true });
|
||
await expect(load).toBeVisible();
|
||
expect(reads).toEqual([]);
|
||
await load.click();
|
||
await expect(panel(page).locator('.panel-heading h2')).toBeVisible();
|
||
expect(reads).toHaveLength(1);
|
||
// The same file again reads nothing more (the cache is on).
|
||
await first.locator('.image-card-actions button').first().click();
|
||
await expect(panel(page).locator('.panel-heading h2')).toBeVisible();
|
||
await requestBarrier(page);
|
||
expect(reads).toHaveLength(1);
|
||
// The viewer's details use the same inspector: another file waits there too, and loads on request.
|
||
await imageCards(page).nth(1).locator('.image-open').click();
|
||
const viewerDetails = page.locator('#viewer-details');
|
||
await expect(viewerDetails.getByRole('status')).toHaveText('Metadata loads when you ask for it.');
|
||
expect(reads).toHaveLength(1);
|
||
await viewerDetails.getByRole('button', { name: 'Load metadata', exact: true }).click();
|
||
await expect(viewerDetails.locator('.panel-heading h2')).toBeVisible();
|
||
expect(reads).toHaveLength(2);
|
||
});
|
||
|
||
test('cache off rereads the current selection; on reuses the one current record', async ({ page }) => {
|
||
const reads = [];
|
||
page.on('request', item => { if (new URL(item.url()).pathname.startsWith(INSPECT_PATH)) reads.push(item.url()); });
|
||
for (const cache of [true, false]) {
|
||
if (!cache) {
|
||
await openAppearance(page);
|
||
await toggle(page, { 'metadata-cache': false });
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
await page.reload();
|
||
}
|
||
await openImages(page);
|
||
const info = imageCards(page).first().locator('.image-card-actions button').first();
|
||
await info.click();
|
||
await expect(panel(page).locator('.panel-heading h2')).toBeVisible();
|
||
await expect.poll(() => reads.length).toBeGreaterThan(0);
|
||
await requestBarrier(page);
|
||
reads.length = 0;
|
||
// Inspect the selected file twice more.
|
||
for (const _ of [1, 2]) {
|
||
const answered = cache ? null : page.waitForResponse(response => new URL(response.url()).pathname.startsWith(INSPECT_PATH));
|
||
await info.click();
|
||
if (answered) await answered;
|
||
await expect(panel(page).locator('.panel-heading h2')).toBeVisible();
|
||
}
|
||
await requestBarrier(page);
|
||
expect(reads, `cache ${cache}`).toHaveLength(cache ? 0 : 2);
|
||
}
|
||
});
|
||
|
||
test('paths hidden only changes display', async ({ page }) => {
|
||
const rows = async () => page.locator('#viewer-details details').filter({ hasText: 'File & provenance' }).locator('dt')
|
||
.evaluateAll(terms => terms.map(term => term.textContent));
|
||
const openViewer = async () => {
|
||
await openImages(page);
|
||
await imageCards(page).first().locator('.image-open').click();
|
||
const provenance = page.locator('#viewer-details details').filter({ hasText: 'File & provenance' });
|
||
await provenance.locator('summary').click();
|
||
await expect(provenance.locator('dl')).toBeVisible();
|
||
return provenance;
|
||
};
|
||
let provenance = await openViewer();
|
||
expect(await rows()).toContain('Path');
|
||
const before = { show: await provenance.getByRole('button', { name: /^Show .* in folder$/ }).count(),
|
||
download: await provenance.getByRole('link', { name: 'Download original', exact: true }).getAttribute('href') };
|
||
await page.keyboard.press('Escape');
|
||
await openAppearance(page);
|
||
await toggle(page, { paths: false });
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
provenance = await openViewer();
|
||
const shown = await rows();
|
||
expect(shown).not.toContain('Path');
|
||
expect(shown).toEqual(expect.arrayContaining(['Source', 'Size']));
|
||
// Everything else is as it was: the folder action and the original download stay.
|
||
expect(await provenance.getByRole('button', { name: /^Show .* in folder$/ }).count()).toBe(before.show);
|
||
await expect(provenance.getByRole('link', { name: 'Download original', exact: true })).toHaveAttribute('href', before.download);
|
||
});
|
||
|
||
test('video defaults reach the viewer', async ({ page }) => {
|
||
await openAppearance(page);
|
||
await toggle(page, { 'video-auto': true, 'video-muted': false, 'video-loop': false });
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
expect(await page.evaluate(async () => (await import('/prompt_manager/js/workspace/media-viewer.mjs')).readViewerPreferences()))
|
||
.toEqual({ videoAutoplay: true, videoMute: false, videoLoop: false });
|
||
const stored = await storedSettings(page);
|
||
expect([stored.videoAutoplay, stored.videoMute, stored.videoLoop]).toEqual([true, false, false]);
|
||
});
|
||
|
||
test('host fields round-trip through /settings with revision', async ({ page, request }) => {
|
||
const posts = [];
|
||
page.on('request', item => { if (item.method() === 'POST' && new URL(item.url()).pathname === SETTINGS_URL) posts.push(item.postDataJSON()); });
|
||
const before = await serverJson(request, SETTINGS_URL);
|
||
await openAppearance(page);
|
||
await expect(page.locator('#open-mode')).toHaveValue(before.settings.webui_display_mode);
|
||
await expect(page.locator('#timeout')).toHaveValue(String(before.settings.result_timeout));
|
||
// Only whole seconds from 0 to 300: anything else is highlighted and never sent.
|
||
for (const bad of ['301', '-1', '2.5']) {
|
||
await page.locator('#timeout').fill(bad);
|
||
await page.locator('#timeout').press('Tab');
|
||
await expect(page.locator('#timeout')).toHaveAttribute('aria-invalid', 'true');
|
||
await expect(statusOf(page)).toHaveText('Some changes were not saved. Review the highlighted settings.');
|
||
await expect(saveOf(page)).toHaveAttribute('aria-disabled', 'true');
|
||
}
|
||
await page.locator('#timeout').fill('0');
|
||
await page.locator('#timeout').press('Tab');
|
||
await expect(page.locator('#timeout')).not.toHaveAttribute('aria-invalid');
|
||
await page.locator('#open-mode').selectOption('popup');
|
||
await saveAppearance(page, 'Saved to the server configuration.');
|
||
expect(posts).toEqual([{ webui_display_mode: 'popup', result_timeout: 0, expected_revision: before.revision }]);
|
||
const after = await serverJson(request, SETTINGS_URL);
|
||
expect([after.settings.webui_display_mode, after.settings.result_timeout]).toEqual(['popup', 0]);
|
||
expect(after.revision).not.toBe(before.revision);
|
||
// No browser key was written for a host field.
|
||
expect(await storedSettings(page)).toBeNull();
|
||
});
|
||
|
||
test('server settings that cannot be read say so in their rows', async ({ page }) => {
|
||
await page.route(url => url.pathname === SETTINGS_URL, route => (route.request().method() === 'GET'
|
||
? route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ success: false, error: 'Injected failure' }) })
|
||
: route.continue()));
|
||
await page.goto(`${workspace}#/system/appearance`);
|
||
for (const id of ['open-mode', 'timeout']) {
|
||
const row = page.locator('#workspace-main .setting-row').filter({ has: page.locator(`#${id}`) });
|
||
await expect(row.locator('p.small')).toHaveText('Server settings could not be read.');
|
||
await expect(page.locator(`#${id}`)).toBeDisabled();
|
||
}
|
||
// The browser rows are this browser's, and work as before.
|
||
await expect(page.locator('#default-view')).toBeEnabled();
|
||
await expect(page.locator('#workspace-main .setting-row p.small')).toHaveCount(2);
|
||
});
|
||
|
||
test('stale revision shows the conflict status', async ({ page, request }) => {
|
||
await openAppearance(page);
|
||
// Another page saves after this one read the settings.
|
||
const current = await serverJson(request, SETTINGS_URL);
|
||
await expect(await request.post(SETTINGS_URL, { data: { result_timeout: 42, expected_revision: current.revision } })).toBeOK();
|
||
await page.locator('#open-mode').selectOption('popup');
|
||
await saveAppearance(page, 'Settings changed elsewhere. Reload this section to see them.');
|
||
await expect(page.locator('#open-mode')).toHaveAttribute('aria-invalid', 'true');
|
||
// The draft is kept and the section now shows the other page's value.
|
||
await expect(page.locator('#open-mode')).toHaveValue('popup');
|
||
await expect(page.locator('#timeout')).toHaveValue('42');
|
||
expect((await serverJson(request, SETTINGS_URL)).settings.webui_display_mode).toBe('newtab');
|
||
// With the reloaded revision, Save succeeds.
|
||
await saveAppearance(page, 'Saved to the server configuration.');
|
||
expect((await serverJson(request, SETTINGS_URL)).settings.webui_display_mode).toBe('popup');
|
||
});
|
||
|
||
test('reload keeps saved values; a new tab reads them', async ({ page, context }) => {
|
||
await openAppearance(page);
|
||
await page.locator('#image-quality').selectOption('high');
|
||
await toggle(page, { 'card-details': false });
|
||
await page.locator('#open-mode').selectOption('popup');
|
||
await saveAppearance(page, 'Saved in this browser. Saved to the server configuration.');
|
||
await page.reload();
|
||
await expect(page.locator('#timeout')).toBeEnabled();
|
||
await expect(page.locator('#image-quality')).toHaveValue('high');
|
||
await expect(page.locator('#card-details')).not.toBeChecked();
|
||
await expect(page.locator('#open-mode')).toHaveValue('popup');
|
||
const other = await context.newPage();
|
||
await openAppearance(other);
|
||
await expect(other.locator('#image-quality')).toHaveValue('high');
|
||
await expect(other.locator('#card-details')).not.toBeChecked();
|
||
// A change saved in one tab reaches the other's clean controls; a draft it overtakes is flagged and kept.
|
||
await other.locator('#density').selectOption('large');
|
||
await page.locator('#density').selectOption('compact');
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
await expect(other.locator('#density')).toHaveValue('large');
|
||
await expect(other.locator('#settings-status')).toHaveText('Settings changed elsewhere. Reload this section to see them.');
|
||
await expect(other.locator('#density')).toHaveAttribute('aria-invalid', 'true');
|
||
await page.locator('#image-quality').selectOption('low');
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
await expect(other.locator('#image-quality')).toHaveValue('low');
|
||
await other.close();
|
||
});
|
||
|
||
test('a change another tab saved while System was closed is a conflict on return, never saved over silently', async ({ page, context }) => {
|
||
await openAppearance(page);
|
||
await page.locator('#density').selectOption('compact');
|
||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||
// Leave System for Images: the draft stays for the page session, but System no longer listens.
|
||
await page.locator('#primary-nav a[data-route="images"]').click();
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
const other = await context.newPage();
|
||
await openAppearance(other);
|
||
await other.locator('#density').selectOption('large');
|
||
await saveAppearance(other, 'Saved in this browser.');
|
||
await other.close();
|
||
// Back in System: the draft is kept and flagged, and nothing was written over the other tab's value.
|
||
await page.evaluate(() => { location.hash = '#/system/appearance'; });
|
||
await expect(page.locator('#workspace-main .settings-layout > section.surface > h2')).toHaveText('Browsing & display');
|
||
await expect(statusOf(page)).toHaveText('Settings changed elsewhere. Reload this section to see them.');
|
||
await expect(page.locator('#density')).toHaveAttribute('aria-invalid', 'true');
|
||
await expect(page.locator('#density')).toHaveValue('compact');
|
||
expect((await storedSettings(page)).workspaceDensity).toBe('large');
|
||
// Saving after the conflict was shown is an explicit choice: it wins.
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
expect((await storedSettings(page)).workspaceDensity).toBe('compact');
|
||
await expect(page.locator('#density')).not.toHaveAttribute('aria-invalid');
|
||
});
|
||
|
||
test('a browser that refuses storage is saved for this tab only, never "Saved"', async ({ page }) => {
|
||
await openAppearance(page);
|
||
await page.evaluate(() => {
|
||
Storage.prototype.setItem = function setItem() { throw new DOMException('Quota exceeded', 'QuotaExceededError'); };
|
||
});
|
||
await page.locator('#default-view').selectOption('list');
|
||
await saveAppearance(page, 'Saved for this tab only; browser storage is unavailable.');
|
||
expect(await storedSettings(page)).toBeNull();
|
||
// This tab's next Images visit still uses it.
|
||
await page.locator('#primary-nav a[data-route="images"]').click();
|
||
await expect(imageCards(page).first()).toBeVisible();
|
||
await expect(page.locator('.image-grid')).toHaveAttribute('data-layout', 'list');
|
||
});
|
||
|
||
test('added rows reach their consumers', async ({ page }) => {
|
||
await openImages(page);
|
||
await expect(imageCards(page).first().locator('.media-info h3')).toBeVisible();
|
||
await openAppearance(page);
|
||
await toggle(page, { 'card-details': false, 'viewer-details': true });
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
await page.reload();
|
||
await openImages(page);
|
||
// Show image details on cards off: no title or file line; Info and Tag stay.
|
||
const card = imageCards(page).first();
|
||
await expect(card.locator('.media-info h3')).toBeHidden();
|
||
await expect(card.locator('.image-card-actions button')).toHaveCount(2);
|
||
// Collapse viewer details by default: the viewer opens with its details hidden behind one toggle.
|
||
await card.locator('.image-open').click();
|
||
const details = page.locator('#viewer-details');
|
||
await expect(page.locator('#viewer-dialog')).toBeVisible();
|
||
await expect(details).toBeHidden();
|
||
const show = page.locator('#viewer-toolbar').getByRole('button', { name: 'Show details', exact: true });
|
||
await expect(show).toHaveAttribute('aria-expanded', 'false');
|
||
await show.click();
|
||
await expect(details).toBeVisible();
|
||
await expect(page.locator('#viewer-toolbar').getByRole('button', { name: 'Hide details', exact: true })).toHaveAttribute('aria-expanded', 'true');
|
||
});
|
||
|
||
test('reset restores defaults without touching other keys', async ({ page }) => {
|
||
await page.goto(`${workspace}#/system/appearance`);
|
||
await page.evaluate(() => localStorage.setItem('gallerySettings', JSON.stringify({ gridColumns: 5, defaultLimit: 200,
|
||
thumbnailPromptDismissed: 'kept', workspaceLayout: 'list', videoMute: false, showImageInfo: false })));
|
||
await page.reload();
|
||
await expect(page.locator('#timeout')).toBeEnabled();
|
||
await expect(page.locator('#default-view')).toHaveValue('list');
|
||
const reset = page.locator('#workspace-main .operation').filter({ hasText: 'Reset display defaults' }).getByRole('button', { name: 'Reset', exact: true });
|
||
await reset.click();
|
||
await expect(page.locator('#default-view')).toHaveValue('grid');
|
||
await expect(page.locator('#video-muted')).toBeChecked();
|
||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||
await saveAppearance(page, 'Saved in this browser.');
|
||
const stored = await storedSettings(page);
|
||
expect(stored).toEqual({ gridColumns: 5, defaultLimit: 200, thumbnailPromptDismissed: 'kept', workspaceLayout: 'grid',
|
||
videoMute: true, showImageInfo: true });
|
||
});
|