* feat(thumbnails): thumbnail format, quality and size as server settings
Thumbnail format (webp default, jxl, jpeg), quality (1-100, default 80)
and size limit (128-2048 px, default 512) are server settings in the
config.json thumbnails section, saved with the settings revision. The
never-read gallery thumbnail_size is gone: older saves wrote its unused
default 256 into config.json.
One module names previews (<stem>_thumb.webp/.jxl/.jpg) and finds the
preview a source owns, preferring the configured format; legacy names
are still found. The encoder module writes every preview atomically and
verifies it decodes. JPEG XL needs no new dependency: Pillow (natively
or with pillow_jxl), ffmpeg with libjxl, or cjxl; without one the
settings refuse jxl (400 jxl-unavailable) and GET says why. Encoder
processes are tracked, bounded and killed at shutdown.
* feat(thumbnails): every preview writer and lookup follows the thumbnail settings
Automatic previews (capture and first view), the thumbnail job, the
legacy gallery routes and the history route write <stem>_thumb.webp
(or .jxl/.jpg) with the configured quality and size limit, for images
and videos alike: video frames, ffmpeg's included (a PNG on stdout,
never upscaled), and the placeholder are encoded like images.
Listings, duplicates, enrichment, the autotag scan and the history
route show any preview the file owns, the current format first, so
older _thumb.png previews keep working until converted. A request for
an older name answers the current preview. Previews are served with
an explicit image/webp or image/jxl type and the same cache headers.
The plan and status count missing, outdated (another format) and
ready previews; the missing job never writes beside an outdated one.
Removing a file removes its previews in every format; the clear
removes .webp and .jxl too. Encoder processes are killed at shutdown.
A preview is only a placeholder: inspection refuses paths under
thumbnails/ and always reads the original, and the inspector cover
accepts the listing's preview in any format the file owns.
* feat(thumbnails): Convert outdated thumbnails as an Activity job
POST /jobs/thumbnails {mode: "convert"} starts "Convert outdated
thumbnails" under the thumbnail job's kind, guarded admission, worker
threads and cancel at a file boundary. For each file whose preview is
in another format, it writes the new preview from the source (atomic,
verified; a video with no decodable frame fails instead of getting the
placeholder), then removes that file's old-format previews in its
thumbnails folder. A failure keeps the old preview; orphan previews
and links are never touched. The final line reports converted, failed
and bytes before and after. The plan counts it with mode=convert; the
legacy gallery stream refuses to attach to a running conversion.
* feat(thumbnails): thumbnail settings in Appearance and Convert outdated in the workspace
System > Appearance gains a Thumbnails surface: format (WebP, JPEG XL,
JPEG), quality and size limit, saved to the server with the settings
revision. JPEG XL is offered only when the server has an encoder, else
the option is disabled with the server's reason (D130); a note says
when this browser cannot show JPEG XL. Saving a new format converts
nothing: the row then says previews keep their old format.
Thumbnail maintenance gains the Convert outdated scope and names the
server's settings instead of its own quality and size fields (D131).
Overview's thumbnail row reads N missing, M outdated, K failed and
offers Convert outdated while previews are outdated.
The workspace decodes a tiny JPEG XL once: where it cannot, cards, the
Library and the inspector cover load the original for a .jxl preview,
and any preview that fails to load falls back to the original. The
viewer and downloads keep using the original (regression test).
README explains enabling JPEG XL; TESTING.md records D130 and D131.
* test(thumbnails): coverage floors for the thumbnail modules and WebP in page workflows
The two new frontend modules enter the coverage baseline (98% lines);
other floors only rise. The visual fixture's preview is WebP and
Appearance has its Thumbnails surface in the System shell check.
* fix(thumbnails): say when the thumbnail settings could not be read
Like Appearance's other server rows, the Thumbnails rows show 'Server
settings could not be read.' while the read failed, instead of only
staying disabled. Firefox exposed the gap: its JPEG XL note arrived
first and changed the row notes the page workflow counted.
* test(thumbnails): accept the legacy preview's spelling a case-insensitive disk finds
On Windows and macOS the '.jpg' lookup finds an older release's
b_thumb.JPG first, so the listed URL spells '.jpg'; it names the same
file there. The test now accepts either spelling and checks the URL
serves that preview.
* fix(thumbnails): address the final review of the thumbnail format work
- ffmpeg writes JPEG XL with -update 1, so a % in a file name is never an
image-sequence pattern, and reads videos as file:<path>. The clear and a
startup sweep remove temp files that interrupted writes left behind.
- Convert outdated converts each group of same-stem files once, from the
first source in the R2 order. An old preview that is already gone counts
as removed, and each file's bytes count once. A current preview is only
kept if it decodes.
- An encoder that fails makes the write detect encoders again once. Another
encoder is used if one is found; with none, the file is written as WebP
and the availability Appearance shows is refreshed.
- Changing the thumbnail format, quality or size while Convert outdated runs
returns 409 busy. If the format still changes underneath, the job stops
without removing anything.
- Legacy preview spellings are matched case-insensitively, so X_thumb.JPG
counts as outdated.
- History's cover uses the same lookup as Images. It serves .jxl only when
Accept lists image/jxl, and otherwise the original or the placeholder.
- A video whose thumbnail the browser cannot show keeps its own element
(Images) or its label (Library).
* fix(thumbnails): keep the new preview, probe encoders only when gone, sweep reused PIDs
- Convert never removes a path that is the preview it just wrote. It
compares the device and inode, or the resolved and normcased paths when
the disk has no inode numbers. This covers x_thumb.JPG on a
case-insensitive disk.
- A JPEG XL encode failure re-runs encoder detection only when the
encoder's binary or module is gone. A "no encoder" result is checked
again on the settings read, on a jxl save, and after 60 s, so one slow
probe no longer turns JPEG XL off until a restart.
- The startup sweep now also removes temp files that carry this process's
PID but predate its start. Containers reuse PIDs.
* fix(history): let the cover ask for JPEG XL when this browser decodes it
Firefox can decode JPEG XL without listing image/jxl in Accept. When the
workspace's probe decodes JPEG XL, it adds jxl=1 to the History cover URL.
The server serves a .jxl preview when that flag is set or when Accept
lists image/jxl. In every other case it falls back as before. The flag
accepts only 0 or 1, and the response stays no-store.
* fix(thumbnails): keep going past the per-batch cap until every preview is made
The missing, rebuild and Convert outdated jobs stopped after
MAX_THUMBNAIL_FILES (10,000) files and said "N more on the next run", but
nothing ever started that next run. The cap now bounds one batch. After
each batch the job plans again, leaving out every file it already worked
on, and continues until nothing is left, the job is cancelled, or a batch
makes no progress. That last case stops on files that fail every time
instead of looping over them.
Activity progress counts against the overall total, and the final line and
the legacy stream's complete frame report every batch. Admission, worker
threads, cancellation and the #316 rules are unchanged. The Thumbnail
maintenance dialog now counts all the work instead of saying "more on the
next run".
200 lines
10 KiB
JavaScript
200 lines
10 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. A section not delivered yet shows the
|
||
* per-section hand-off to its legacy tool (D94), never mock placeholders. Overview (system-overview.mjs),
|
||
* Appearance (system-appearance.mjs) and Sources & scans (system-sources.mjs) are native.
|
||
*
|
||
* 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 { SYSTEM_SECTIONS, navigateTo } from './state.mjs';
|
||
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 { mountSources } from './system-sources.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';
|
||
const ADMIN = Object.freeze({ href: '/prompt_manager/admin', label: 'Open existing administration' });
|
||
const GALLERY = Object.freeze({ href: '/prompt_manager/gallery', label: 'Open existing image gallery' });
|
||
/**
|
||
* D94: where each section's capabilities live until its PR (the plan's legacy capability coverage): the admin page's
|
||
* dashboard, Settings, Maintenance, Backup, Restore, Scan, Logs, Diagnostics and Auto-tag tools, and the gallery's
|
||
* settings, thumbnails, duplicates and cache tools.
|
||
*/
|
||
export const SECTION_HANDOFFS = Object.freeze({
|
||
integrations: [ADMIN],
|
||
tagging: [ADMIN],
|
||
maintenance: [ADMIN, GALLERY],
|
||
backups: [ADMIN],
|
||
diagnostics: [ADMIN],
|
||
});
|
||
export const NOT_DELIVERED = 'This setting is not available here yet.';
|
||
|
||
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, text, className) {
|
||
const node = document.createElement(tag);
|
||
if (text !== undefined) node.textContent = text;
|
||
if (className) node.className = className;
|
||
return node;
|
||
}
|
||
|
||
/** A domain whose settings no delivered section edits yet: nothing can be drafted, and a write would say it failed. */
|
||
const undelivered = async () => { throw new Error(NOT_DELIVERED); };
|
||
|
||
/**
|
||
* 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).
|
||
*/
|
||
export function systemDrafts(api) {
|
||
drafts ??= createSystemDrafts({
|
||
readBrowser: () => readPreferences().values,
|
||
readRuntime: () => ({}),
|
||
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' });
|
||
// 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).
|
||
return { values: { ...result.settings, thumbnail_encoders: result.thumbnail_encoders }, revision: result.revision };
|
||
},
|
||
async writeHost(changes, { expected_revision }) {
|
||
try {
|
||
return await api.post(SETTINGS_URL, { ...changes, expected_revision });
|
||
} 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;
|
||
}
|
||
|
||
/** D94: the shared hand-off panel, linking each legacy tool that still owns this section. */
|
||
function handoff(section) {
|
||
const panel = el('section', undefined, 'surface handoff');
|
||
panel.append(el('h2', 'Your current tools are ready'),
|
||
el('p', 'This workspace is being introduced in stages. Continue in the existing tool with your saved data.'));
|
||
for (const tool of SECTION_HANDOFFS[section]) {
|
||
const link = el('a', tool.label, 'workspace-link');
|
||
link.href = window.ApiClient.resolveUrl(tool.href);
|
||
panel.append(link);
|
||
}
|
||
return [panel];
|
||
}
|
||
|
||
/** 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');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The sections delivered so far: Overview (S2 Task 6), Appearance (S3 Task 8), Sources & scans (S4 Task 11), and Maintenance's notice with "Run health checks" above the
|
||
* hand-off to the maintenance tools that are not native yet (D123).
|
||
*/
|
||
export const DELIVERED_SECTIONS = Object.freeze({
|
||
overview: mountOverview,
|
||
appearance: mountAppearance,
|
||
sources: mountSources,
|
||
maintenance: (container, { api, activity, scope }) => [healthNotice({ api, activity, scope }), ...handoff('maintenance')],
|
||
});
|
||
|
||
/**
|
||
* 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}) => nodes`), and every other section hands off. `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).
|
||
*/
|
||
export function mountSystem(main, api, scope, { section, activity, 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', undefined, 'settings-layout');
|
||
const saveRow = el('div', undefined, 'save-row');
|
||
const status = el('span', undefined, 'small');
|
||
status.id = 'settings-status';
|
||
const save = createButton('Save preferences', 'ca-primary');
|
||
saveRow.append(status, save);
|
||
layout.append(saveRow);
|
||
main.append(nav, layout);
|
||
|
||
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();
|
||
const mount = sections[next];
|
||
const nodes = mount ? mount(layout, { api, activity, scope: sectionScope, drafts: store }) : handoff(next);
|
||
layout.prepend(...nodes);
|
||
paintStatus();
|
||
}
|
||
show(section);
|
||
return { show };
|
||
}
|