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

refactor([patch-settings-slice-helper]): add patchSettingsSlice helper and migrate clobber-prone callers

[._.]/ Adam Eivy1fac092591b6
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index 0658bba9af..2dc99c8561 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -24,7 +24,7 @@ import {
PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
-import { getSettings, updateSettings } from '../../../services/apiSystem';
+import { getSettings, patchSettingsSlice } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import MediaJobThumb from '../MediaJobThumb';
import MediaPreview from '../../media/MediaPreview';
@@ -247,11 +247,8 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
const persistImageCfg = useCallback(async (next) => {
setImageCfg(next);
- const current = await getSettings().catch(() => ({}));
- await updateSettings({
- ...current,
- pipeline: { ...(current.pipeline || {}), imageGen: next },
- }).catch((err) => toast.error(`Settings save failed: ${err.message}`));
+ await patchSettingsSlice('pipeline', { imageGen: next })
+ .catch((err) => toast.error(`Settings save failed: ${err.message}`));
}, []);
// URL-driven drawer state — mirrors StoryboardPanel so the settings panel
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index 8e2382f4c2..133b953086 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -24,7 +24,7 @@ import {
extractUniverseCanon, refineUniverseCharacter,
getUniverseSeriesNames,
} from '../../../services/apiUniverseBuilder';
-import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';
+import { getSettings, patchSettingsSlice, generateImage } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import {
matchCharactersInText, matchPlacesInText, matchObjectsInText,
@@ -177,11 +177,8 @@ export default function NounsStage({ issue, series }) {
const persistImageCfg = useCallback(async (next) => {
setImageCfg(next);
- const current = await getSettings().catch(() => ({}));
- await updateSettings({
- ...current,
- pipeline: { ...(current.pipeline || {}), imageGen: next },
- }).catch((err) => toast.error(`Settings save failed: ${err.message}`));
+ await patchSettingsSlice('pipeline', { imageGen: next })
+ .catch((err) => toast.error(`Settings save failed: ${err.message}`));
}, []);
const [searchParams, setSearchParams] = useSearchParams();
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 5819a8341a..4641e1ec8e 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -11,7 +11,7 @@ import {
listWritersRoomAnalyses,
getWritersRoomAnalysis,
} from '../../services/apiWritersRoom';
-import { getSettings, updateSettings, listImageStylePresets } from '../../services/apiSystem';
+import { getSettings, patchSettingsSlice, listImageStylePresets } from '../../services/apiSystem';
import { listImageModels } from '../../services/apiImageVideo';
import BackendChipStrip from '../media/BackendChipStrip';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
@@ -244,11 +244,8 @@ export default function StoryboardPanel({
const persistCfg = useCallback(async (next) => {
setImageCfg(next);
- const current = await getSettings().catch(() => ({}));
- await updateSettings({
- ...current,
- writersRoom: { ...(current.writersRoom || {}), imageGen: next },
- }).catch((err) => toast.error(`Settings save failed: ${err.message}`));
+ await patchSettingsSlice('writersRoom', { imageGen: next })
+ .catch((err) => toast.error(`Settings save failed: ${err.message}`));
}, []);
const charByKey = useMemo(() => buildCharByKey(characters), [characters]);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 782ba606f6..94ad175675 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -55,7 +55,7 @@ import {
listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,
upscaleVideo,
listImageGallery,
- getSettings, updateSettings,
+ getSettings, patchSettingsSlice,
getActiveVideoJob,
} from '../services/api';
import { randomSeed, safeParseJSON } from '../lib/genUtils';
@@ -545,20 +545,8 @@ export default function VideoGen() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- // Settings PUT shallow-merges top-level keys, so the full imageGen slice
- // must round-trip — otherwise mode/external/codex/expose get clobbered.
const handleSavePythonPath = useCallback(async (path) => {
- const current = await getSettings({ silent: true }).catch(() => ({}));
- const imageGen = current?.imageGen || {};
- await updateSettings(
- {
- imageGen: {
- ...imageGen,
- local: { ...(imageGen.local || {}), pythonPath: path || undefined },
- },
- },
- { silent: true },
- )
+ await patchSettingsSlice('imageGen.local', { pythonPath: path || undefined }, { silent: true })
.then(() => refreshStatus())
.catch((err) => toast.error(`Failed to save: ${err.message}`));
}, [refreshStatus]);
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index d23fafc3de..619933af5c 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -39,6 +39,32 @@ export const updateSettings = (data, options) => request('/settings', {
...options
});
+// PUT /api/settings shallow-merges top-level keys only — patching
+// `{ imageGen: { local: { pythonPath } } }` directly clobbers the rest of
+// `imageGen`. patchSettingsSlice fetches current settings, walks to the slice
+// at a dotted path, shallow-merges `partial` into it, and PUTs the rebuilt
+// top-level key so sibling subkeys survive. `options` flows through to the
+// final updateSettings (e.g. `{ silent: true }`).
+export const patchSettingsSlice = async (slicePath, partial, options = {}) => {
+ if (typeof slicePath !== 'string' || !slicePath) {
+ throw new Error('patchSettingsSlice: slicePath required');
+ }
+ if (partial == null || typeof partial !== 'object' || Array.isArray(partial)) {
+ throw new Error('patchSettingsSlice: partial must be a plain object');
+ }
+ const segments = slicePath.split('.');
+ const current = await getSettings({ silent: true }).catch(() => ({}));
+ let existing = current;
+ for (const seg of segments) existing = existing?.[seg];
+ let updated = { ...(existing || {}), ...partial };
+ for (let i = segments.length - 1; i > 0; i--) {
+ let parent = current;
+ for (let j = 0; j < i; j++) parent = parent?.[segments[j]];
+ updated = { ...(parent || {}), [segments[i]]: updated };
+ }
+ return updateSettings({ [segments[0]]: updated }, options);
+};
+
// Usage
export const getUsage = () => request('/usage');
export const getUsageRaw = () => request('/usage/raw');
diff --git a/client/src/services/apiSystem.test.js b/client/src/services/apiSystem.test.js
new file mode 100644
index 0000000000..7aee670e42
--- /dev/null
+++ b/client/src/services/apiSystem.test.js
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./apiCore.js', () => ({
+ request: vi.fn(),
+}));
+
+let request;
+let patchSettingsSlice;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ request } = await import('./apiCore.js'));
+ ({ patchSettingsSlice } = await import('./apiSystem.js'));
+ request.mockReset();
+});
+
+const mockSettings = (settings) => {
+ request.mockImplementation((path, opts) => {
+ if (path === '/settings' && (!opts || opts.method !== 'PUT')) {
+ return Promise.resolve(settings);
+ }
+ return Promise.resolve({ ok: true });
+ });
+};
+
+describe('patchSettingsSlice', () => {
+ it('preserves sibling subkeys when patching a deep slice', async () => {
+ mockSettings({
+ imageGen: {
+ mode: 'codex',
+ external: { sdapiUrl: 'http://x' },
+ local: { pythonPath: '/old', denoise: true },
+ codex: { enabled: true },
+ },
+ });
+ await patchSettingsSlice('imageGen.local', { pythonPath: '/new' });
+ const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');
+ expect(putCall).toBeDefined();
+ const body = JSON.parse(putCall[1].body);
+ expect(body).toEqual({
+ imageGen: {
+ mode: 'codex',
+ external: { sdapiUrl: 'http://x' },
+ local: { pythonPath: '/new', denoise: true },
+ codex: { enabled: true },
+ },
+ });
+ });
+
+ it('preserves sibling top-level subkeys when patching a one-level slice', async () => {
+ mockSettings({
+ pipeline: {
+ imageGen: { provider: 'old' },
+ videoGen: { mode: 'i2v' },
+ },
+ unrelated: { keep: true },
+ });
+ await patchSettingsSlice('pipeline', { imageGen: { provider: 'new' } });
+ const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');
+ const body = JSON.parse(putCall[1].body);
+ expect(body).toEqual({
+ pipeline: {
+ imageGen: { provider: 'new' },
+ videoGen: { mode: 'i2v' },
+ },
+ });
+ // Top-level `unrelated` is never in the PUT body — the server merges by
+ // top-level key, so omitting it leaves it untouched on disk.
+ expect(body.unrelated).toBeUndefined();
+ });
+
+ it('creates the slice path when it does not exist yet', async () => {
+ mockSettings({});
+ await patchSettingsSlice('writersRoom.imageGen', { foo: 'bar' });
+ const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');
+ const body = JSON.parse(putCall[1].body);
+ expect(body).toEqual({ writersRoom: { imageGen: { foo: 'bar' } } });
+ });
+
+ it('falls back to an empty slice when getSettings rejects', async () => {
+ request.mockImplementation((path, opts) => {
+ if (path === '/settings' && (!opts || opts.method !== 'PUT')) {
+ return Promise.reject(new Error('boom'));
+ }
+ return Promise.resolve({ ok: true });
+ });
+ await patchSettingsSlice('imageGen.local', { pythonPath: '/x' });
+ const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');
+ const body = JSON.parse(putCall[1].body);
+ expect(body).toEqual({ imageGen: { local: { pythonPath: '/x' } } });
+ });
+
+ it('passes options through to updateSettings', async () => {
+ mockSettings({});
+ await patchSettingsSlice('backup', { destPath: '/tmp' }, { silent: true });
+ const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');
+ expect(putCall[1].silent).toBe(true);
+ });
+
+ it('throws on missing slicePath', async () => {
+ await expect(patchSettingsSlice('', {})).rejects.toThrow(/slicePath required/);
+ });
+
+ it('throws on non-object partial', async () => {
+ await expect(patchSettingsSlice('imageGen', null)).rejects.toThrow(/plain object/);
+ await expect(patchSettingsSlice('imageGen', [])).rejects.toThrow(/plain object/);
+ await expect(patchSettingsSlice('imageGen', 'foo')).rejects.toThrow(/plain object/);
+ });
+});