Files
odysseus/static/js/settings/imagePreferences.js
T
39303f19cd fix(editor): stabilize image generation, layer editing and controls (#6992)
* fix(editor): stabilize image workflows and editing controls

* docs(editor): add desktop and mobile visual validation evidence

* fix(editor): synchronize quick edit model events and register imagePreferences in test coordinator

* fix(settings): enforce authoritative global image-gen policy and non-admin preference persistence

- Enforce authoritative administrator global image_gen_enabled disable in get_user_setting, do_generate_image, and image_editing_provider_available, preventing non-admin user preference overrides while preserving user-disabled opt-outs and can_generate_images privilege checks across direct, gallery, and editor paths.
- Filter non-admin preference persistence in saveImagePreferences to user preference keys only (image_model, image_edit_model, image_quality), preventing global policy toggles from leaking into user preferences.
- Return accurate 200 OK Response from saveImagePreferences after fallback persistence succeeds so settings UI displays 'Saved' instead of false 403 error, while retaining visibility of real errors.
- Load per-user preferences via readImagePreferences in initImageSettings so non-admin selections persist and display correctly after page reload.
- Clear per-user model preferences on successful admin save (POST /api/auth/settings) via PUT /api/prefs/{key} with value: null to prevent stale per-user preferences from shadowing updated global settings.
- Support clearing keys in PUT /api/prefs/{key} when value is null.
- Add comprehensive Python regression tests for global-disabled/user-enabled, global-enabled/user-disabled, and authorized generation, plus Node and browser regression tests for non-admin persistence, toggle isolation, reload, and admin clearing.

* fix(settings): invalidate shared appConfig cache near auth settings write

* fix(test): isolate test_tool_policy unit suite from external model endpoint state

* fix(test): isolate web_fetch failure regression from contextual follow-up heuristics

* fix(test): isolate test_tool_policy from cross-test approval gate state

Ensure _patch_loop_basics disables TOOL_APPROVAL_GATE_ENABLED so routing tests in test_tool_policy run in the intended opt-out posture even when prior tests populate DATA_DIR with skills or untrusted context. Remove unnecessary forced_tools and contextual web mock workarounds.

* fix(settings): isolate non-admin image toggle and surface preference cleanup errors

- Restrict image generation availability toggle to admin users in imageModels.js, disabling the switch for non-admins and reverting unauthorized changes with an explicit message.
- Separate non-admin image model preference saves from global toggle updates.
- Track preference cleanup results on admin save in imagePreferences.js, propagating cleanup failures instead of ignoring them.
- Require valid preference keys on 403 fallback so toggle-only attempts reject cleanly.
- Add /api/prefs route mock to test_image_model_settings_sync_both_directions_and_survive_reopening.
- Add regression coverage for admin cleanup failures and non-admin toggle rejection.

* fix(settings): reconcile admin toggle on partial cleanup failure and report errors

- In imagePreferences.js, distinguish pre-persistence failures from post-save cleanup failures using err.globalSaved and err.phase.

- In imagePreferences.js, notify listeners of global policy updates on partial success before propagating cleanup failure.

- In imageModels.js, retain the persisted target state on admin toggle when global persistence succeeds but cleanup fails.

- In imageModels.js, reconcile admin toggle with authoritative server state via readImagePreferences() after ambiguous or partial failures.

- In imageModels.js, report partial success accurately without suppressing preference cleanup error messages.

- Add regression coverage in test_settings_save_response_ok_js.py for cleanup HTTP 500, cleanup network rejection, successful cleanup, and failed global POST.

---------

Co-authored-by: pewdiepie-archdaemon <pewdiepie-archdaemon@users.noreply.github.com>
Co-authored-by: Alexandre Teixeira <general@alexandreteixeira.dev>
2026-11-01 02:56:46 +00:00

108 lines
4.3 KiB
JavaScript

import { invalidateSettings } from '../appConfig.js';
const USER_PREFERENCE_KEYS = ['image_model', 'image_edit_model', 'image_quality'];
export async function readImagePreferences() {
const [prefsRes, settingsRes] = await Promise.all([
fetch('/api/prefs', { credentials: 'same-origin' }).catch(() => null),
fetch('/api/auth/settings', { credentials: 'same-origin' }).catch(() => null),
]);
const prefs = (prefsRes && prefsRes.ok) ? await prefsRes.json().catch(() => ({})) : {};
const settings = (settingsRes && settingsRes.ok) ? await settingsRes.json().catch(() => ({})) : {};
if (!prefsRes?.ok && !settingsRes?.ok) throw new Error('Could not load image settings');
return {
...settings,
image_model: prefs?.image_model || settings?.image_model || '',
image_edit_model: prefs?.image_edit_model || settings?.image_edit_model || '',
image_quality: prefs?.image_quality || settings?.image_quality || 'medium',
};
}
let saveQueue = Promise.resolve();
export function waitForImagePreferences() { return saveQueue; }
export function saveImagePreferences(patch) {
const save = async () => {
let response;
try {
response = await fetch('/api/auth/settings', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch),
});
} catch (netErr) {
invalidateSettings();
netErr.globalSaved = false;
throw netErr;
}
invalidateSettings();
if (response.status === 403) {
const userEntries = Object.entries(patch).filter(([k]) => USER_PREFERENCE_KEYS.includes(k));
if (userEntries.length === 0) {
const err = new Error('Admin access is required to change these settings.');
err.status = 403;
err.globalSaved = false;
throw err;
}
for (const [key, value] of userEntries) {
const prefRes = await fetch(`/api/prefs/${encodeURIComponent(key)}`, {
method: 'PUT', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value }),
});
if (!prefRes.ok) {
const err = new Error(await prefRes.text().catch(() => 'Could not save image preferences'));
err.status = prefRes.status;
err.globalSaved = false;
throw err;
}
}
response = typeof Response !== 'undefined'
? new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'Content-Type': 'application/json' } })
: { ok: true, status: 200, json: async () => ({ ok: true }), text: async () => '{"ok":true}' };
} else if (response.ok) {
const clearResults = await Promise.all(USER_PREFERENCE_KEYS.map(async key => {
try {
const res = await fetch(`/api/prefs/${encodeURIComponent(key)}`, {
method: 'PUT', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: null }),
});
if (!res.ok) {
const err = new Error(await res.text().catch(() => `HTTP ${res.status}`));
err.status = res.status;
return { ok: false, error: err };
}
return { ok: true };
} catch (err) {
return { ok: false, error: err };
}
}));
const failure = clearResults.find(r => !r.ok);
if (failure) {
invalidateSettings();
if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') {
window.dispatchEvent(new CustomEvent('image-preferences-changed', { detail: patch }));
}
const err = new Error(failure.error?.message || 'Could not clear personal preferences');
err.status = failure.error?.status || 500;
err.cause = failure.error;
err.globalSaved = true;
err.phase = 'cleanup';
throw err;
}
} else {
const err = new Error('Could not save image settings');
err.status = response.status;
err.globalSaved = false;
throw err;
}
invalidateSettings();
if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') {
window.dispatchEvent(new CustomEvent('image-preferences-changed', { detail: patch }));
}
return response;
};
const result = saveQueue.then(save);
saveQueue = result.catch(() => {});
return result;
}