* refactor(thumbnails): one resolver for where previews live on disk (#320) Add py/api/preview_store.py: the store of a source, a preview's path, URL parts to disk, containment (owns), a write generation and the lock around every preview's final rename. Every preview reader, writer and remover now asks it instead of joining <source>/thumbnails by hand: serve, on-demand, capture (its path resolved when the write starts), the after-scan queue, the thumbnail plans and job payloads, clear, the temp sweep, History covers, the auto-tag listing and the owned-preview lookups. Source mode only: every path is the one built before, so nothing changes on disk or on the wire. A structural test keeps new thumbnails joins out of the backend. * refactor(thumbnails): keep the after-scan queue's store rule and pin the write lock (#320) A planned target keeps the plan's own containment rule (inside the store, as the thumbnail job writes it); captures keep the serve rule. The structural test also covers PREVIEW_FOLDER joins and the repo-root modules; the write-lock test asserts the lock instead of waiting on a timer; new tests cover nested roots in the after-scan queue and a legacy upper-case preview served through the resolver. * feat(thumbnails): keep previews in one folder, set from config.json (#320) thumbnails.location in config.json can now name one folder for every source's previews: <folder>/<source key>/<rel>_thumb<ext>. A source key is a readable slug plus a short hash of the source's identity, stored in the folder's marker (.promptmanager-thumbnails.json) with the install that made it. Serving, on-demand and capture writes, listings, clear, delete, duplicates, the temp sweep and History covers all follow it; a leftover in <source>/thumbnails is never served and other text under thumbnails/ is refused. A missing, unplugged or foreign folder is unavailable (a probe checks it every 5 s within 2 s; a stalled or failing store call flips it at once): originals are served, nothing is written anywhere, the folder is never re-created, and generate, convert and clear answer 409 location-unavailable. A bad config value is unavailable too, never a fall-back to the sources. No UI yet: POST /settings refuses thumbnail_location (409 location-needs-move); GET /settings reports it with its path, the thumbnail status without one. Sources inside or around the folder and a library move into it are refused. * fix(thumbnails): never follow a marker or a link out of the thumbnail folder (#320) Marker keys are data, not paths: only a single <slug>-<hex> folder name is ever joined onto the thumbnail folder; anything else is dropped and logged. Every preview write and delete passes one ownership check (below a key folder, lexically and resolved, no link, junction or reparse point on the way); make_parent refuses anything else and writes nothing while the folder lacks this install's marker (an unmounted mount point). Clear never descends into a junction. The configured location is in force before any request (unchecked folder mode is unavailable), and a startup check that fails leaves it invalid, never the sources. Older listings that run on the event loop no longer touch the store in folder mode. A leftover under another case of thumbnails/ on a case-insensitive disk is refused too. * test(memory): let the musl test fake os.confstr on Windows (#523) The portability run on main fails since #523: Windows has no os.confstr, so patching it without create=True raises before the test runs. * feat(thumbnails): move thumbnails between the sources and one folder (#320) POST /images/thumbnails/plan reviews a move (what is copied, removed and left, free space, too-long Windows paths, sources no longer listed) and hands out a token; POST /jobs/thumbnails {mode: move} runs it as a thumbnails job: hold automatic previews, copy and check every preview on the job pool, switch with one config commit that records the old copies, then remove them. Per-file errors still switch; a folder-wide error, a cancel before the switch or a crash leaves nothing changed (a journal is undone at the next start); old copies that could not go are removed by a finishing job at the next start. Leaving a folder removes the previews of this install's sources that are no longer listed (Q320-8). Recreate folder and Use this folder answer an unavailable folder; the Thumbnail maintenance scope prune removes the thumbnails of removed sources. * feat(system): choose where thumbnails are kept and move them (#320) System › Sources & scans gains the Thumbnail location row (D196): Inside each source or One folder, the folder path, the status line and Review move…, whose review (D197) lists what is copied, removed and left before Move thumbnails starts; a refused folder is explained under the field, a folder of your own asks for a confirmation first. Activity shows a move and a prune with their own tiles and step line (D198). An unavailable folder shows a notice on Overview and Sources & scans with Recreate folder or Use this folder (D199). Thumbnail maintenance offers Remove thumbnails of removed sources in folder mode (D200), and Move library's review says where the thumbnails stay (D201). Closes #320 * fix(thumbnails): keep a move's own previews and never walk out of a store (#320) A cleanup that waited from an earlier move never names a key folder the new move just filled, so moving back keeps the previews. Removing empty folders walks top-down and never into a link or junction. Any error while copying undoes the copies; once the switch is committed, a journal that cannot be removed no longer undoes it. Hand-edited cleanup entries and marker keys never name a folder outside the stores; removal stops at interpreter exit. The path field carries aria-invalid with its reason, and a review that went stale reviews again. * test(thumbnails): cover the prune scope, the Overview notice and the space refusal (#320) The frontend coverage gate counted the new branches of thumbnail maintenance, the Activity views, the notices' Change location and the api-client's space refusal as uncovered; page and unit tests now drive them. * fix(thumbnails): report removals that fail and explain the quiet excepts (#320) An old thumbnail the finishing move cannot remove (held open on Windows) is now an error row of the job with its path, and logged; a failed copy's temp that cannot go is logged with its path. Every except that only passes says why, and the thread runners say their caller re-raises. * fix(thumbnails): never plan or delete through a linked key folder (#320) Review finding P1 on #591: in folder mode a source key folder that is a link or junction to a folder outside was still handed to the planner, so Convert outdated could remove an older-format file outside the thumbnail folder. ensure_store now refuses a linked store before any planning, and each removal of an old preview passes may_write at the moment it runs. * fix(thumbnails): the temp sweep never walks into a link (#320) Review finding P2 on #591: Clear thumbnails and the startup sweep removed crashed-write temps with a plain os.walk, which on Windows walks into a junction even without followlinks. The sweeper now skips a folder that is a link, junction or reparse point (the top one too), and each temp passes may_write before it is removed. * fix(thumbnails): lock the folder marker across processes (#320) Review finding P2 on #591: two installs sharing one thumbnail folder could each read the marker, add a key and replace it, so the last writer dropped the other's key. write_marker now re-reads, changes and replaces the marker under a lock file made with O_CREAT | O_EXCL beside it (atomic on shares, unlike flock); a lock older than 30 s, left by a writer that died, is taken over, and a wait past 1.5 s fails as a TimeoutError like an unreachable folder. Tested with three processes adding keys at once. * test(thumbnails): cover the space refusal, Overview's Use this folder and the prune review (#320) The frontend coverage floors of activity-kinds, system-overview and thumbnail-review: a disk without the space shows the review but cannot move (a fixture route fakes the free space), Use this folder on Overview reloads the host values, the prune review's text and rows are pure functions with unit tests, and Overview takes the System drafts it is always mounted with. * fix(thumbnails): never copy through a linked folder; refuse a target inside the folder in use (#320) Moving back to Inside each source followed an existing linked folder in the destination and could replace a file outside the source (Codex P1). A target nested inside the thumbnail folder in use was accepted, and the old-copy cleanup then removed the previews just copied there (Codex P2). Every copy now checks the whole destination chain for links, also when the folders exist, and the move refuses a folder inside the one in use with location-inside-current. The cancelled branches no longer mix explicit and implicit returns (code-quality note). * fix(system): one full stop in the move-back review (#320) * fix(thumbnails): a folder check answers for the folder as it is now (#320) Probe.check() joined a check already running, or a finished one nobody had collected. A folder deleted right after configure() woke the probe therefore stayed available until the next probe, which failed the Overview notice spec in the merge queue. It now waits for a running check and starts a new one, still never two at once, and a stuck check still times out. The spec also asserts the fixture's removal took effect.
223 lines
12 KiB
JavaScript
223 lines
12 KiB
JavaScript
/**
|
||
* Native System (#249 System S2 Task 5): the concept's `renderSystem` shell (app.js 698–706) at `#/system/<section>`.
|
||
* Under the page heading it renders the section nav (`.section-nav`, one button per section, the shown one
|
||
* `aria-pressed`; a press navigates to its hash), then `.settings-layout` with the section's body and the Save row
|
||
* (`span.small#settings-status` + "Save preferences"). D92: no "Sample configuration" chip, the status copy is
|
||
* truthful and "Save preferences" is aria-disabled while nothing is unsaved. Every section is native: Overview
|
||
* (system-overview.mjs), Appearance (system-appearance.mjs), Sources & scans (system-sources.mjs), Integrations
|
||
* (system-integrations.mjs), Auto-tagging (system-tagging.mjs), Maintenance (system-maintenance.mjs), Backup & export
|
||
* (system-backups.mjs) and Diagnostics & logs (system-diagnostics.mjs, S12, which retired the D94 hand-off panel).
|
||
*
|
||
* Switching sections keeps the shell (and focus on the pressed button) and disposes the old section's scope, so its
|
||
* listeners and timers never outlive it. The drafts are module-level (Q10): they live for the page session.
|
||
*/
|
||
import { createButton, createScope } from '../shared/toolkit/core.js';
|
||
import { LEGACY_PAGES, SYSTEM_SECTIONS, navigateTo } from './state.mjs';
|
||
import { createSystemDrafts, DRAFT_DOMAINS, INVALID_SETTING_CODE } from './system-state.mjs';
|
||
import { sectionNav } from './system-controls.mjs';
|
||
import { mountOverview } from './system-overview.mjs';
|
||
import { mountAppearance } from './system-appearance.mjs';
|
||
import { mountSources } from './system-sources.mjs';
|
||
import { mountMaintenance } from './system-maintenance.mjs';
|
||
import { mountBackups } from './system-backups.mjs';
|
||
import { mountTagging } from './system-tagging.mjs';
|
||
import { mountDiagnostics, runtimeBody, runtimeValues, CONFIG_URL as LOG_CONFIG_URL } from './system-diagnostics.mjs';
|
||
import { LORA_ENABLE_URL, LORA_STATUS_URL, loraValues, mountIntegrations, writeHostInParts } from './system-integrations.mjs';
|
||
import { busyToast } from './activity-scan.mjs';
|
||
import { showWorkspaceToast } from './toast.mjs';
|
||
import { displayPreferences, readPreferences, reconcilePreferences, subscribePreferences, writePreferences } from './preferences.mjs';
|
||
|
||
const SETTINGS_URL = '/prompt_manager/settings';
|
||
|
||
let drafts = null;
|
||
// The Activity store of the System page shown last: a refused host save that does not name its job reads the list.
|
||
let jobs = null;
|
||
|
||
/** The running job a 409 `busy` named, else the first running one from a fresh list read (the load never throws). */
|
||
async function runningJob(error) {
|
||
if (error?.running) return error.running;
|
||
await jobs.load();
|
||
return jobs.running()[0];
|
||
}
|
||
|
||
function el(tag, className) {
|
||
const node = document.createElement(tag);
|
||
node.className = className;
|
||
return node;
|
||
}
|
||
|
||
/**
|
||
* S11 (CUJ 2a): a `/settings` save that carried Auto-tagging values (`autotag_*` keys in `body`) and was refused with a
|
||
* plain 400 naming the setting ("General-tag confidence must be between 0 and 1."): mark it `invalid-setting`, so the
|
||
* Save row shows the server's sentence. Every other section's refusal is left as it was (the generic copy).
|
||
*/
|
||
export function settingRefusal(error, body) {
|
||
const tagging = Object.keys(body ?? {}).some(key => key.startsWith('autotag_'));
|
||
if (tagging && error?.status === 400 && error.refused === true && !error.code && typeof error.message === 'string'
|
||
&& error.message) {
|
||
error.code = INVALID_SETTING_CODE;
|
||
}
|
||
return error;
|
||
}
|
||
|
||
/**
|
||
* The page session's drafts (Q10). The browser domain is this browser's display defaults (preferences.mjs): a write
|
||
* says whether storage kept it, so the status never claims "Saved in this browser." for a change only this tab holds.
|
||
* The host domain reads and saves the server settings with their revision (#220). The runtime domain is the running
|
||
* server's log level and console setting (S12-9, `/logs/config`): applied until the server restarts.
|
||
*/
|
||
export function systemDrafts(api) {
|
||
drafts ??= createSystemDrafts({
|
||
readBrowser: () => readPreferences().values,
|
||
readRuntime: async () => runtimeValues((await api.get(LOG_CONFIG_URL, { cache: 'no-store' })).config),
|
||
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: changes => api.post(LOG_CONFIG_URL, runtimeBody(changes)),
|
||
async readHost() {
|
||
// S10: the LoRA state rides along; when it cannot be read its values stay missing (Integrations says so)
|
||
// and every other host setting still loads.
|
||
const [result, lora] = await Promise.all([api.get(SETTINGS_URL, { cache: 'no-store' }),
|
||
api.get(LORA_STATUS_URL, { cache: 'no-store' }).catch(() => null)]);
|
||
// The store reads a missing value as none and a missing revision as unreadable (no host save). #317: which
|
||
// thumbnail formats the server can write rides along as a read-only value (never drafted or sent).
|
||
// #320: where previews live rides along the same way (read-only; only Move thumbnails changes it).
|
||
return { values: { ...result.settings, thumbnail_encoders: result.thumbnail_encoders,
|
||
thumbnail_location: result.thumbnail_location, ...(lora ? loraValues(lora) : {}) },
|
||
revision: result.revision };
|
||
},
|
||
async writeHost(changes, { expected_revision }) {
|
||
// S10: the LoRA keys save through /lora/enable, the rest through /settings, each with the current revision;
|
||
// a save where only one part was written reports which (writeHostInParts, review I3).
|
||
try {
|
||
return await writeHostInParts({ changes, saved: drafts.saved('host'), expected_revision,
|
||
postLora: body => api.post(LORA_ENABLE_URL, body),
|
||
postSettings: body => api.post(SETTINGS_URL, body).catch(error => { throw settingRefusal(error, body); }) });
|
||
} catch (error) {
|
||
// A sources change waits for a running record-changing job (S4): name it, as a refused start does (D57).
|
||
if (error?.code === 'busy') showWorkspaceToast(busyToast(await runningJob(error)));
|
||
throw error;
|
||
}
|
||
},
|
||
});
|
||
return drafts;
|
||
}
|
||
|
||
/** D92: highlight the controls of the settings the last save could not save. */
|
||
function markFailed(layout, store) {
|
||
const failed = new Set(DRAFT_DOMAINS.flatMap(domain => [...store.failed(domain)]));
|
||
for (const control of layout.querySelectorAll('[data-setting]')) {
|
||
// A row's control names its stored key when that differs from the row id (Appearance's `data-key`).
|
||
if (failed.has(control.dataset.key ?? control.dataset.setting)) control.setAttribute('aria-invalid', 'true');
|
||
else control.removeAttribute('aria-invalid');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Every System section: Overview (S2 Task 6), Appearance (S3 Task 8), Sources & scans (S4 Task 11), Integrations (S10
|
||
* Task 27), Auto-tagging (S11 Task 6, #328), Maintenance (S7 Task 19), Backup & export (S9 Task 24) and Diagnostics &
|
||
* logs (S12, #329).
|
||
*/
|
||
export const DELIVERED_SECTIONS = Object.freeze({
|
||
overview: mountOverview,
|
||
appearance: mountAppearance,
|
||
sources: mountSources,
|
||
integrations: mountIntegrations,
|
||
tagging: mountTagging,
|
||
maintenance: mountMaintenance,
|
||
backups: mountBackups,
|
||
diagnostics: mountDiagnostics,
|
||
});
|
||
|
||
/**
|
||
* Mount System under the heading `renderHeading` wrote in `main`. Returns `{show(section)}`, which shows another
|
||
* section in place. `scope` is the page's view scope; `sections` maps a section id to a delivered section's mount
|
||
* (`(container, {api, activity, scope, drafts, counts}) => nodes`; `counts` is the shell's sidebar counts, #555) for every section. `activity` is the page's Activity store, which follows the jobs a section starts.
|
||
*
|
||
* 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). 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).
|
||
*/
|
||
/** D165 (#525): one small line under System's Overview, the workspace's only visible way to the legacy pages. */
|
||
function legacyPagesLine() {
|
||
const line = el('p', 'small legacy-pages');
|
||
line.append('Legacy pages: ');
|
||
LEGACY_PAGES.forEach((page, index) => {
|
||
const link = document.createElement('a');
|
||
link.textContent = page.label;
|
||
link.href = window.ApiClient.resolveUrl(page.href);
|
||
link.target = '_blank';
|
||
link.rel = 'noopener';
|
||
if (index) line.append(' · ');
|
||
line.append(link);
|
||
});
|
||
return line;
|
||
}
|
||
|
||
export function mountSystem(main, api, scope, { section, activity, counts = null, sections = DELIVERED_SECTIONS,
|
||
navigate = navigateTo }) {
|
||
const store = systemDrafts(api);
|
||
jobs = activity;
|
||
store.reloadHost();
|
||
// 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). `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', 'settings-layout');
|
||
const saveRow = el('div', 'save-row');
|
||
const status = el('span', 'small');
|
||
status.id = 'settings-status';
|
||
const save = createButton('Save preferences', 'ca-primary');
|
||
saveRow.append(status, save);
|
||
layout.append(saveRow);
|
||
main.append(nav, layout);
|
||
const legacyPages = legacyPagesLine();
|
||
|
||
const paintStatus = () => {
|
||
status.textContent = store.statusText();
|
||
if (store.dirty() && !store.saving()) save.removeAttribute('aria-disabled');
|
||
else save.setAttribute('aria-disabled', 'true');
|
||
markFailed(layout, store);
|
||
};
|
||
scope.cleanup(store.subscribe(paintStatus));
|
||
scope.listen(save, 'click', () => {
|
||
if (save.getAttribute('aria-disabled') === 'true') return;
|
||
const saving = store.save();
|
||
paintStatus();
|
||
saving.then(() => { if (!scope.signal.aborted) paintStatus(); });
|
||
});
|
||
|
||
let sectionScope = null;
|
||
scope.cleanup(() => sectionScope?.dispose());
|
||
function show(next) {
|
||
sectionScope?.dispose();
|
||
sectionScope = createScope();
|
||
for (const button of nav.children) button.setAttribute('aria-pressed', String(button.dataset.value === next));
|
||
while (layout.firstChild !== saveRow) layout.firstChild.remove();
|
||
// Every section is delivered (S12), and the router only names known sections (state.mjs).
|
||
const nodes = sections[next](layout, { api, activity, scope: sectionScope, drafts: store, counts });
|
||
layout.prepend(...nodes);
|
||
if (next === 'overview') main.append(legacyPages);
|
||
else legacyPages.remove();
|
||
paintStatus();
|
||
}
|
||
show(section);
|
||
return { show };
|
||
}
|