Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: save the Media settings drawer field-by-field so sibling patches survive

[._.]/ Adam Eivye0eb21675bc0
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index e9e32a988e..413948dde9 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -6,7 +6,7 @@
* lives in the always-visible Codex CLI Imagegen section.
*/
-import { useState, useEffect, useCallback, useId, useRef } from 'react';
+import { useState, useEffect, useCallback, useId } from 'react';
import {
Save, Image as ImageIcon, Zap, Wrench, Cloud, Cpu, Globe, AlertTriangle,
Sparkles, Terminal, Key, Check, Trash2, SlidersHorizontal, Bot, FlaskConical
@@ -23,7 +23,7 @@ import { isLoopbackHost } from '../../lib/loopbackHost.js';
import { PORTS } from '../../lib/ports.js';
import { getNavPageForPath } from '../../../../server/lib/navManifest.js';
import {
- getSettings, updateSettings, getImageGenStatus, getVideoGenModelContext, generateImage,
+ getSettings, patchSettingsSlice, getImageGenStatus, getVideoGenModelContext, generateImage,
registerTool, updateTool, getToolsList,
saveHfToken, clearHfToken,
getCredentialInventory, saveCredential, getProviders,
@@ -84,6 +84,66 @@ export const MEDIA_TABS = [
];
const MEDIA_TAB_IDS = MEDIA_TABS.map((t) => t.id);
+// Per-surface render defaults (#3231). Entries with no effective pin are
+// dropped so settings.json doesn't accumulate `{ imageMode: 'auto' }` no-ops
+// for every surface the user merely glanced at.
+const pruneRenderDefaults = (rd) => Object.fromEntries(
+ Object.entries(rd).filter(([, entry]) => entry && Object.values(entry).some(
+ (v) => typeof v === 'string' && v.trim() && v !== RENDER_TARGET_BACKEND_AUTO,
+ )),
+);
+
+// Every settings field this drawer owns, grouped by the slice PATCH that
+// persists it (server: settingsSlicePartialSchemas). The server merges per
+// field inside the selected slice, so a save sends only the fields that
+// changed since load and never a snapshot of a sibling — a value VideoGen's
+// LocalSetupPanel patched after the drawer opened (`imageGen.local.pythonPath`)
+// or a hand-edited key the drawer never renders (`imageGen.local.steps`)
+// survives. Cleared strings travel as '' (every reader falls back on a blank);
+// the two pins readers coerce with `||` go as null so an un-pin needs no
+// sentinel string. `renderDefaults` merges per target, so a cleared surface
+// is an explicit null.
+const sliceFieldsOf = (f) => ({
+ imageGen: { mode: f.mode, sdapiUrl: f.sdapiUrl },
+ 'imageGen.external': { sdapiUrl: f.sdapiUrl, cleanC2PA: f.cleanC2PAByMode.external, denoise: f.denoiseByMode.external },
+ 'imageGen.local': {
+ pythonPath: f.pythonPath || null,
+ modelId: f.localModelId || null,
+ cleanC2PA: f.cleanC2PAByMode.local,
+ denoise: f.denoiseByMode.local,
+ },
+ 'imageGen.codex': {
+ enabled: f.codexEnabled, codexPath: f.codexPath, model: f.codexModel, effort: f.codexEffort,
+ parallelLimit: f.codexParallelLimit, cleanC2PA: f.cleanC2PAByMode.codex, denoise: f.denoiseByMode.codex,
+ },
+ 'imageGen.grok': {
+ enabled: f.grokEnabled, grokPath: f.grokPath, aspectRatio: f.grokAspectRatio,
+ cleanC2PA: f.cleanC2PAByMode.grok, denoise: f.denoiseByMode.grok,
+ },
+ 'imageGen.agy': {
+ enabled: f.agyEnabled, agyPath: f.agyPath, model: f.agyModel,
+ cleanC2PA: f.cleanC2PAByMode.agy, denoise: f.denoiseByMode.agy,
+ },
+ 'imageGen.fal': {
+ enabled: f.falEnabled, model: falImageFamily(f.falModel) ? f.falModel : '',
+ cleanC2PA: f.cleanC2PAByMode.fal, denoise: f.denoiseByMode.fal,
+ },
+ 'imageGen.expose': { a1111: f.exposeA1111 },
+ renderDefaults: Object.fromEntries(RENDER_TARGET_OPTIONS.map(({ id }) => [id, f.renderDefaults[id] ?? null])),
+ videoGen: { mode: f.videoGenMode || null, defaultModelId: f.localVideoModelId || null, displaySleep: f.videoGenDisplaySleep },
+});
+
+// `[slicePath, partial]` pairs that move the persisted fields from `previous`
+// to `next`; a slice with no changed field is not sent at all.
+const diffSlicePatches = (next, previous) => {
+ const before = sliceFieldsOf(previous);
+ return Object.entries(sliceFieldsOf(next)).flatMap(([slicePath, fields]) => {
+ const changed = Object.entries(fields)
+ .filter(([key, value]) => JSON.stringify(value) !== JSON.stringify(before[slicePath][key]));
+ return changed.length ? [[slicePath, Object.fromEntries(changed)]] : [];
+ });
+};
+
export function ImageGenTab() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -111,18 +171,9 @@ export function ImageGenTab() {
// Only pinned entries are kept; an absent target means "auto".
const [renderDefaults, setRenderDefaults] = useState({});
// Install-wide video backend pin (`settings.videoGen.mode`, #3231 Phase 4).
- // '' = no pin (local). The full loaded `videoGen` slice is kept in a ref —
- // never rendered, only round-tripped at save time so sibling keys
- // (defaultModelId) survive the settings PUT's wholesale slice replace.
+ // '' = no pin (local).
const [videoGenMode, setVideoGenMode] = useState('');
const [videoGenDisplaySleep, setVideoGenDisplaySleep] = useState(false);
- const videoGenSliceRef = useRef({});
- // Same round-trip guard as videoGenSliceRef, for the same reason: the PUT
- // replaces `imageGen` wholesale, and `imageGen.local` carries hand-edit-only
- // keys this tab never renders — steps / guidance / quantize, read by
- // fableLoom/production.js. Rebuilding the slice from the rendered fields
- // alone silently wiped them on every Media save.
- const localSliceRef = useRef({});
const [sdapiUrl, setSdapiUrl] = useState('');
const [pythonPath, setPythonPath] = useState('');
// Install-wide default local image model (`settings.imageGen.local.modelId`).
@@ -250,7 +301,7 @@ export function ImageGenTab() {
falEnabled: false, falModel: '',
cleanC2PAByMode: { external: true, local: true, codex: true, grok: false, agy: false, fal: false },
denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false, fal: false },
- renderDefaultsJson: '{}',
+ renderDefaults: {},
videoGenMode: '',
localVideoModelId: '',
videoGenDisplaySleep: false,
@@ -363,12 +414,11 @@ export function ImageGenTab() {
Promise.all([getSettings({ silent: true }), getToolsList({ silent: true })])
.then(([s, tools]) => {
const ig = s?.imageGen || {};
- // Round-trip the FULL renderDefaults object (including videoModel keys
- // this tab doesn't edit) — the server replaces the top-level slice
- // wholesale on save, so dropping unedited keys here would erase them.
+ // Load every target entry whole (including videoModel keys this tab
+ // doesn't edit) — an entry is saved as one unit when it changes.
const rd = (s?.renderDefaults && typeof s.renderDefaults === 'object') ? s.renderDefaults : {};
- // Video pin: keep the whole slice for round-trip; normalize the mode
- // ('auto'/blank → '', i.e. no pin) for the select.
+ // Video pin: normalize the mode ('auto'/blank → '', i.e. no pin) for
+ // the select.
const vg = (s?.videoGen && typeof s.videoGen === 'object') ? s.videoGen : {};
const vgMode = normalizeRenderPinValue(vg.mode) || '';
const vgModelId = vg.defaultModelId || '';
@@ -414,8 +464,6 @@ export function ImageGenTab() {
setVideoGenMode(vgMode);
setLocalVideoModelId(vgModelId);
setVideoGenDisplaySleep(vgDisplaySleep);
- localSliceRef.current = (ig.local && typeof ig.local === 'object') ? ig.local : {};
- videoGenSliceRef.current = vg;
setSdapiUrl(url);
setPythonPath(py);
setLocalModelId(localModel);
@@ -444,7 +492,7 @@ export function ImageGenTab() {
agyEnabled: ayEnabled, agyPath: ayPath, agyModel: ayModel,
falEnabled: flEnabled, falModel: flModel,
cleanC2PAByMode: c2, denoiseByMode: dn,
- renderDefaultsJson: JSON.stringify(rd),
+ renderDefaults: rd,
videoGenMode: vgMode,
localVideoModelId: vgModelId,
videoGenDisplaySleep: vgDisplaySleep,
@@ -573,112 +621,78 @@ export function ImageGenTab() {
|| denoiseByMode.codex !== saved.denoiseByMode.codex
|| denoiseByMode.local !== saved.denoiseByMode.local
|| denoiseByMode.external !== saved.denoiseByMode.external
- || JSON.stringify(renderDefaults) !== saved.renderDefaultsJson
+ || JSON.stringify(renderDefaults) !== JSON.stringify(saved.renderDefaults)
|| videoGenMode !== saved.videoGenMode
|| localVideoModelId !== saved.localVideoModelId
|| videoGenDisplaySleep !== saved.videoGenDisplaySleep;
const handleSave = async () => {
setSaving(true);
- const url = normalizeUrl(sdapiUrl) || undefined;
- const cxPath = codexPath?.trim() || undefined;
- const cxModel = codexModel?.trim() || undefined;
- const cxEffort = codexEffort?.trim() || undefined;
- const cxParallel = clampParallel(codexParallelLimit, parallelBounds);
- const gkPath = grokPath?.trim() || undefined;
- const gkRatio = grokAspectRatio?.trim() || undefined;
- const ayPath = agyPath?.trim() || undefined;
- const ayModel = agyModel?.trim() || undefined;
- const patch = {
- imageGen: {
- mode,
- external: { sdapiUrl: url, cleanC2PA: cleanC2PAByMode.external, denoise: denoiseByMode.external },
- local: {
- ...localSliceRef.current,
- pythonPath: pythonPath || undefined,
- // `undefined` drops the key so an un-pinned install keeps resolving
- // through LOCAL_IMAGEGEN_DEFAULT_MODEL rather than persisting a ''
- // that every `|| LOCAL_IMAGEGEN_DEFAULT_MODEL` read would have to
- // keep coercing.
- modelId: localModelId || undefined,
- cleanC2PA: cleanC2PAByMode.local,
- denoise: denoiseByMode.local,
- },
- codex: {
- enabled: codexEnabled, codexPath: cxPath, model: cxModel, effort: cxEffort, parallelLimit: cxParallel,
- cleanC2PA: cleanC2PAByMode.codex, denoise: denoiseByMode.codex,
- },
- grok: {
- enabled: grokEnabled, grokPath: gkPath, aspectRatio: gkRatio,
- cleanC2PA: cleanC2PAByMode.grok, denoise: denoiseByMode.grok,
- },
- agy: {
- enabled: agyEnabled, agyPath: ayPath, model: ayModel,
- cleanC2PA: cleanC2PAByMode.agy, denoise: denoiseByMode.agy,
- },
- fal: {
- enabled: falEnabled, model: falImageFamily(falModel) ? falModel : undefined,
- cleanC2PA: cleanC2PAByMode.fal, denoise: denoiseByMode.fal,
- },
- expose: { a1111: exposeA1111 },
- // Keep the legacy field populated so anything still reading
- // `imageGen.sdapiUrl` directly stays working.
- sdapiUrl: url,
- },
- // Per-surface render defaults (#3231). Entries with no effective pin are
- // dropped so settings.json doesn't accumulate `{ imageMode: 'auto' }`
- // no-ops for every surface the user merely glanced at.
- renderDefaults: Object.fromEntries(
- Object.entries(renderDefaults).filter(([, entry]) => entry && Object.values(entry).some(
- (v) => typeof v === 'string' && v.trim() && v !== RENDER_TARGET_BACKEND_AUTO,
- )),
- ),
- // Install-wide video pin (#3231 Phase 4). Spread over the loaded slice so
- // sibling keys (defaultModelId) survive the wholesale slice replace.
- videoGen: {
- ...videoGenSliceRef.current,
- mode: videoGenMode || null,
- defaultModelId: localVideoModelId || null,
- displaySleep: videoGenDisplaySleep,
- },
+ // What the server will hold after this save: the form, normalized the way
+ // the inputs are reflected back below (trimmed paths/models, clamped
+ // parallel limit, pruned render defaults).
+ const next = {
+ mode,
+ sdapiUrl: normalizeUrl(sdapiUrl),
+ pythonPath,
+ localModelId,
+ exposeA1111,
+ codexEnabled,
+ codexPath: codexPath?.trim() || '',
+ codexModel: codexModel?.trim() || '',
+ codexEffort: codexEffort?.trim() || '',
+ codexParallelLimit: clampParallel(codexParallelLimit, parallelBounds),
+ grokEnabled,
+ grokPath: grokPath?.trim() || '',
+ grokAspectRatio: grokAspectRatio?.trim() || '',
+ agyEnabled,
+ agyPath: agyPath?.trim() || '',
+ agyModel: agyModel?.trim() || '',
+ falEnabled,
+ falModel,
+ cleanC2PAByMode,
+ denoiseByMode,
+ renderDefaults: pruneRenderDefaults(renderDefaults),
+ videoGenMode,
+ localVideoModelId,
+ videoGenDisplaySleep,
};
+ const url = next.sdapiUrl || undefined;
+ const cxPath = next.codexPath || undefined;
+ const cxModel = next.codexModel || undefined;
+ const cxEffort = next.codexEffort || undefined;
+ const cxParallel = next.codexParallelLimit;
+ const gkPath = next.grokPath || undefined;
+ const gkRatio = next.grokAspectRatio || undefined;
+ const ayPath = next.agyPath || undefined;
+ const ayModel = next.agyModel || undefined;
try {
- await updateSettings(patch, { silent: true });
- // Store trimmed values to match what was persisted — otherwise
- // trailing whitespace in the inputs leaves isDirty stuck true even
- // after a successful save (state has " codex " but `saved` was
- // updated with the trimmed "codex").
- setSaved({
- mode, sdapiUrl: url || '', pythonPath, localModelId, exposeA1111,
- codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '', codexEffort: cxEffort || '',
- codexParallelLimit: cxParallel,
- grokEnabled, grokPath: gkPath || '', grokAspectRatio: gkRatio || '',
- agyEnabled, agyPath: ayPath || '', agyModel: ayModel || '',
- falEnabled, falModel,
- cleanC2PAByMode, denoiseByMode,
- renderDefaultsJson: JSON.stringify(patch.renderDefaults),
- videoGenMode,
- localVideoModelId,
- videoGenDisplaySleep,
- });
+ // One request per changed slice, in order, so the server's write queue
+ // merges each against the freshest persisted settings. A failure part
+ // way leaves `saved` untouched: the next save re-sends the same
+ // (idempotent) patches.
+ for (const [slicePath, partial] of diffSlicePatches(next, saved)) {
+ await patchSettingsSlice(slicePath, partial, { silent: true });
+ }
+ // `saved` holds the normalized values — otherwise trailing whitespace in
+ // the inputs leaves isDirty stuck true after a successful save.
+ setSaved(next);
// Reflect the pruned no-op entries back into the editor state so the
// dirty check compares like against like after a save.
- setRenderDefaults(patch.renderDefaults);
- videoGenSliceRef.current = patch.videoGen;
- localSliceRef.current = patch.imageGen.local;
+ setRenderDefaults(next.renderDefaults);
if (cxParallel !== codexParallelLimit) {
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
}
// Reflect the normalization back into the inputs so what the user
// sees matches what was saved.
- if (cxPath !== codexPath) setCodexPath(cxPath || '');
- if (cxModel !== codexModel) setCodexModel(cxModel || '');
- if (cxEffort !== codexEffort) setCodexEffort(cxEffort || '');
- if (gkPath !== grokPath) setGrokPath(gkPath || '');
- if (gkRatio !== grokAspectRatio) setGrokAspectRatio(gkRatio || '');
- if (ayPath !== agyPath) setAgyPath(ayPath || '');
- if (ayModel !== agyModel) setAgyModel(ayModel || '');
+ if (next.codexPath !== codexPath) setCodexPath(next.codexPath);
+ if (next.codexModel !== codexModel) setCodexModel(next.codexModel);
+ if (next.codexEffort !== codexEffort) setCodexEffort(next.codexEffort);
+ if (next.grokPath !== grokPath) setGrokPath(next.grokPath);
+ if (next.grokAspectRatio !== grokAspectRatio) setGrokAspectRatio(next.grokAspectRatio);
+ if (next.agyPath !== agyPath) setAgyPath(next.agyPath);
+ if (next.agyModel !== agyModel) setAgyModel(next.agyModel);
toast.success('Image gen settings saved');
} catch (err) {
toast.error(err.message || 'Failed to save settings');
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 96899ac580..47664908a4 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -4,7 +4,7 @@ import { MemoryRouter } from 'react-router';
vi.mock('../../services/api', () => ({
getSettings: vi.fn(),
- updateSettings: vi.fn(),
+ patchSettingsSlice: vi.fn(),
getImageGenStatus: vi.fn(),
getVideoGenModelContext: vi.fn(),
generateImage: vi.fn(),
@@ -36,13 +36,17 @@ vi.mock('./LocalSetupPanel', () => ({
vi.mock('../imageGen/Flux2InstallModal', () => ({ default: () => null }));
import {
- getSettings, getToolsList, updateSettings, listAgyImageModels, listImageModels, getImageGenStatus,
+ getSettings, getToolsList, patchSettingsSlice, listAgyImageModels, listImageModels, getImageGenStatus,
getVideoGenModelContext, generateImage, getCredentialInventory, getProviders, registerTool,
} from '../../services/api';
import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';
import { ImageGenTab, MEDIA_TABS } from './ImageGenTab';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
+// Every slice PATCH a save sent, keyed by slice path.
+const sentSlices = () => Object.fromEntries(patchSettingsSlice.mock.calls.map(([slicePath, partial]) => [slicePath, partial]));
+const awaitSave = () => waitFor(() => expect(patchSettingsSlice).toHaveBeenCalled());
+
const renderTab = async (initialEntries = ['/media/image']) => {
const view = render(
<MemoryRouter initialEntries={initialEntries}>
@@ -81,7 +85,7 @@ beforeEach(() => {
{ id: 'reactor', label: 'reactor.inc', configured: false, source: 'none', editable: true },
],
});
- updateSettings.mockResolvedValue({});
+ patchSettingsSlice.mockResolvedValue({});
getProviders.mockResolvedValue({
providers: [{ id: 'codex', type: 'cli', command: 'codex', models: ['gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-luna'] }],
});
@@ -108,8 +112,8 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.blur(input);
expect(input.value).toBe('50');
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- expect(updateSettings.mock.calls[0][0].imageGen.codex.parallelLimit).toBe(50);
+ await awaitSave();
+ expect(sentSlices()['imageGen.codex'].parallelLimit).toBe(50);
},
);
@@ -180,9 +184,9 @@ describe('ImageGenTab grouped tabs', () => {
expect(screen.getByRole('option', { name: 'Install default (FastMetal 5B QAD)' })).toBeTruthy();
fireEvent.change(select, { target: { value: 'ltx23_distilled_q4' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ await awaitSave();
- expect(updateSettings.mock.calls[0][0].videoGen.defaultModelId).toBe('ltx23_distilled_q4');
+ expect(sentSlices().videoGen).toEqual({ defaultModelId: 'ltx23_distilled_q4' });
});
it('clears the saved local video model pin to follow the install default', async () => {
@@ -195,9 +199,9 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.change(screen.getByLabelText('Default local video model'), { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ await awaitSave();
- expect(updateSettings.mock.calls[0][0].videoGen.defaultModelId).toBeNull();
+ expect(sentSlices().videoGen).toEqual({ defaultModelId: null });
});
it('keeps LocalSetupPanel mounted (hidden) after leaving the Local tab so an in-flight install stream is not torn down', async () => {
@@ -312,7 +316,11 @@ describe('ImageGenTab grouped tabs', () => {
expect(screen.getByText(/grok — grok-cli 0\.0\.30/)).toBeTruthy();
});
- it('preserves the save behavior — dirtying a field enables Save and PUTs the full imageGen patch', async () => {
+ it('saves only the changed fields as slice patches, so a sibling panel\'s later write survives (#12030)', async () => {
+ // The drawer loaded pythonPath '/usr/bin/python3'. While it is open,
+ // VideoGen's LocalSetupPanel patches imageGen.local.pythonPath to a new
+ // interpreter — a write this drawer cannot see. Its save must not carry
+ // a snapshot of imageGen.local (or of any slice the user did not edit).
await renderTab();
fireEvent.click(screen.getByRole('tab', { name: /External/i }));
const urlInput = screen.getByPlaceholderText('http://localhost:7860');
@@ -320,14 +328,30 @@ describe('ImageGenTab grouped tabs', () => {
const saveBtn = screen.getByRole('button', { name: /^Save$/ });
expect(saveBtn.disabled).toBe(false);
fireEvent.click(saveBtn);
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- const patch = updateSettings.mock.calls[0][0];
- expect(patch.imageGen.external.sdapiUrl).toBe('http://localhost:9999');
- expect(patch.imageGen.mode).toBe('external');
- expect(patch.imageGen).toHaveProperty('codex');
- expect(patch.imageGen).toHaveProperty('grok');
- expect(patch.imageGen).toHaveProperty('agy');
- expect(patch.imageGen).toHaveProperty('expose');
+ await awaitSave();
+ // The legacy flat `imageGen.sdapiUrl` is kept populated beside the
+ // external slice; nothing else travels.
+ expect(sentSlices()).toEqual({
+ 'imageGen.external': { sdapiUrl: 'http://localhost:9999' },
+ imageGen: { sdapiUrl: 'http://localhost:9999' },
+ });
+ expect(patchSettingsSlice.mock.calls.every(([, , options]) => options?.silent === true)).toBe(true);
+ await waitFor(() => expect(saveBtn.disabled).toBe(true));
+ });
+
+ it('keeps the form dirty and re-sends the same patches when a slice save fails', async () => {
+ patchSettingsSlice.mockRejectedValueOnce(new Error('offline'));
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /External/i }));
+ fireEvent.change(screen.getByPlaceholderText('http://localhost:7860'), { target: { value: 'http://localhost:9999' } });
+ const saveBtn = screen.getByRole('button', { name: /^Save$/ });
+ fireEvent.click(saveBtn);
+ await awaitSave();
+ await waitFor(() => expect(saveBtn.disabled).toBe(false));
+ patchSettingsSlice.mockClear();
+ fireEvent.click(saveBtn);
+ await awaitSave();
+ expect(sentSlices()['imageGen.external']).toEqual({ sdapiUrl: 'http://localhost:9999' });
});
it('offers the Codex provider\'s models in a picker and keeps an unlisted stored pin', async () => {
@@ -344,8 +368,8 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.change(select, { target: { value: 'gpt-6-sol' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- expect(updateSettings.mock.calls[0][0].imageGen.codex.model).toBe('gpt-6-sol');
+ await awaitSave();
+ expect(sentSlices()['imageGen.codex']).toEqual({ model: 'gpt-6-sol' });
});
it('pins the install-wide default local model and saves it under imageGen.local.modelId', async () => {
@@ -359,11 +383,11 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.change(select, { target: { value: 'flux2-klein-4b' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- expect(updateSettings.mock.calls[0][0].imageGen.local.modelId).toBe('flux2-klein-4b');
+ await awaitSave();
+ expect(sentSlices()['imageGen.local']).toEqual({ modelId: 'flux2-klein-4b' });
});
- it('drops modelId from the save body when the pin is cleared, so the server default resolves again', async () => {
+ it('clears modelId with an explicit null when the pin is cleared, so the server default resolves again', async () => {
getSettings.mockResolvedValue({
imageGen: {
mode: 'local',
@@ -380,11 +404,11 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.change(select, { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- // Absent, not '' — every consumer reads `local.modelId || DEFAULT`, and a
+ await awaitSave();
+ // null, not '' — the slice merge keeps an omitted key, so the clear must
+ // be a value; every consumer reads `local.modelId || DEFAULT`, and a
// persisted empty string is a value they would all have to keep coercing.
- expect(JSON.parse(JSON.stringify(updateSettings.mock.calls[0][0])).imageGen.local)
- .not.toHaveProperty('modelId');
+ expect(sentSlices()['imageGen.local']).toEqual({ modelId: null });
});
it('keeps a pin the catalog no longer lists selectable rather than silently dropping it', async () => {
@@ -405,12 +429,11 @@ describe('ImageGenTab grouped tabs', () => {
expect(screen.getByRole('option', { name: /retired-model \(unavailable on this machine\)/ })).toBeTruthy();
});
- it('the imageGen.local save body round-trips sibling keys the tab does not edit', async () => {
- // Same wholesale-slice-replace hazard the videoGen case below pins:
+ it('the imageGen.local save body names only the changed field, so hand-edited siblings survive', async () => {
// imageGen.local carries hand-edit-only render knobs this tab never
// renders (steps / guidance / quantize, read by fableLoom/production.js).
- // Rebuilding the slice from the rendered fields alone wipes them on every
- // Media save. The server can't see this — it validates whatever arrives.
+ // The slice PATCH merges per field, so the drawer neither re-sends a
+ // snapshot of them nor omits them into oblivion.
getSettings.mockResolvedValue({
imageGen: {
mode: 'local',
@@ -425,19 +448,14 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.change(screen.getByLabelText('Default model'), { target: { value: 'flux2-klein-4b' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- const local = updateSettings.mock.calls[0][0].imageGen.local;
- expect(local).toMatchObject({ steps: 28, guidance: 4.5, quantize: '4' });
- expect(local.modelId).toBe('flux2-klein-4b');
- expect(local.pythonPath).toBe('/usr/bin/python3');
- });
-
- it('the videoGen save body round-trips sibling keys the tab does not edit (#3231 Phase 4)', async () => {
- // The settings PUT replaces top-level slices wholesale, so if this wire
- // body ever drops the loaded slice's sibling keys, a Defaults-tab save
- // erases videoGen.defaultModelId (read by pipeline video stages). The
- // server suite can't see this — it validates whatever body arrives — so
- // the exact wire body is pinned HERE.
+ await awaitSave();
+ expect(sentSlices()).toEqual({ 'imageGen.local': { modelId: 'flux2-klein-4b' } });
+ });
+
+ it('the videoGen save body carries only the changed pin (#3231 Phase 4)', async () => {
+ // A Defaults-tab save that re-sent the loaded slice would overwrite a
+ // videoGen.defaultModelId another surface changed after this drawer
+ // opened. The exact wire body is pinned HERE.
getSettings.mockResolvedValue({
imageGen: { mode: 'external', external: { sdapiUrl: 'http://localhost:7860' } },
videoGen: { mode: 'grok', defaultModelId: 'ltx23_distilled_q4' },
@@ -447,13 +465,10 @@ describe('ImageGenTab grouped tabs', () => {
expect(videoSelect.value).toBe('grok');
fireEvent.change(videoSelect, { target: { value: 'local' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- const patch = updateSettings.mock.calls[0][0];
+ await awaitSave();
// fal/reactor keys are no longer part of this save body (#8997) — they
// move through the write-only credential setter instead.
- expect(patch.videoGen).toEqual({
- mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: false,
- });
+ expect(sentSlices()).toEqual({ videoGen: { mode: 'local' } });
});
});
@@ -545,7 +560,7 @@ describe('ImageGenTab — Test Render backend picker (#4128)', () => {
fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
fireEvent.click(screen.getByLabelText(/Enable Grok/i));
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ await awaitSave();
fireEvent.click(screen.getByRole('tab', { name: /^Test$/i }));
const select = screen.getByLabelText('Backend');
@@ -571,12 +586,8 @@ describe('ImageGenTab — Agy CLI section', () => {
expect(modelInput.value).toBe('gemini-image');
fireEvent.change(modelInput, { target: { value: 'custom/image-v3' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- expect(updateSettings.mock.calls[0][0].imageGen.agy).toEqual(expect.objectContaining({
- enabled: true,
- agyPath: '/opt/agy',
- model: 'custom/image-v3',
- }));
+ await awaitSave();
+ expect(sentSlices()).toEqual({ 'imageGen.agy': { model: 'custom/image-v3' } });
});
it('render-defaults tab pins a backend + model per surface and saves the slice (#3231)', async () => {
@@ -594,12 +605,25 @@ describe('ImageGenTab — Agy CLI section', () => {
const modelInput = screen.getByLabelText('Sprite references & anchors model');
fireEvent.change(modelInput, { target: { value: 'gemini-3.6-flash-low' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- // The saved wire body carries exactly the pinned entries — no 'auto' no-ops.
- expect(updateSettings.mock.calls[0][0].renderDefaults).toEqual({
- 'universe-bible': { imageMode: 'codex' },
- 'sprite-reference': { imageMode: 'agy', imageModel: 'gemini-3.6-flash-low' },
+ await awaitSave();
+ // The wire body carries exactly the changed target — the untouched
+ // universe-bible pin is not re-sent, and no 'auto' no-ops travel.
+ expect(sentSlices()).toEqual({
+ renderDefaults: { 'sprite-reference': { imageMode: 'agy', imageModel: 'gemini-3.6-flash-low' } },
+ });
+ });
+
+ it('clears a render-default pin with an explicit null entry (#12030)', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { mode: 'local' },
+ renderDefaults: { 'universe-bible': { imageMode: 'codex' } },
});
+ await renderTab(['/media/image?mediaTab=defaults']);
+ const bibleSelect = await screen.findByLabelText('Universe Bible & canon renders');
+ fireEvent.change(bibleSelect, { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+ await awaitSave();
+ expect(sentSlices()).toEqual({ renderDefaults: { 'universe-bible': null } });
});
it('grok pins never show a model input — its backend has no model knob (#3231)', async () => {
@@ -657,11 +681,8 @@ describe('ImageGenTab — Grok CLI section (#2859)', () => {
fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
fireEvent.change(screen.getByPlaceholderText('grok (uses $PATH)'), { target: { value: '/usr/local/bin/grok' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- const patch = updateSettings.mock.calls[0][0];
- expect(patch.imageGen.grok).toEqual(expect.objectContaining({
- enabled: true, grokPath: '/usr/local/bin/grok', aspectRatio: '16:9',
- }));
+ await awaitSave();
+ expect(sentSlices()).toEqual({ 'imageGen.grok': { grokPath: '/usr/local/bin/grok' } });
});
it('falls the mode back to local when grok is disabled while active', async () => {
@@ -676,10 +697,8 @@ describe('ImageGenTab — Grok CLI section (#2859)', () => {
fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
fireEvent.click(screen.getByLabelText(/Enable Grok Imagegen/i));
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- const patch = updateSettings.mock.calls[0][0];
- expect(patch.imageGen.grok.enabled).toBe(false);
- expect(patch.imageGen.mode).toBe('local');
+ await awaitSave();
+ expect(sentSlices()).toEqual({ imageGen: { mode: 'local' }, 'imageGen.grok': { enabled: false } });
});
});
@@ -703,10 +722,10 @@ describe('ImageGenTab — fal.ai section', () => {
fireEvent.click(screen.getByLabelText(/Enable fal\.ai Imagegen/i));
fireEvent.change(screen.getByLabelText(/Default model/i), { target: { value: 'fal-ai/bytedance/seedream/v5/lite/text-to-image' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
- await waitFor(() => expect(updateSettings).toHaveBeenCalled());
- expect(updateSettings.mock.calls[0][0].imageGen.fal).toEqual(expect.objectContaining({
+ await awaitSave();
+ expect(sentSlices()['imageGen.fal']).toEqual({
enabled: true, model: 'fal-ai/bytedance/seedream/v5/lite/text-to-image',
- }));
+ });
fireEvent.click(screen.getByRole('tab', { name: /Backend/i }));
expect(screen.getByText(/Hosted image and reference-edit models through fal\.ai/i)).toBeTruthy();
});
diff --git a/docs/API.md b/docs/API.md
index 8f06bb061a..4f0ed2d799 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -39,8 +39,14 @@ replace that key; explicit null/empty values clear fields where their schema all
Unreadable/malformed persisted settings and failed writes return errors.
Supported paths are `localLlm.ollama`, `localLlm.lmstudio`, `localLlm.llama`,
-`localLlm.mtplx`, `localLlm.slotstream`, `imageGen.local`, `pipeline`,
+`localLlm.mtplx`, `localLlm.slotstream`, `imageGen`, `imageGen.external`,
+`imageGen.local`, `imageGen.codex`, `imageGen.grok`, `imageGen.agy`,
+`imageGen.fal`, `imageGen.expose`, `renderDefaults`, `videoGen`, `pipeline`,
`writersRoom`, `seriesAutopilot`, `pipelineEditorialChecks`, and `autoUpdate`.
+The Media settings drawer saves only the fields the user changed through these,
+one slice per request, so a value a sibling panel patched after the drawer
+opened is never overwritten by a stale snapshot. A `renderDefaults` target sent
+as `null` clears that surface's pin.
Only the current controls' fields are accepted; credential/auth paths and
prototype-related keys are rejected. Execution-policy and changed executable
fields retain the same operator authority checks as `PUT /api/settings`,
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 702c4f7736..a5e2b63eb4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2106,8 +2106,10 @@ const renderTargetEntrySchema = z.object({
videoMode: videoModePinSchema,
videoModel: renderTargetModelSchema,
});
+// A null entry is an explicit "no pin for this surface": the slice PATCH merges
+// per target, so clearing one must be sent as a value, not an omitted key.
export const renderDefaultsSettingsSchema = z.object(
- Object.fromEntries(RENDER_TARGETS.map((t) => [t, renderTargetEntrySchema.optional()])),
+ Object.fromEntries(RENDER_TARGETS.map((t) => [t, renderTargetEntrySchema.nullable().optional()])),
);
// Install-wide video render pin (`settings.videoGen`, #3231 Phase 4) — the
@@ -2245,9 +2247,42 @@ const renderFormSettingsSchema = z.object({
export const settingsSlicePartialSchemas = Object.freeze({
...Object.fromEntries(Object.entries(localLlmSettingsSchema.shape)
.map(([runtime, schema]) => [`localLlm.${runtime}`, schema.unwrap()])),
+ // The Media settings drawer (ImageGenTab) saves field-by-field through these
+ // so a sibling panel's later patch (VideoGen's LocalSetupPanel writing
+ // `imageGen.local.pythonPath`) survives a drawer save. Cleared strings travel
+ // as '' (every reader falls back on a blank); the two pins that readers
+ // coerce with `||` accept null so an un-pin needs no sentinel string.
+ imageGen: z.object({
+ mode: z.enum(IMAGE_GEN_MODES).optional(),
+ // Legacy flat field, kept populated beside `imageGen.external.sdapiUrl`.
+ sdapiUrl: z.string().max(500).optional(),
+ }).strict(),
+ 'imageGen.external': z.object({
+ sdapiUrl: z.string().max(500).optional(),
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
+ }).strict(),
'imageGen.local': z.object({
pythonPath: z.string().max(500).nullable().optional(),
+ modelId: z.string().max(300).nullable().optional(),
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
+ }).strict(),
+ 'imageGen.codex': z.object({
+ enabled: z.boolean().optional(),
+ codexPath: z.string().max(500).optional(),
+ model: z.string().max(300).optional(),
+ effort: z.string().max(40).optional(),
+ parallelLimit: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
}).strict(),
+ 'imageGen.grok': imageGenGrokSettingsSchema.strict(),
+ 'imageGen.agy': imageGenAgySettingsSchema.strict(),
+ 'imageGen.fal': imageGenFalSettingsSchema.strict(),
+ 'imageGen.expose': z.object({ a1111: z.boolean().optional() }).strict(),
+ renderDefaults: renderDefaultsSettingsSchema,
+ videoGen: videoGenSettingsSchema.pick({ mode: true, defaultModelId: true, displaySleep: true }).strict(),
pipeline: z.object({ imageGen: renderFormSettingsSchema.nullable().optional() }).strict(),
writersRoom: z.object({ imageGen: renderFormSettingsSchema.nullable().optional() }).strict(),
seriesAutopilot: seriesAutopilotSettingsSchema.partial(),
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 63eba10587..be001d7d98 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -1555,13 +1555,44 @@ describe('Settings routes — atomic partial saves (#11045)', () => {
expect(saved.secrets.example).toBe('private-placeholder');
});
+ // The Media settings drawer saves one slice per changed field group; a
+ // sibling panel's later write to a field the drawer did not touch must
+ // survive, and a cleared render-target pin travels as an explicit null.
+ it('merges the Media drawer slices per field and clears a render-target pin with null', async () => {
+ const app = buildApp();
+ expect((await patch(app, 'imageGen.codex', { model: 'gpt-example', parallelLimit: 4 })).status).toBe(200);
+ expect((await patch(app, 'imageGen', { mode: 'codex' })).status).toBe(200);
+ expect((await patch(app, 'imageGen.local', { modelId: 'example-model', cleanC2PA: false })).status).toBe(200);
+ expect((await patch(app, 'imageGen.expose', { a1111: true })).status).toBe(200);
+ expect((await patch(app, 'renderDefaults', { 'universe-bible': { imageMode: 'codex' }, 'sprite-reference': { imageMode: 'agy' } })).status).toBe(200);
+ expect((await patch(app, 'renderDefaults', { 'universe-bible': null })).status).toBe(200);
+ expect((await patch(app, 'videoGen', { defaultModelId: 'example-video', displaySleep: true })).status).toBe(200);
+ expect((await patch(app, 'videoGen', { mode: 'grok' })).status).toBe(200);
+ expect(persisted()).toMatchObject({
+ imageGen: {
+ mode: 'codex',
+ local: { pythonPath: '/example/python3', denoise: true, modelId: 'example-model', cleanC2PA: false },
+ codex: { enabled: true, model: 'gpt-example', parallelLimit: 4 },
+ expose: { a1111: true },
+ },
+ renderDefaults: { 'universe-bible': null, 'sprite-reference': { imageMode: 'agy' } },
+ videoGen: { mode: 'grok', defaultModelId: 'example-video', displaySleep: true },
+ });
+ });
+
it('rejects invalid values, unapproved paths and credential/prototype keys without writes', async () => {
const before = fs.readFileSync(settingsFile, 'utf8');
for (const [path, partial] of [
['secrets.auth', { enabled: false }],
['imageGen', { hfToken: 'example-token' }],
+ ['imageGen', { mode: 'not-a-backend' }],
['imageGen.local', { hfToken: 'example-token' }],
['imageGen.local', { pythonPath: '/example/sh' }],
+ ['imageGen.codex', { parallelLimitBounds: { min: 1, max: 1 } }],
+ ['imageGen.grok', { aspectRatio: 'wide' }],
+ ['renderDefaults', { 'universe-bible': { imageMode: 'not-a-backend' } }],
+ ['videoGen', { acceptedModelTerms: [] }],
+ ['videoGen', { mode: 'not-a-backend' }],
['localLlm.mtplx', { idleMinutes: -1 }],
['localLlm.mtplx', { launch: { model: [] } }],
['autoUpdate', { enabled: 'yes' }],