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 music and LoRA caption prefs without overwriting sibling settings

Adam Eivy2483a4a64a08
diff --git a/client/src/components/loraTraining/CaptionModelPicker.jsx b/client/src/components/loraTraining/CaptionModelPicker.jsx
index d45c1f9f8b..6661fa9438 100644
--- a/client/src/components/loraTraining/CaptionModelPicker.jsx
+++ b/client/src/components/loraTraining/CaptionModelPicker.jsx
@@ -9,10 +9,10 @@
* provider+model. "Auto" defers to the server's vision-model auto-pick.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { Loader2, AlertTriangle } from 'lucide-react';
import toast from '../ui/Toast';
-import { getVisionModels, getSettings, updateSettings } from '../../services/api';
+import { getVisionModels, getSettings, patchSettingsSlice } from '../../services/api';
const AUTO = '__auto__';
const keyFor = (m) => `${m.providerId}::${m.id}`;
@@ -21,10 +21,6 @@ export default function CaptionModelPicker({ onChange }) {
const [models, setModels] = useState(null); // null = loading; [] = none installed
const [value, setValue] = useState(AUTO);
const [saving, setSaving] = useState(false);
- // Preserve the rest of settings.loraTraining (training `defaults`) on save —
- // updateSettings merges shallowly at the top level, so writing just the
- // caption fields would clobber the sibling slice.
- const loraTrainingRef = useRef({});
useEffect(() => {
let alive = true;
@@ -35,7 +31,6 @@ export default function CaptionModelPicker({ onChange }) {
if (!alive) return;
const list = vm?.models || [];
setModels(list);
- loraTrainingRef.current = settings?.loraTraining || {};
const savedModel = settings?.loraTraining?.captionModel || null;
const savedProvider = settings?.loraTraining?.captionProviderId || null;
if (savedModel) {
@@ -58,14 +53,14 @@ export default function CaptionModelPicker({ onChange }) {
const picked = next === AUTO ? null : (models || []).find((m) => keyFor(m) === next) || null;
onChange?.(picked ? { providerId: picked.providerId, model: picked.id } : { providerId: null, model: null });
setSaving(true);
- const nextLoraTraining = {
- ...loraTrainingRef.current,
- captionProviderId: picked ? picked.providerId : null,
- captionModel: picked ? picked.id : null,
- };
+ // A slice patch, merged server-side into the stored `loraTraining`, so the
+ // hand-set training knobs beside these two keys survive even when the
+ // settings read above failed.
try {
- await updateSettings({ loraTraining: nextLoraTraining }, { silent: true });
- loraTrainingRef.current = nextLoraTraining;
+ await patchSettingsSlice('loraTraining', {
+ captionProviderId: picked ? picked.providerId : null,
+ captionModel: picked ? picked.id : null,
+ }, { silent: true });
} catch {
toast.error('Could not save caption-model preference');
} finally {
diff --git a/client/src/components/music/ChiptunePanel.jsx b/client/src/components/music/ChiptunePanel.jsx
index cba37e776f..96e6cf47f9 100644
--- a/client/src/components/music/ChiptunePanel.jsx
+++ b/client/src/components/music/ChiptunePanel.jsx
@@ -21,7 +21,7 @@ import { buildChiptuneSchedule, createChiptunePlayer } from '../../lib/chiptuneP
import { formatTimecode } from '../../utils/formatters';
import {
generateTrackChiptune, renderTrackChiptune, publishTrackChiptune,
- getApps, getSettings, updateSettings,
+ getApps, getSettings, patchSettingsSlice,
} from '../../services/api';
const slugify = (s) => String(s || '').toLowerCase().trim().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
@@ -50,7 +50,6 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePromp
// hook auto-selects a default when its list arrives, so applying the pin
// immediately would race that load and be nondeterministically overwritten.
const [savedPin, setSavedPin] = useState(null);
- const musicSettingsRef = useRef({});
// StrictMode-safe (re-armed on remount) — a plain `useRef(true)` + cleanup
// would stay false after StrictMode's dev double-mount and wedge every
// post-await state update.
@@ -100,9 +99,7 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePromp
useEffect(() => {
getSettings({ silent: true }).then((settings) => {
if (!mountedRef.current) return;
- const music = settings?.music || {};
- musicSettingsRef.current = music;
- const saved = music.chiptune || {};
+ const saved = settings?.music?.chiptune || {};
if (saved.providerId) setSavedPin({ providerId: saved.providerId, model: saved.model || '' });
if (saved.publishAppId) setPublishAppId(saved.publishAppId);
if (saved.publishSubdir) setPublishSubdir(saved.publishSubdir);
@@ -174,11 +171,10 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePromp
return () => cancelAnimationFrame(raf);
}, [playing, idleTotalSec]);
+ // The server merges into the stored `music.chiptune`, so neither a failed
+ // prefs load nor the Music Designer's own saves can be overwritten from here.
const persistChiptunePrefs = (patch) => {
- const music = musicSettingsRef.current;
- const next = { ...music, chiptune: { ...(music.chiptune || {}), ...patch } };
- musicSettingsRef.current = next;
- updateSettings({ music: next }, { silent: true }).catch(() => {});
+ patchSettingsSlice('music.chiptune', patch, { silent: true }).catch(() => {});
};
const handleGenerate = async () => {
diff --git a/client/src/components/music/ChiptunePanel.test.jsx b/client/src/components/music/ChiptunePanel.test.jsx
index d147664f93..4145747d3b 100644
--- a/client/src/components/music/ChiptunePanel.test.jsx
+++ b/client/src/components/music/ChiptunePanel.test.jsx
@@ -25,7 +25,7 @@ vi.mock('../../services/api', () => ({
publishTrackChiptune: vi.fn(),
getApps: vi.fn(),
getSettings: vi.fn(),
- updateSettings: vi.fn(),
+ patchSettingsSlice: vi.fn(),
}));
vi.mock('../../hooks/useProviderModels', () => ({
@@ -65,7 +65,7 @@ describe('ChiptunePanel', () => {
audio.loopSec = 0;
api.getSettings.mockResolvedValue({ music: {} });
api.getApps.mockResolvedValue([GAME_APP]);
- api.updateSettings.mockResolvedValue({});
+ api.patchSettingsSlice.mockResolvedValue({});
});
it('baseline: enables Generate, Render, and Publish when nothing is in flight', async () => {
@@ -145,6 +145,10 @@ describe('ChiptunePanel', () => {
{ appId: 'game-app', subdir: 'game/assets/music', slug: 'my-test-song' },
{ silent: true },
);
+ // Only the panel's own sub-slice is sent; the server merges it.
+ await waitFor(() => expect(api.patchSettingsSlice).toHaveBeenCalledWith(
+ 'music.chiptune', { publishAppId: 'game-app', publishSubdir: 'game/assets/music' }, { silent: true },
+ ));
});
});
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsx
index 54fa5c2ccf..3539ef2e7a 100644
--- a/client/src/components/music/MusicDesigner.jsx
+++ b/client/src/components/music/MusicDesigner.jsx
@@ -44,7 +44,7 @@ import useMounted from '../../hooks/useMounted';
import useProviderModels from '../../hooks/useProviderModels';
import { safeReadStorage, safeRemoveStorage, safeWriteStorage } from '../../lib/safeStorage.js';
import {
- createTrack, describeMusic, generateLyrics, getSettings, getTrack, updateSettings, updateTrack,
+ createTrack, describeMusic, generateLyrics, getSettings, getTrack, patchSettingsSlice, updateTrack,
} from '../../services/api';
const STEPS = [
@@ -123,7 +123,6 @@ export default function MusicDesigner() {
// auto-selects a default when its list arrives, so applying immediately would
// race that load (same pattern as ChiptunePanel).
const [savedPin, setSavedPin] = useState(null);
- const musicSettingsRef = useRef({});
const stepFromUrl = STEP_IDS.includes(id) ? id : FIRST_STEP;
@@ -184,9 +183,7 @@ export default function MusicDesigner() {
useEffect(() => {
getSettings({ silent: true }).then((settings) => {
if (!mountedRef.current) return;
- const music = settings?.music || {};
- musicSettingsRef.current = music;
- const saved = music.designer || {};
+ const saved = settings?.music?.designer || {};
if (saved.describeTemplate) setDescribeTemplate(saved.describeTemplate);
if (saved.lyricsTemplate) setLyricsTemplate(saved.lyricsTemplate);
if (saved.providerId) {
@@ -214,11 +211,10 @@ export default function MusicDesigner() {
setSavedPin(null); // apply once
}, [savedPin, providersLoading, providers, setSelectedProviderId, setSelectedModel]);
+ // The server merges into the stored `music.designer`, so saving one template
+ // cannot drop the other or the Chiptune panel's prefs, even after a failed load.
const persistDesignerPrefs = (patch) => {
- const music = musicSettingsRef.current;
- const next = { ...music, designer: { ...(music.designer || {}), ...patch } };
- musicSettingsRef.current = next;
- updateSettings({ music: next }, { silent: true }).catch((err) => toast.error(err?.message || 'Could not save Music Designer preferences'));
+ patchSettingsSlice('music.designer', patch, { silent: true }).catch((err) => toast.error(err?.message || 'Could not save Music Designer preferences'));
};
const saveDraft = (patch) => {
diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsx
index 9fca822219..6c5b798445 100644
--- a/client/src/components/music/MusicDesigner.test.jsx
+++ b/client/src/components/music/MusicDesigner.test.jsx
@@ -11,7 +11,7 @@ vi.mock('../../services/api', () => ({
generateLyrics: vi.fn(),
getSettings: vi.fn(),
getTrack: vi.fn(),
- updateSettings: vi.fn(),
+ patchSettingsSlice: vi.fn(),
updateTrack: vi.fn(),
}));
@@ -87,7 +87,7 @@ describe('<MusicDesigner>', () => {
api.getSettings.mockResolvedValue({ music: {} });
api.createTrack.mockResolvedValue({ id: 'track-draft', title: 'Untitled music draft', concept: '', prompt: '', lyrics: '' });
api.getTrack.mockResolvedValue({ id: 'track-draft', title: 'Untitled music draft', concept: '', prompt: '', lyrics: '' });
- api.updateSettings.mockResolvedValue({});
+ api.patchSettingsSlice.mockResolvedValue({});
api.updateTrack.mockResolvedValue({ id: 'track-draft', title: 'Untitled music draft' });
});
@@ -262,7 +262,7 @@ describe('<MusicDesigner>', () => {
fireEvent.click(screen.getByRole('button', { name: /describe it/i }));
await findEnabledByLabelText(/music description/i);
expect(api.describeMusic).toHaveBeenCalledWith(expect.objectContaining({ concept, guidance: ' Soft pulse ', template }), { silent: true });
- expect(api.updateSettings).toHaveBeenCalledWith(expect.objectContaining({ music: expect.objectContaining({ designer: expect.objectContaining({ describeTemplate: template }) }) }), { silent: true });
+ expect(api.patchSettingsSlice).toHaveBeenCalledWith('music.designer', { describeTemplate: template }, { silent: true });
await waitFor(() => expect(api.updateTrack).toHaveBeenCalledWith('track-draft', { concept }, { silent: true }));
const edited = description + 'Keep my ending. ';
fireEvent.change(screen.getByLabelText(/music description/i), { target: { value: edited } });
@@ -351,8 +351,9 @@ describe('<MusicDesigner>', () => {
fireEvent.change(await findEnabledByLabelText(/what do you want to hear/i), { target: { value: 'x' } });
fireEvent.click(screen.getByRole('button', { name: /describe it/i }));
- await waitFor(() => expect(api.updateSettings).toHaveBeenCalledWith(
- { music: { designer: { providerId: 'provider-a', model: 'model-a', effort: '' } } },
+ await waitFor(() => expect(api.patchSettingsSlice).toHaveBeenCalledWith(
+ 'music.designer',
+ { providerId: 'provider-a', model: 'model-a', effort: '' },
{ silent: true },
));
});
diff --git a/docs/API.md b/docs/API.md
index ce95f9b7ce..9d80183f63 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -42,10 +42,13 @@ Supported paths are `localLlm.ollama`, `localLlm.lmstudio`, `localLlm.llama`,
`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
+`writersRoom`, `seriesAutopilot`, `pipelineEditorialChecks`, `autoUpdate`,
+`music.chiptune`, `music.designer`, and `loraTraining` (its caption-model keys
+only). 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. The Chiptune panel, the Music
+Designer and the LoRA caption-model picker save the same way, so none of them can
+drop another's prefs or the hand-set LoRA training knobs. 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
diff --git a/server/lib/validation.js b/server/lib/validation.js
index ef6da6cf86..0f72a7c34b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -7,6 +7,7 @@ import { z } from 'zod';
import { NOTIFICATION_TYPES } from './notificationTypes.js';
import { POLLUTING_KEYS } from './objects.js';
import { pipelineEditorialChecksSettingsSchema } from './pipelineValidation.js';
+import { loraTrainingConfigSchema } from './mediaValidation.js';
import { ServerError } from './errorHandler.js';
import { isSafeGitRef } from './gitArgs.js';
import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap, presetProviderIdSchema, providerRefSchema } from './zodCompat.js';
@@ -2302,6 +2303,13 @@ export const settingsSlicePartialSchemas = Object.freeze({
seriesAutopilot: seriesAutopilotSettingsSchema.partial(),
pipelineEditorialChecks: pipelineEditorialChecksSettingsSchema.partial(),
autoUpdate: autoUpdateSettingsSchema,
+ // The Chiptune panel and the Music Designer each own one sub-slice, so a save
+ // from either cannot drop the other's prefs or a template saved elsewhere.
+ 'music.chiptune': musicSettingsSchema.shape.chiptune.unwrap().strict(),
+ 'music.designer': musicSettingsSchema.shape.designer.unwrap().strict(),
+ // The caption-model picker owns only these two keys; the rest of the slice
+ // (training defaults, segmentation, watchdog, display sleep) is hand-set.
+ loraTraining: loraTrainingConfigSchema.pick({ captionProviderId: true, captionModel: true }).strict(),
});
// Check raw JSON before Zod can strip a dangerous key. Arrays can contain
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 9d4325113d..81335b3c1e 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -1581,6 +1581,29 @@ describe('Settings routes — atomic partial saves (#11045)', () => {
});
});
+ // Each music panel and the LoRA caption picker patch only the keys they own,
+ // so a save from one never drops a sibling's prefs or the hand-set knobs.
+ it('merges the music and LoRA caption prefs into their owned sub-slices', async () => {
+ fs.writeFileSync(settingsFile, JSON.stringify({
+ music: { designer: { describeTemplate: 'Example describe', lyricsTemplate: 'Example lyrics' }, chiptune: { publishSubdir: 'game/assets/music' } },
+ loraTraining: { displaySleep: false, segmentation: false, defaults: { steps: 1200 } },
+ }));
+ actual.__resetSettingsCache();
+ const app = buildApp();
+ expect((await patch(app, 'music.chiptune', { providerId: 'example-provider', model: 'example-model' })).status).toBe(200);
+ expect((await patch(app, 'music.designer', { describeTemplate: 'Example revised' })).status).toBe(200);
+ expect((await patch(app, 'loraTraining', { captionProviderId: 'example-provider', captionModel: 'example-vision' })).status).toBe(200);
+ expect(persisted()).toMatchObject({
+ music: {
+ designer: { describeTemplate: 'Example revised', lyricsTemplate: 'Example lyrics' },
+ chiptune: { publishSubdir: 'game/assets/music', providerId: 'example-provider', model: 'example-model' },
+ },
+ loraTraining: {
+ displaySleep: false, segmentation: false, defaults: { steps: 1200 }, captionProviderId: 'example-provider', captionModel: 'example-vision',
+ },
+ });
+ });
+
it('rejects invalid values, unapproved paths and credential/prototype keys without writes', async () => {
const before = fs.readFileSync(settingsFile, 'utf8');
for (const [path, partial] of [
@@ -1604,6 +1627,9 @@ describe('Settings routes — atomic partial saves (#11045)', () => {
['pipeline', JSON.parse('{"imageGen":{"constructor":{}}}')],
['pipeline', JSON.parse('{"__proto__":{"polluted":true}}')],
['pipeline', { imageGen: { steps: 'not-a-number' } }],
+ ['music.chiptune', { describeTemplate: 'Example template' }],
+ ['music.designer', { describeTemplate: 'x'.repeat(8001) }],
+ ['loraTraining', { displaySleep: true }],
]) {
expect((await patch(buildApp(), path, partial)).status, path).toBe(400);
}