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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: merge the federation settings slice per sub-key so Sharing and Instances stop overwriting each other (#4703)
[._.]/ Adam Eivy3eef5cdf7d47
diff --git a/client/src/components/instances/UnattendedRenderRouting.jsx b/client/src/components/instances/UnattendedRenderRouting.jsxindex 3d26b93c4e..9047de48c8 100644--- a/client/src/components/instances/UnattendedRenderRouting.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.jsx@@ -75,12 +75,11 @@ function routeOptions(peers, kind, field) {*/export default function UnattendedRenderRouting({ peers }) {// `null` = not loaded yet, and NOT the same as `{}` (loaded, nothing routed).- // Conflating them is what would let a failed settings read save a `federation`- // slice rebuilt from an empty object, wiping mediaProvider and- // strictPullAuthorization. `loadFailed` keeps the card visible but read-only- // so the failure is legible instead of silently destructive.+ // Conflating them is what would let a failed settings read save a routing map+ // rebuilt from an empty object, clearing a route this page never saw.+ // `loadFailed` keeps the card visible but read-only so the failure is legible+ // instead of silently destructive.const [routing, setRouting] = useState(null);- const [federation, setFederation] = useState(null);const [loadFailed, setLoadFailed] = useState(false);const [saving, setSaving] = useState(false);@@ -88,7 +87,6 @@ export default function UnattendedRenderRouting({ peers }) {getSettings({ silent: true }).then((settings) => {const slice = isRecord(settings?.federation) ? settings.federation : {};- setFederation(slice);setRouting(isRecord(slice.mediaRouting) ? slice.mediaRouting : {});}).catch(() => setLoadFailed(true));@@ -100,26 +98,21 @@ export default function UnattendedRenderRouting({ peers }) {);const save = async (kind, route) => {- // Belt and braces with the `disabled` below: without a validated snapshot- // there is no federation slice to carry forward, so a save here would- // replace the whole thing.- if (!isRecord(federation) || !isRecord(routing)) return;+ // Belt and braces with the `disabled` below: without a loaded routing map+ // there is nothing to merge this kind onto.+ if (!isRecord(routing)) return;setSaving(true);- // The settings PATCH shallow-merges TOP-LEVEL keys, so `federation` is- // replaced wholesale — this write has to carry the rest of the slice. Re-read- // it immediately before writing rather than trusting the snapshot taken at- // mount: the Sharing tab owns mediaProvider and strict-pull, and a page left- // open across an edit there would otherwise write back the stale values it- // captured.+ // The server merges the `federation` slice per sub-key (#4703), so this+ // patch carries `mediaRouting` alone and can no longer revert the Sharing+ // tab's `mediaProvider` / `strictPullAuthorization`.//- // A FAILED re-read aborts the save. Falling back to the mount snapshot was- // the wrong instinct: it is not "better than sending {}", it is a write of- // known-stale state over whatever is actually on the server, which is how a- // newer mediaProvider or strictPullAuthorization gets silently reverted.- // A SUCCESSFUL response with no `federation` key is a fresh install that has- // simply never opted into anything — the correct base is `{}`, and treating- // it as unreadable would make the very first route unsavable on every- // install. Only a failed request (`null`) aborts.+ // The re-read is still worth its round trip: it merges this kind onto the+ // freshest routing map rather than the one captured at mount, and it turns+ // "settings are unreachable" into a stated error instead of a select that+ // silently snaps back. A FAILED read (`null`) aborts. A SUCCESSFUL response+ // with no `federation` key is a fresh install that has simply never opted+ // into anything — the correct base is `{}`, and treating it as unreadable+ // would make the very first route unsavable on every install.const fresh = await getSettings({ silent: true }).catch(() => null);if (fresh === null) {setSaving(false);@@ -127,12 +120,10 @@ export default function UnattendedRenderRouting({ peers }) {return;}const base = isRecord(fresh.federation) ? fresh.federation : {};- // Merge onto the freshest routing too, so a kind another surface set in the- // meantime isn't reverted by this one's stale copy.const baseRouting = isRecord(base.mediaRouting) ? base.mediaRouting : routing;const nextRouting = { ...baseRouting, [kind]: route };const merged = await updateSettings(- { federation: { ...base, mediaRouting: nextRouting } },+ { federation: { mediaRouting: nextRouting } },{ silent: true },).catch(() => null);setSaving(false);@@ -142,8 +133,7 @@ export default function UnattendedRenderRouting({ peers }) {toast.error('Failed to save unattended render routing');return;}- setRouting(nextRouting);- setFederation(isRecord(merged.federation) ? merged.federation : { ...base, mediaRouting: nextRouting });+ setRouting(isRecord(merged.federation?.mediaRouting) ? merged.federation.mediaRouting : nextRouting);};const savedRoute = (kind) => (isRecord(routing?.[kind]) ? routing[kind] : null);diff --git a/client/src/components/instances/UnattendedRenderRouting.test.jsx b/client/src/components/instances/UnattendedRenderRouting.test.jsxindex 2494468c65..8e571f29ac 100644--- a/client/src/components/instances/UnattendedRenderRouting.test.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.test.jsx@@ -60,7 +60,10 @@ describe('UnattendedRenderRouting', () => {expect(screen.queryByLabelText('Audio')).not.toBeInTheDocument();});- it('saves a chosen route while carrying the rest of the federation slice forward', async () => {+ // #4703 — this page owns `mediaRouting` and nothing else in the slice. It+ // patches that sub-key alone; the server carries the Sharing tab's sub-keys+ // forward, so a save here can no longer revert them.+ it('patches mediaRouting alone rather than rewriting the whole federation slice', async () => {getSettings.mockResolvedValue({federation: { strictPullAuthorization: true, mediaProvider: { enabled: true } },});@@ -71,8 +74,6 @@ describe('UnattendedRenderRouting', () => {await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({federation: {- strictPullAuthorization: true,- mediaProvider: { enabled: true },mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } },},}, { silent: true }));@@ -162,24 +163,26 @@ describe('UnattendedRenderRouting — failure and staleness handling', () => {});describe('UnattendedRenderRouting — writes against the freshest settings', () => {- it('re-reads the federation slice at save time instead of writing a mount-time snapshot', async () => {- // Mounted before the Sharing tab enabled the provider elsewhere.- getSettings.mockResolvedValueOnce({ federation: { mediaProvider: { enabled: false } } });+ // The server merge is per federation SUB-key, so `mediaRouting` still crosses+ // whole. The re-read is what keeps a kind routed from another tab of this same+ // page from being reverted by this one's mount-time copy.+ it('merges the chosen kind onto the freshest routing map, not the mount-time one', async () => {+ // Mounted before another tab routed video.+ getSettings.mockResolvedValueOnce({ federation: { mediaRouting: {} } });render(<UnattendedRenderRouting peers={[peerWith()]} />);const select = await screen.findByLabelText('Image');- getSettings.mockResolvedValueOnce({- federation: { mediaProvider: { enabled: true }, strictPullAuthorization: true },- });+ const videoRoute = { peerId: 'peer-1', engine: 'comfy', modelId: 'svd' };+ getSettings.mockResolvedValueOnce({ federation: { mediaRouting: { video: videoRoute } } });fireEvent.change(select, { target: { value: JSON.stringify(['peer-1', 'comfy', 'sdxl-base']) } });await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({federation: {- // The newer values survive — writing the stale snapshot would have- // reverted mediaProvider.enabled and erased strictPullAuthorization.- mediaProvider: { enabled: true },- strictPullAuthorization: true,- mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } },+ mediaRouting: {+ // Writing the mount-time map would have cleared this.+ video: videoRoute,+ image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' },+ },},}, { silent: true }));});diff --git a/client/src/components/settings/SharingTab.jsx b/client/src/components/settings/SharingTab.jsxindex 4c0f8402b7..fef7b1bd52 100644--- a/client/src/components/settings/SharingTab.jsx+++ b/client/src/components/settings/SharingTab.jsx@@ -58,9 +58,9 @@ export function SharingTab() {const [saving, setSaving] = useState(false);const [strictPull, setStrictPull] = useState(false);const [strictPullSaving, setStrictPullSaving] = useState(false);- // No mount-time copy of the `federation` slice is kept: PATCH replaces that- // key wholesale, so every write here re-reads it immediately beforehand rather- // than carrying a snapshot that another surface may have superseded.+ // No mount-time copy of the whole `federation` slice is kept: this tab owns+ // only `mediaProvider` and `strictPullAuthorization`, and patches those+ // sub-keys alone (the server merges the slice per sub-key, #4703).const [authEnabled, setAuthEnabled] = useState(false);const [musicEngines, setMusicEngines] = useState([]);const [providerSettings, setProviderSettings] = useState({});@@ -105,12 +105,10 @@ export function SharingTab() {setBio(b);setSavedDisplayName(display);setSavedBio(b);- const federation = settings?.federation && typeof settings.federation === 'object' ? settings.federation : {};+ const federation = isRecord(settings?.federation) ? settings.federation : {};setStrictPull(federation.strictPullAuthorization === true);setAuthEnabled(auth?.enabled === true);- const provider = federation.mediaProvider && typeof federation.mediaProvider === 'object'- ? federation.mediaProvider- : {};+ const provider = isRecord(federation.mediaProvider) ? federation.mediaProvider : {};const enabled = provider.enabled === true;const maxQueuedJobs = Number.isInteger(provider.maxQueuedJobs) ? provider.maxQueuedJobs : 2;const models = normalizeSelectedModels(provider.audioModels);@@ -155,16 +153,14 @@ export function SharingTab() {const handleStrictPullToggle = async (next) => {setStrictPullSaving(true);- // Same whole-slice replacement hazard as the provider save below.+ // Same reachability precheck as the provider save below.const fresh = await getSettings({ silent: true }).catch(() => null);if (fresh === null) {setStrictPullSaving(false);toast.error('Could not read current settings — not saved');return;}- const base = isRecord(fresh.federation) ? fresh.federation : {};- const federation = { ...base, strictPullAuthorization: next };- const merged = await updateSettings({ federation }).catch(() => null);+ const merged = await updateSettings({ federation: { strictPullAuthorization: next } }).catch(() => null);setStrictPullSaving(false);if (!merged) return;setStrictPull(next);@@ -213,26 +209,20 @@ export function SharingTab() {...Object.fromEntries(VISUAL_KINDS.map(({ kind, field }) => [field, visualSelections[kind]])),};setProviderSaving(true);- // /api/settings replaces the top-level `federation` slice wholesale, so this- // write has to carry everything else in it. Re-read immediately before- // saving rather than trusting the mount-time snapshot: the Instances page- // owns `mediaRouting`, and a Settings tab left open across a routing change- // would otherwise write back the slice as it looked before, silently- // clearing the route and sending unattended renders back to local.- // A failed read ABORTS: PUT /api/settings replaces the whole `federation`- // key, so writing the mount-time snapshot over it can erase a route the- // Instances page added while this tab sat open. A successful response with- // no `federation` key is a different thing entirely — a fresh install — and- // correctly bases on `{}`.+ // /api/settings merges the `federation` slice per sub-key (#4703), so this+ // write carries `mediaProvider` alone and can no longer clear the+ // `mediaRouting` the Instances page owns.+ //+ // The read stays as a reachability precheck: without it an unreachable+ // server would surface only as a generic save failure, and the user would+ // not know their earlier edits were never loaded. A failed read aborts.const fresh = await getSettings({ silent: true }).catch(() => null);if (fresh === null) {setProviderSaving(false);toast.error('Could not read current settings — provider not saved');return;}- const base = isRecord(fresh.federation) ? fresh.federation : {};- const federation = { ...base, mediaProvider };- const merged = await updateSettings({ federation }, { silent: true }).catch(() => null);+ const merged = await updateSettings({ federation: { mediaProvider } }, { silent: true }).catch(() => null);setProviderSaving(false);if (!merged) {toast.error('Failed to save media provider settings');diff --git a/client/src/components/settings/SharingTab.test.jsx b/client/src/components/settings/SharingTab.test.jsxindex 7872dc5898..b6d4302e12 100644--- a/client/src/components/settings/SharingTab.test.jsx+++ b/client/src/components/settings/SharingTab.test.jsx@@ -42,7 +42,7 @@ describe('SharingTab — federated media provider (#4348)', () => {expect(screen.getByText(/instance password is required/i)).toBeInTheDocument();});- it('persists an allowlisted model while preserving the rest of the federation slice', async () => {+ it('persists an allowlisted model while preserving unknown mediaProvider fields', async () => {getAuthStatus.mockResolvedValue({ enabled: true });getSettings.mockResolvedValue({federation: {@@ -76,10 +76,10 @@ describe('SharingTab — federated media provider (#4348)', () => {fireEvent.click(providerToggle());fireEvent.click(screen.getByRole('button', { name: 'Save provider' }));+ // #4703 — the patch carries `mediaProvider` alone; `strictPullAuthorization`+ // and the unknown `somethingElse` are the server merge's job to carry.await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({federation: {- strictPullAuthorization: false,- somethingElse: 'keep-me',mediaProvider: {enabled: true,maxQueuedJobs: 2,@@ -131,13 +131,13 @@ describe('SharingTab — federation pull authorization (#3659)', () => {await waitFor(() => expect(strictToggle().checked).toBe(true));});- it('carries the rest of the federation slice forward on save (shallow top-level merge)', async () => {+ it('patches the toggle alone and leaves sibling sub-keys to the server merge', async () => {getSettings.mockResolvedValue({ federation: { strictPullAuthorization: false, somethingElse: 'keep-me' } });render(<SharingTab />);await waitFor(() => expect(strictToggle()).toBeInTheDocument());fireEvent.click(strictToggle());await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({- federation: { strictPullAuthorization: true, somethingElse: 'keep-me' },+ federation: { strictPullAuthorization: true },}));await waitFor(() => expect(strictToggle().checked).toBe(true));});@@ -211,11 +211,11 @@ describe('SharingTab — visual provider models', () => {});});-// /api/settings replaces the whole `federation` slice, and the Instances page-// owns mediaRouting — a tab left open across a routing change must not write-// back the slice as it looked before.-describe('SharingTab — writes against the freshest federation slice', () => {- it('preserves a route added elsewhere after this tab loaded', async () => {+// #4703 — the Instances page owns `federation.mediaRouting`. This tab must not+// name that sub-key at all: a patch that carried it would replace the routing+// map with whatever this tab happened to read, however stale.+describe('SharingTab — patches only the federation sub-keys it owns', () => {+ it('never names mediaRouting in a provider save', async () => {getMediaShareCandidates.mockResolvedValue({ image: [], video: [] });getAuthStatus.mockResolvedValue({ enabled: true });// Start enabled, then turn sharing OFF — disabling needs no model selection,@@ -247,11 +247,9 @@ describe('SharingTab — writes against the freshest federation slice', () => {fireEvent.click(toggle);fireEvent.click(screen.getByRole('button', { name: 'Save provider' }));- // Writing the mount-time snapshot would have dropped mediaRouting entirely,- // silently sending every unattended render back to local.- await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({- federation: expect.objectContaining({ mediaRouting: { image: route } }),- }, { silent: true }));+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ const [patch] = updateSettings.mock.calls.at(-1);+ expect(Object.keys(patch.federation)).toEqual(['mediaProvider']);});});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 3ea6e904c3..6f521db0db 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -98,6 +98,27 @@ const preserveExternallyOwnedKeys = (next, current) => {return next;};+// `federation` is the one top-level slice with more than one owning surface:+// Settings → Sharing writes `mediaProvider` and `strictPullAuthorization`, while+// Instances → Unattended render routing writes `mediaRouting`. The generic+// top-level shallow merge replaces the slice wholesale, so whichever PUT lands+// second silently reverts the other surface's freshly saved sub-key (#4703).+// Merging per sub-key here removes that class instead of narrowing it — and+// because `updateSettingsWith` runs inside the settings write queue, `current`+// is always the freshest persisted snapshot, not the one the client read.+//+// A SHALLOW per-sub-key merge is deliberately enough: every sub-key today has+// exactly one owning surface, so an incoming sub-key is a complete value for it.+// "Absent vs present-but-empty" falls straight out of the spread — an omitted+// sub-key keeps the stored value, while one sent as `{}` or `null` applies the+// clear the user actually asked for. A FUTURE sub-key written by two surfaces+// would need its own deeper merge added here.+const mergeFederationSlice = (next, current) => {+ if (!isPlainObject(next.federation) || !isPlainObject(current?.federation)) return next;+ next.federation = { ...current.federation, ...next.federation };+ return next;+};+// Single sanitizer every settings response (GET load + PUT save) runs through,// so a leak can't reappear on one path after being closed on the other: strip// the top-level `secrets` hierarchy, redact external tokens (#1821), then@@ -310,11 +331,15 @@ router.put('/', asyncHandler(async (req, res) => {// would replace the whole map, silently dropping any family the incoming// patch didn't mention.const { secrets: _ignoredSecrets, catalogUserTypes: _ignoredTypes, subscriptionCosts: subscriptionCostsPatch, ...settingsPatch } = req.body || {};- // updateSettingsWith (not updateSettings) so we can re-inject persisted- // write-only tokens the incoming patch omits, against the freshest snapshot- // inside the write queue (see preserveExternallyOwnedKeys).+ // updateSettingsWith (not updateSettings) so the multi-owner `federation`+ // slice merges per sub-key and persisted write-only tokens the incoming patch+ // omits get re-injected — both against the freshest snapshot inside the write+ // queue (see mergeFederationSlice / preserveExternallyOwnedKeys).let merged = await updateSettingsWith((current) =>- preserveExternallyOwnedKeys({ ...current, ...settingsPatch }, current));+ preserveExternallyOwnedKeys(+ mergeFederationSlice({ ...current, ...settingsPatch }, current),+ current,+ ));if (subscriptionCostsPatch !== undefined) {const costs = await saveSubscriptionCosts(subscriptionCostsPatch);merged = { ...merged, subscriptionCosts: costs };diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex f528bb61a5..2c09c8ffda 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -11,8 +11,9 @@ vi.mock('../services/settings.js', () => ({store = { ...store, ...patch };return { ...store };}),- // The PUT handler uses updateSettingsWith so it can re-inject persisted- // sub-keys this route does not own but the patch omits (see+ // The PUT handler uses updateSettingsWith so it can merge the multi-owner+ // federation slice per sub-key and re-inject persisted sub-keys this route+ // does not own but the patch omits (see mergeFederationSlice /// preserveExternallyOwnedKeys).updateSettingsWith: vi.fn(async (mutate) => {store = await mutate({ ...store });@@ -136,6 +137,56 @@ describe('Settings routes — agent context and federated media provider slices'expect(res.body.federation.futureFederationField).toBe('preserve');});+ // #4703 — Sharing owns federation.mediaProvider + strictPullAuthorization,+ // Instances owns federation.mediaRouting. Each now patches ONLY the sub-keys+ // it owns; the server carries the rest of the slice forward. Two saves issued+ // from the same stale page load must therefore both survive.+ it('merges federation sub-keys so two writes from the same stale page load both survive', async () => {+ const app = buildApp();+ store = { federation: { strictPullAuthorization: false } };+ const route = { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' };++ const sharing = await request(app)+ .put('/api/settings')+ .send({ federation: { strictPullAuthorization: true } });+ expect(sharing.status).toBe(200);++ // Instances never saw the toggle above — it patches its own sub-key only.+ const routing = await request(app)+ .put('/api/settings')+ .send({ federation: { mediaRouting: { image: route } } });+ expect(routing.status).toBe(200);+ expect(routing.body.federation).toEqual({+ strictPullAuthorization: true,+ mediaRouting: { image: route },+ });+ });++ it('preserves unknown federation sub-keys a patch omits (mixed-version client)', async () => {+ store = { federation: { futureFederationField: 'preserve', strictPullAuthorization: true } };+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaProvider: { enabled: true } } });+ expect(res.status).toBe(200);+ expect(res.body.federation).toEqual({+ futureFederationField: 'preserve',+ strictPullAuthorization: true,+ mediaProvider: { enabled: true },+ });+ });++ it('applies an intentional federation sub-key clear rather than restoring the stored value', async () => {+ store = { federation: {+ mediaRouting: { image: { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' } },+ strictPullAuthorization: true,+ } };+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaRouting: {} } });+ expect(res.status).toBe(200);+ expect(res.body.federation).toEqual({ mediaRouting: {}, strictPullAuthorization: true });+ });+it('rejects invalid limits and duplicate engine/model pairs', async () => {const invalidLimit = await request(buildApp()).put('/api/settings')