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([settings-getsave-callers-stale-base]): queue settings read-modify-write for the four external-read callers

[._.]/ Adam Eivy4302b127e44e
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 8a3f0f801c..58c9ebe118 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -21,7 +21,7 @@ import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveImageCleaners } from '../services/imageGen/index.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
-import { getSettings, saveSettings } from '../services/settings.js';
+import { getSettings, updateSettingsWith } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
import { getImageModels, isFlux2, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';
import { usesDiffusersRunner } from '../lib/runners.js';
@@ -720,20 +720,20 @@ const hfTokenSchema = z.object({
});
router.post('/setup/hf-token', asyncHandler(async (req, res) => {
const { token } = validateRequest(hfTokenSchema, req.body || {});
- const settings = await getSettings();
- await saveSettings({
+ await updateSettingsWith((settings) => ({
...settings,
imageGen: { ...(settings.imageGen || {}), hfToken: token.trim() },
- });
+ }));
res.json({ ok: true, hfTokenPresent: true, source: 'stored' });
}));
// Clear the stored HF token. Falls back to env / CLI tokens if present —
// callers should re-fetch /setup/hf-token-status to see the post-clear state.
router.delete('/setup/hf-token', asyncHandler(async (_req, res) => {
- const settings = await getSettings();
- const { hfToken: _drop, ...restImageGen } = settings.imageGen || {};
- await saveSettings({ ...settings, imageGen: restImageGen });
+ await updateSettingsWith((settings) => {
+ const { hfToken: _drop, ...restImageGen } = settings.imageGen || {};
+ return { ...settings, imageGen: restImageGen };
+ });
const { token, source } = await getHfTokenInfo();
res.json({ ok: true, hfTokenPresent: !!token, source });
}));
diff --git a/server/routes/loras.js b/server/routes/loras.js
index f9eaef5a86..28bd93046e 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -20,7 +20,7 @@ import {
patchLoraSidecar,
} from '../services/loras.js';
import { getSuggestions } from '../services/civitaiSuggestions.js';
-import { getSettings, saveSettings } from '../services/settings.js';
+import { getSettings, updateSettingsWith } from '../services/settings.js';
const router = Router();
@@ -57,23 +57,24 @@ const authPostSchema = z.object({ apiKey: z.string().min(1).max(256) });
router.post('/auth/civitai', asyncHandler(async (req, res) => {
const { apiKey } = validateRequest(authPostSchema, req.body);
// Shared deepMerge so future civitai sub-fields don't get clobbered by
- // updateSettings' shallow-merge contract (see lib/objects.js).
- const current = await getSettings();
- await saveSettings(deepMerge(current, { civitai: { apiKey: apiKey.trim() } }));
+ // updateSettings' shallow-merge contract (see lib/objects.js). Runs inside the
+ // settings write queue so a concurrent save can't clobber it with a stale base.
+ await updateSettingsWith((current) => deepMerge(current, { civitai: { apiKey: apiKey.trim() } }));
res.json({ hasKey: true, source: 'settings' });
}));
router.delete('/auth/civitai', asyncHandler(async (_req, res) => {
- const current = await getSettings();
- const next = { ...current };
- // typeof === 'object' is true for arrays — guard explicitly so a
- // legacy/malformed `civitai: ['x']` value doesn't get spread into
- // `{ '0': 'x', apiKey: undefined }`.
- if (isPlainObject(next.civitai)) {
- const { apiKey: _omit, ...rest } = next.civitai;
- next.civitai = rest;
- }
- await saveSettings(next);
+ await updateSettingsWith((current) => {
+ const next = { ...current };
+ // typeof === 'object' is true for arrays — guard explicitly so a
+ // legacy/malformed `civitai: ['x']` value doesn't get spread into
+ // `{ '0': 'x', apiKey: undefined }`.
+ if (isPlainObject(next.civitai)) {
+ const { apiKey: _omit, ...rest } = next.civitai;
+ next.civitai = rest;
+ }
+ return next;
+ });
// The env var (if set) still wins after a delete — surface that so the
// UI can explain "you cleared the saved key but CIVITAI_API_KEY is still
// active in the shell environment."
diff --git a/server/services/settings.js b/server/services/settings.js
index 0bac7212fb..c2ca56ad51 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -108,3 +108,20 @@ export const updateSettings = (patch) => queueWrite(async () => {
const merged = { ...raw, ...incoming };
return save(merged);
});
+
+// Read-modify-write INSIDE the write queue. For callers whose merge semantics
+// `updateSettings`' shallow `{ ...raw, ...patch }` can't express — a deep merge
+// (`deepMerge(current, …)`), or building the next object by spreading/deleting a
+// sub-key. `mutate(current)` receives the freshest stripped settings (same shape
+// `getSettings()` returns) and returns the FULL next settings object to persist.
+//
+// This closes the stale-base window in the old `getSettings() → modify →
+// saveSettings(...)` pattern: there, a concurrent `updateSettings` landing
+// between the external read and the queued write was clobbered by the caller's
+// stale pre-image. Here the read and the write share one queued turn, so the
+// mutator always sees the latest persisted snapshot.
+export const updateSettingsWith = (mutate) => queueWrite(async () => {
+ const current = stripStoreKeys(await loadRaw());
+ const next = await mutate(current);
+ return save(next);
+});
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 0a3aff53b0..722ed07b56 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -14,7 +14,7 @@ vi.mock('../lib/fileUtils.js', async (importActual) => {
});
import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
-import { getSettings, updateSettings } from './settings.js';
+import { getSettings, updateSettings, updateSettingsWith } from './settings.js';
describe('settings.js', () => {
beforeEach(() => {
@@ -179,6 +179,59 @@ describe('settings.js', () => {
});
});
+ describe('updateSettingsWith', () => {
+ it('hands the mutator the current stripped settings and persists its return', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ civitai: { apiKey: 'old', other: 'keep' } }));
+ let seen;
+ const result = await updateSettingsWith((current) => {
+ seen = current;
+ return { ...current, civitai: { ...current.civitai, apiKey: 'new' } };
+ });
+ expect(seen).toEqual({ civitai: { apiKey: 'old', other: 'keep' } });
+ expect(result).toEqual({ civitai: { apiKey: 'new', other: 'keep' } });
+ expect(JSON.parse(atomicWrite.mock.calls[0][1])).toEqual({ civitai: { apiKey: 'new', other: 'keep' } });
+ });
+
+ it('supports building the next object by deleting a sub-key (no stale spread)', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ imageGen: { hfToken: 'tok', model: 'flux' }, theme: 'dark' }));
+ const result = await updateSettingsWith((current) => {
+ const { hfToken: _drop, ...rest } = current.imageGen || {};
+ return { ...current, imageGen: rest };
+ });
+ expect(result).toEqual({ imageGen: { model: 'flux' }, theme: 'dark' });
+ });
+
+ it('runs the read-modify-write in one queued turn — a racing updateSettings is not clobbered', async () => {
+ // Slow disk: each write reflects onto the next read. If updateSettingsWith
+ // read OUTSIDE the queue (the old getSettings→saveSettings bug), it would
+ // overwrite the interleaved updateSettings patch with its stale base.
+ let current = { base: true };
+ tryReadFile.mockImplementation(async () => JSON.stringify(current));
+ atomicWrite.mockImplementation(async (_path, content) => { current = JSON.parse(content); });
+
+ const [withResult, plainResult] = await Promise.all([
+ updateSettingsWith((c) => ({ ...c, deep: { a: 1 } })),
+ updateSettings({ second: 2 }),
+ ]);
+
+ // Both landed; neither clobbered the other.
+ expect(atomicWrite).toHaveBeenCalledTimes(2);
+ expect(current).toEqual({ base: true, deep: { a: 1 }, second: 2 });
+ // First-queued sees only the base; second-queued sees the first's result.
+ expect(withResult).toEqual({ base: true, deep: { a: 1 } });
+ expect(plainResult).toEqual({ base: true, deep: { a: 1 }, second: 2 });
+ });
+
+ it('strips MortalLoom store keys from the snapshot handed to the mutator', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ goals: [1, 2], theme: 'dark' }));
+ let seen;
+ await updateSettingsWith((current) => { seen = current; return current; });
+ // `goals` is a MortalLoom store key — getSettings strips it, so the mutator
+ // must not see it (matching the getSettings() the old callers read).
+ expect(seen).toEqual({ theme: 'dark' });
+ });
+ });
+
describe('MortalLoom store key pollution guard', () => {
it('strips MortalLoom-store top-level keys on read', async () => {
// Simulates the historical corruption: settings.json contains both