fix(system): flag changes made while System was closed and keep embedded galleries fixed

Final review fixes for System S3 (Appearance):

- I1: the on-demand metadata deviation is D124 (TESTING.md, inspector
  markers); TESTING.md names the spec that pins it, since no concept
  comparison renders that state.
- I2: System checks the display defaults for conflicts on mount, not only
  on storage events, and a browser write refuses a draft another page
  overtook, so a draft is never saved over another tab's value without
  the conflict status first. New two-tab spec.
- I3: the layout and size defaults start the Images page only; embedded
  galleries (a prompt history's Shared gallery and dialogs) keep
  Grid/Comfortable.
- M1: host rows whose /settings read failed say "Server settings could
  not be read."
- M2: a rejected timeout shows the "Some changes were not saved" status.
- M3: the browser loads on mount and on storage events never reject
  unhandled.
- M4: the next accepted write stores the tab-only changes and clears the
  overlay.
- M5: cache off never re-reads a source-changed selection, and refresh()
  never loads a deferred one.
- M6: the System fixture refuses a config.json outside its temp root and
  restores it with os.replace.
- M7: the inspection read counts wait on a request barrier, not frames.
- M8 recorded as an open saved-views question in TESTING.md.
This commit is contained in:
Vito Sansevero
2026-10-23 06:55:02 -07:00
parent 324b720db7
commit 4d554fbf40
16 changed files with 319 additions and 51 deletions
+2 -2
View File
@@ -197,7 +197,7 @@ function prefixedChip(prefix, text) {
* `variant: 'full'` (the viewer's `#viewer-details`, imageDetails(i, true)) leaves out the cover and adds "File &
* provenance" and "Workflow & raw metadata" with the downloads. `inline: true` means `panel`; neither means `full`.
*/
/** D-NEW-S3-1: the inspector's line while "Load metadata on selection" is off. */
/** D124: the inspector's line while "Load metadata on selection" is off. */
export const DEFERRED_TEXT = 'Metadata loads when you ask for it.';
export function mountFileInspector(container, {api, sender, parentScope, variant, inline = false, promptContext = '', onTagFilter, onRetry, onRefresh, onLoad, onInteraction = () => {}, copyFallback = openCopyFallback}) {
@@ -239,7 +239,7 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
function render(state) {
const inner = el('div', undefined, full ? undefined : 'detail-inner');
if (state.loading || state.error) {container.append(inner); statusView(state, inner); return;}
// D-NEW-S3-1: "Load metadata on selection" is off, so the file's details wait for an explicit request.
// D124: "Load metadata on selection" is off, so the file's details wait for an explicit request.
if (state.deferred) {
container.append(inner);
const status = el('p', DEFERRED_TEXT, 'small'); status.setAttribute('role', 'status'); inner.append(status);
+3 -1
View File
@@ -122,7 +122,9 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
const prior = embedded || saved || favorites ? null : lastVisit;
// A stale visit keeps its filters, layout and size, and lists again instead of restoring (M6).
const visit = prior?.stale ? null : prior;
const start = initialImagesView({prior, saved, preferences});
// The layout and size defaults are the Images page's: an embedded gallery (a prompt history's, its dialogs) has no
// toolbar to change them, so it keeps its fixed Grid/Comfortable. The metadata and card defaults apply everywhere.
const start = initialImagesView({prior, saved, preferences:embedded ? null : preferences});
let density = start.density;
let metrics = {...INITIAL_METRICS};
let layout = start.layout, selection = visit?.selection || null, frame = 0, loadFrame = 0, restoreFrame = 0, observer;
+5 -3
View File
@@ -350,7 +350,8 @@ const emptyState = () => ({ loading: false, error: false, deferred: false, recor
* One selection's inspection. #249 System S3 (Appearance): `autoLoad: false` ("Load metadata on selection" off) makes a
* selection publish `deferred` instead of reading, and `load()` reads it once on request; `cache: false` ("Cache
* metadata in this browser" off) re-reads the selected file when it is selected again, where the default reuses the one
* current record. A read in flight is shared either way.
* current record. A read in flight is shared either way, and a file whose source changed is never re-read by selecting
* it again (as `retry()` and `refresh()` refuse).
*/
export function createInspectionController({ api, extractFacts, adapter = rootedFileAdapter, autoLoad = true, cache = true }) {
let state = Object.freeze(emptyState()), current = null, pending = null, disposed = false;
@@ -375,7 +376,7 @@ export function createInspectionController({ api, extractFacts, adapter = rooted
try {
adapter.validate(image);
const scope = adapter.scope(image), key = adapter.key(image), path = adapter.inspectionPath(image);
if (current?.key === key && current.scope === scope && current.path === path && (cache || state.loading || state.deferred)) return pending;
if (current?.key === key && current.scope === scope && current.path === path && (cache || state.loading || state.deferred || state.refreshRequired)) return pending;
selected = { key, scope, path };
} catch {
// The loader publishes validation errors after invalidating the previous source.
@@ -396,7 +397,8 @@ export function createInspectionController({ api, extractFacts, adapter = rooted
},
/** Re-read the selected file keeping the shown record until the answer (a retry when none is shown). */
refresh() {
if (disposed || !hasAttempt || state.refreshRequired) return;
// A deferred selection loads only through `load()` (the user's "Load metadata").
if (disposed || !hasAttempt || state.refreshRequired || state.deferred) return;
return read(attempted, { quiet: Boolean(state.record) && !state.loading && !state.error });
},
clear() {
+4 -3
View File
@@ -11,7 +11,7 @@
* - `writePreferences(dirty, getStorage, {baseline})` → `{persisted, conflicts}`: re-reads the stored object and writes
* back only the dirty keys, every other key byte-for-byte as stored. A write the browser refused (denied storage, a
* full quota) leaves the stored bytes as they were and keeps the change for this tab only, so every reader in this
* tab still sees it. `conflicts` lists the dirty keys another page changed since `baseline` was read; the explicit
* tab still sees it; the next write storage accepts stores those changes too. `conflicts` lists the dirty keys another page changed since `baseline` was read; the explicit
* save still wins.
* - `subscribePreferences(win, onChange, getStorage)` → unsubscribe: `onChange(readPreferences())` after another page
* changed the settings (a `storage` event).
@@ -82,12 +82,13 @@ export function writePreferences(dirty, getStorage = defaultStorage, { baseline
const current = pick(normalizer()(stored));
const conflicts = baseline ? Object.keys(dirty).filter(key => Object.hasOwn(baseline, key) && current[key] !== baseline[key]) : [];
try {
storage.setItem(PREFERENCES_KEY, JSON.stringify({ ...stored, ...dirty }));
// The changes this tab could not store before are stored with this one, so "Saved" is true for all of them.
storage.setItem(PREFERENCES_KEY, JSON.stringify({ ...stored, ...Object.fromEntries(tabOnly), ...dirty }));
} catch {
keep();
return { persisted: false, conflicts };
}
for (const key of Object.keys(dirty)) tabOnly.delete(key);
tabOnly.clear();
return { persisted: true, conflicts };
}
+16 -3
View File
@@ -13,12 +13,15 @@
* (`showImageInfo`), "Collapse viewer details by default" (`sidebarCollapsedByDefault`) and the operation "Reset
* display defaults", which drafts the gallery's defaults for these browser rows and touches no other key.
*
* Controls follow the store: a value read later (the host settings, another tab's change) repaints them.
* Controls follow the store: a value read later (the host settings, another tab's change) repaints them. A host row
* whose value could not be read stays disabled and says so ("Server settings could not be read.").
*/
import { settingRow, operationRow } from './system-controls.mjs';
import { preferenceDefaults } from './preferences.mjs';
export const RESULT_TIMEOUT_MAX = 300;
/** A host row's line while the server settings could not be read (its control stays disabled). */
export const HOST_UNAVAILABLE = 'Server settings could not be read.';
const BOOLEAN = Object.freeze({ type: 'toggle' });
/**
@@ -115,7 +118,7 @@ export function mountAppearance(container, { scope, drafts }) {
surface.append(node);
const input = controlOf(node, id);
input.dataset.key = key;
controls.push({ input, control, domain, key });
controls.push({ input, control, domain, key, text: node.children[0], note: null });
}
surface.append(operationRow({ title: 'Reset display defaults',
description: 'Restore this browser’s display defaults, then save. Other settings are kept.', label: 'Reset', scope,
@@ -123,7 +126,17 @@ export function mountAppearance(container, { scope, drafts }) {
const defaults = preferenceDefaults();
for (const key of DISPLAY_KEYS) drafts.set('browser', key, defaults[key]);
} }));
const repaint = () => { for (const { input, control, domain, key } of controls) paint(input, control, drafts.get(domain, key)); };
const repaint = () => {
const unavailable = drafts.hostState?.() === 'failed';
for (const row of controls) {
const value = drafts.get(row.domain, row.key);
paint(row.input, row.control, value);
if (row.domain !== 'host') continue;
if (unavailable && value === undefined) {
if (!row.note) { row.note = el('p', HOST_UNAVAILABLE, 'small'); row.text.append(row.note); }
} else if (row.note) { row.note.remove(); row.note = null; }
}
};
scope.cleanup(drafts.subscribe(repaint));
repaint();
return [surface];
+18 -5
View File
@@ -15,8 +15,9 @@
* the page session (Q10a): a section left and opened again shows them, and a reload of its values keeps them.
*
* Adapters: `readBrowser()` and `readRuntime()` return the values; `readHost()` returns `{values, revision}`.
* `writeBrowser(changes)` returns `{persisted}` (false: kept for this tab only), `writeHost(changes,
* {expected_revision})` the settings response (`{success, persisted, revision}`), `writeRuntime(changes)` anything;
* `writeBrowser(changes)` returns `{persisted}` (false: kept for this tab only) and throws an error with `code:
* 'settings-changed'` when another page changed a drafted value (a conflict: the browser values are read again),
* `writeHost(changes, {expected_revision})` the settings response (`{success, persisted, revision}`), `writeRuntime(changes)` anything;
* a write that throws failed.
*/
export { SYSTEM_SECTIONS, isSystemSection } from './state.mjs';
@@ -64,6 +65,7 @@ export function createSystemDrafts(adapters) {
const failedKeys = { browser: new Set(), host: new Set(), runtime: new Set() };
const listeners = new Set();
let revision = null;
let hostRead = 'pending';
let outcome = null;
let saving = null;
@@ -78,6 +80,7 @@ export function createSystemDrafts(adapters) {
const read = await adapters.readHost();
values = read?.values ?? {};
revision = read?.revision ?? null;
hostRead = 'loaded';
} else {
values = await (domain === 'browser' ? adapters.readBrowser() : adapters.readRuntime());
}
@@ -159,8 +162,11 @@ export function createSystemDrafts(adapters) {
}
}
/** Read the host values again; a failed read leaves host saves refused until one succeeds. */
const reloadHost = () => load('host').then(() => true, () => false);
/**
* Read the host values again; a failed read leaves host saves refused until one succeeds, and `hostState()` says
* so (System S3: the host rows show that the server settings could not be read).
*/
const reloadHost = () => load('host').then(() => true, () => { hostRead = 'failed'; notify(); return false; });
/** Save the dirty domains in order; a Save pressed while one runs joins it. */
function save() {
@@ -170,6 +176,7 @@ export function createSystemDrafts(adapters) {
for (const domain of DRAFT_DOMAINS) result[domain] = await saveDomain(domain);
// Settings changed elsewhere: read them (and their revision), keeping the drafts (Q10).
if (result.host === 'conflict') await reloadHost();
if (result.browser === 'conflict') await load('browser').catch(() => {});
return result;
})().then(result => {
saving = null;
@@ -180,11 +187,15 @@ export function createSystemDrafts(adapters) {
return saving;
}
/** A value the control could not take (System S3: a timeout outside 0–300): no draft, and the control is highlighted. */
/**
* A value the control could not take (System S3: a timeout outside 0–300): no draft, the control is highlighted and
* the status says a change was not saved.
*/
function reject(domain, key) {
requireDomain(domain);
drafts[domain].delete(key);
failedKeys[domain].add(key);
outcome = { [domain]: 'failed' };
notify();
}
@@ -203,6 +214,8 @@ export function createSystemDrafts(adapters) {
return {
load,
reloadHost,
/** Whether the host values were read: `pending`, `loaded`, or `failed` (the last read failed). */
hostState: () => hostRead,
reject,
conflict,
/** The saved values of a domain (its last read or save), not the drafts. */
+22 -9
View File
@@ -16,7 +16,7 @@ import { createSystemDrafts, DRAFT_DOMAINS } from './system-state.mjs';
import { sectionNav } from './system-controls.mjs';
import { healthNotice, mountOverview } from './system-overview.mjs';
import { mountAppearance } from './system-appearance.mjs';
import { readPreferences, reconcilePreferences, subscribePreferences, writePreferences } from './preferences.mjs';
import { displayPreferences, readPreferences, reconcilePreferences, subscribePreferences, writePreferences } from './preferences.mjs';
const SETTINGS_URL = '/prompt_manager/settings';
const ADMIN = Object.freeze({ href: '/prompt_manager/admin', label: 'Open existing administration' });
@@ -57,7 +57,14 @@ export function systemDrafts(api) {
drafts ??= createSystemDrafts({
readBrowser: () => readPreferences().values,
readRuntime: () => ({}),
writeBrowser: changes => ({ persisted: writePreferences(changes).persisted }),
writeBrowser: changes => {
// Another page changed a drafted value since this tab read it, and no storage event told it yet: refuse,
// so the store keeps the draft, flags it and reads the values again; the next Save is an explicit choice.
const baseline = drafts.saved('browser');
const { conflicts } = reconcilePreferences({ baseline, drafts: changes, next: readPreferences().values });
if (conflicts.length) throw Object.assign(new Error('Settings changed elsewhere'), { code: 'settings-changed' });
return { persisted: writePreferences(changes, undefined, { baseline }).persisted };
},
writeRuntime: undelivered,
async readHost() {
const result = await api.get(SETTINGS_URL, { cache: 'no-store' });
@@ -110,18 +117,24 @@ export const DELIVERED_SECTIONS = Object.freeze({
*
* The host values are read on mount (and by the store again after a conflict), so a save carries the current revision;
* until a read returned one, a host save fails without a request (system-state.mjs). The browser values are read on
* mount and again whenever another page changes them (a `storage` event).
* mount and again whenever another page changes them (a `storage` event). Either way a value another page changed
* under one of this tab's drafts flags that draft (D92's conflict status), including a change made while System was
* not mounted (the drafts outlive it, Q10).
*/
export function mountSystem(main, api, scope, { section, activity, sections = DELIVERED_SECTIONS, navigate = navigateTo }) {
const store = systemDrafts(api);
store.reloadHost();
store.load('browser');
// Another tab or the legacy gallery changed the display defaults: clean values follow it; a draft it overtook stays
// and is flagged (D92's conflict status).
scope.cleanup(subscribePreferences(window, next => {
const { conflicts } = reconcilePreferences({ baseline: store.saved('browser'), drafts: store.changes('browser'), next: next.values });
store.load('browser').then(() => store.conflict('browser', conflicts));
}));
// and is flagged (D92's conflict status). `next` is null when the values cannot be read (no gallery-settings.js).
const reconcile = next => {
const baseline = store.saved('browser');
// The first mount has read nothing yet, so nothing can have been overtaken.
const conflicts = next && Object.keys(baseline).length
? reconcilePreferences({ baseline, drafts: store.changes('browser'), next }).conflicts : [];
store.load('browser').then(() => store.conflict('browser', conflicts), () => {});
};
reconcile(displayPreferences());
scope.cleanup(subscribePreferences(window, next => reconcile(next.values)));
const nav = sectionNav({ label: 'System sections', sections: SYSTEM_SECTIONS, active: section, scope,
onSelect: id => navigate(`#/system/${id}`) });
const layout = el('div', undefined, 'settings-layout');