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
feat(federation): bidirectional sync from a single toggle (auto-reciprocate)
Adam Eivye63346f67ce4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fbc8cd1b3e..062d53b812 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@## Changed+- **[issue-1070] Federation sync is now bidirectional from one switch** — turning on a sync category for a peer (Brain, Goals, Universe, etc.) now automatically asks that peer to sync the same category back, so you no longer have to set the toggle on both machines by hand. Since you typically own every federated machine, enabling once establishes two-way sync. The Sync Categories panel explains this inline, and a new **Make mutual** button pushes the current set to a peer that was offline during an earlier change (or was configured one-directionally before this existed). Peers on older versions that don't understand the request simply stay one-directional until you toggle again — nothing breaks.- **Songs: built-in alert stacks cleanly on mobile** — the "Built-in default" banner on the song page now stacks its label, description, and Refresh action vertically on narrow screens instead of cramming them onto one row, with full-width touch targets for the refresh/confirm buttons.- **[issue-1027] Songs: vocal takes remember their pitch analysis** — a recorded take now saves its tuner trace and color-match score so your accuracy isn't recomputed every time you reopen the song.- **[issue-1060] Cleaner test runs** — browser-dependent tests now run only under their own test environment, so the server test run no longer reports spurious failures from double-running them.diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 55df1c4187..d35818697d 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -14,7 +14,7 @@ import Pill from '../components/ui/Pill';import socket from '../services/socket';import {getInstances, updateSelfInstance, addPeer, updatePeer,- removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert,+ removePeer, connectPeer, reciprocatePeer, probePeer, getTailnetInfo, provisionTailnetCert,getNetworkExposure,listPeerSubscriptions,} from '../services/api';@@ -531,6 +531,17 @@ function SyncCategoriesPanel({ peer, onRefresh }) {onRefresh();};+ // Explicitly push our current category map to the peer so it enables the same+ // toward us. Toggling already auto-reciprocates; this is the catch-up button+ // for peers configured one-directionally before auto-reciprocate existed, or+ // when the peer was offline during an earlier toggle.+ const makeMutual = async () => {+ const result = await reciprocatePeer(peer.id, { silent: true }).catch(() => null);+ if (result?.ok) toast.success(`Asked ${peer.name} to sync the same categories back`);+ else toast.error(`Couldn't reach ${peer.name} to make sync mutual — try again when it's online`);+ onRefresh();+ };+return (<div className="mt-2 pt-2 border-t border-port-border/50"><button@@ -549,7 +560,21 @@ function SyncCategoriesPanel({ peer, onRefresh }) {{expanded && (<div className="mt-2 space-y-1">- <div className="flex justify-end gap-2 mb-1.5">+ <p className="text-[10px] text-gray-600 mb-1.5 leading-snug">+ Enabling a category syncs it both ways — we ask {peer.name || 'the peer'} to+ sync the same back automatically.+ </p>+ <div className="flex items-center justify-end gap-2 mb-1.5">+ {peer.instanceId && enabledCount > 0 && (+ <button+ onClick={makeMutual}+ className="flex items-center gap-1 mr-auto text-[10px] text-gray-500 hover:text-port-accent transition-colors"+ title="Push the current categories to this peer so it syncs them back (use if it was offline during a change)"+ >+ <ArrowLeftRight size={10} />+ Make mutual+ </button>+ )}<buttononClick={() => toggleAll(true)}className="text-[10px] text-port-accent hover:text-port-accent/80 transition-colors"diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 3147dc8c0b..3870c95834 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -173,6 +173,7 @@ export const addPeer = (data) => request('/instances/peers', { method: 'POST', bexport const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'DELETE' });export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });+export const reciprocatePeer = (id, options) => request(`/instances/peers/${id}/reciprocate`, { method: 'POST', ...options });export const probePeer = (id) => request(`/instances/peers/${id}/probe`, { method: 'POST' });export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);export const getTailnetInfo = () => request('/instances/tailnet-suffix');diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 108e016b87..c08bd71bba 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -95,6 +95,16 @@ const querySchema = z.object({path: z.string().startsWith('/api/', 'Path must start with /api/')});+// Reciprocal sync request from a peer: it enabled `syncCategories` toward us+// and asks us to mirror them so the sync is bidirectional. instanceId is the+// announcing peer's identity (matched against our peer record).+const reciprocalSyncSchema = z.object({+ instanceId: z.string().guid(),+ // `.unwrap()` strips the `.optional()` from the shared schema — the category+ // map is required on this endpoint (an empty/absent map has nothing to mirror).+ syncCategories: syncCategoriesSchema.unwrap()+});+// GET /api/instances — list self + all peersrouter.get('/', asyncHandler(async (req, res) => {const [self, peers, syncStatus] = await Promise.all([@@ -239,6 +249,29 @@ router.post('/peers/:id/connect', asyncHandler(async (req, res) => {res.json(instances.sanitizePeerForClient(result));}));+// POST /api/instances/peers/sync-categories — reciprocal-sync callback from a+// peer. The peer enabled some categories toward us and is asking us to mirror+// them so the sync is bidirectional. No :id — the peer is identified by the+// instanceId in the body (we may not know its local-peer-id mapping).+router.post('/peers/sync-categories', asyncHandler(async (req, res) => {+ const data = reciprocalSyncSchema.parse(req.body);+ const { changed, peer } = await instances.applyReciprocalSync(data.instanceId, data.syncCategories);+ // 200 even when the peer is unknown to us / nothing changed — this is a+ // best-effort convergence signal, not a command that must succeed.+ res.json({ applied: changed, peer: peer ? instances.sanitizePeerForClient(peer) : null });+}));++// POST /api/instances/peers/:id/reciprocate — explicit "make all enabled+// categories mutual" for an existing (likely one-directional) peer. Pushes our+// current category map to the peer so it enables the same toward us.+router.post('/peers/:id/reciprocate', asyncHandler(async (req, res) => {+ const peers = await instances.getPeers();+ const peer = peers.find(p => p.id === req.params.id);+ if (!peer) throw new ServerError('Peer not found', { status: 404 });+ const result = await instances.requestReciprocalSync(peer, peer.syncCategories || {});+ res.json(result);+}));+// POST /api/instances/peers/:id/probe — force immediate proberouter.post('/peers/:id/probe', asyncHandler(async (req, res) => {const peers = await instances.getPeers();diff --git a/server/services/instances.js b/server/services/instances.jsindex 1b77eb790f..1580560650 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -295,6 +295,11 @@ export async function updatePeer(id, updates) {// peer object) and consumed after the lock releases.const turnedOnKinds = [];let backfillPeerInstanceId = null;+ // When the user changes which categories sync toward this peer, mirror the+ // change back so the sync is bidirectional (the user owns all machines). We+ // reciprocate the FULL resulting category map, not just the delta, so the+ // peer converges even if an earlier reciprocate was missed (peer offline).+ let reciprocateCategories = null;const result = await withData(async (data) => {const peer = data.peers.find(p => p.id === id);if (!peer) return null;@@ -313,6 +318,9 @@ export async function updatePeer(id, updates) {}peer.syncCategories = { ...prev, ...incoming };if (turnedOnKinds.length > 0) backfillPeerInstanceId = peer.instanceId || null;+ // Reciprocate the resulting map so the peer enables the same categories+ // toward us. Only when we know the peer's identity (post-handshake).+ if (peer.instanceId) reciprocateCategories = { ...peer.syncCategories };}// Optional proxy credential. `null` (or both fields blank) clears it; a// valid object replaces it; malformed input (sanitizePeerAuth → undefined)@@ -399,6 +407,14 @@ export async function updatePeer(id, updates) {console.log(`⚠️ peer: backfill-subscribe after category toggle failed: ${err.message}`);});}+ // Mirror the category change back to the peer so sync is bidirectional.+ // Fire-and-forget — a peer that's offline / on an older version just stays+ // one-directional until the next toggle (or the "make mutual" backfill).+ if (reciprocateCategories && result) {+ requestReciprocalSync(result, reciprocateCategories).catch((err) => {+ console.log(`⚠️ peer: reciprocal sync request failed: ${err.message}`);+ });+ }return result;}@@ -675,6 +691,107 @@ export async function connectPeer(id) {return probed;}+// --- Bidirectional sync reciprocation ---+//+// A single user commonly owns every federated machine and expects enabling a+// sync category toward a peer to make it two-way without also toggling it on+// the peer by hand. Sync is pull-based per direction, so enabling category C+// toward peer B only makes US pull B's C. For B to pull OUR C, B must enable C+// toward US. `requestReciprocalSync` asks B to do exactly that; the peer side+// is `applyReciprocalSync`, invoked by the POST /sync-categories route.++// Keep only the keys DEFAULT_SYNC_CATEGORIES defines, coerced to booleans, so a+// peer can never inject unknown/garbage category flags onto our peer record.+function sanitizeSyncCategories(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const out = {};+ for (const key of Object.keys(DEFAULT_SYNC_CATEGORIES)) {+ if (typeof input[key] === 'boolean') out[key] = input[key];+ }+ return Object.keys(out).length > 0 ? out : null;+}++/**+ * Receiver side of reciprocation: a peer is telling us it enabled `categories`+ * toward us and is asking us to mirror them so the sync is bidirectional.+ * Find the local peer record for the announcing instance and apply the same+ * category flags. Returns `{ changed, peer }`; `changed` is false when our+ * record already matched (the echo guard — the caller never re-reciprocates,+ * but this keeps a misbehaving peer from churning our state).+ */+export async function applyReciprocalSync(instanceId, categories) {+ const sanitized = sanitizeSyncCategories(categories);+ if (!sanitized) return { changed: false, peer: null };+ const turnedOnKinds = [];+ let backfillInstanceId = null;+ let changed = false;+ const peer = await withData(async (data) => {+ const entry = data.peers.find(p => p.instanceId === instanceId);+ if (!entry) return null;+ const prev = entry.syncCategories || { ...DEFAULT_SYNC_CATEGORIES };+ const next = { ...prev, ...sanitized };+ // No-op when nothing actually flips — the echo guard.+ if (Object.keys(next).every(k => next[k] === prev[k])) return entry;+ for (const [cat, kind] of [['universe', 'universe'], ['pipeline', 'series']]) {+ if (prev[cat] !== true && next[cat] === true) turnedOnKinds.push(kind);+ }+ entry.syncCategories = next;+ entry.syncEnabled = Object.values(next).some(Boolean);+ if (turnedOnKinds.length > 0) backfillInstanceId = entry.instanceId || null;+ changed = true;+ instanceEvents.emit('peers:updated', data.peers);+ return entry;+ });+ if (!peer) return { changed: false, peer: null };+ // Mirror updatePeer's backfill-subscribe so a reciprocally-enabled+ // per-record category (universe/pipeline) pushes our existing records too.+ if (changed && turnedOnKinds.length > 0 && backfillInstanceId) {+ import('./sharing/peerSync.js').then(async ({ autoSubscribePeerToAllRecords }) => {+ for (const kind of turnedOnKinds) {+ await autoSubscribePeerToAllRecords(backfillInstanceId, kind).catch((err) => {+ console.log(`⚠️ peer: reciprocal backfill-subscribe ${kind} failed: ${err.message}`);+ });+ }+ }).catch((err) => console.log(`⚠️ peer: reciprocal backfill-subscribe failed: ${err.message}`));+ }+ if (changed) console.log(`🔁 Reciprocal sync applied for peer ${peer.name}: ${Object.keys(sanitized).filter(k => sanitized[k]).join(',') || 'none'}`);+ return { changed, peer };+}++/**+ * Sender side: ask `peer` to enable `categories` toward us (mirror what we just+ * enabled toward them). Best-effort and fire-and-forget at the call site — a+ * peer that's offline or on an older version (404s the endpoint) just stays+ * one-directional until the next toggle. Returns `{ ok, reason }`.+ */+export async function requestReciprocalSync(peer, categories) {+ const self = await getSelf();+ if (!self?.instanceId) return { ok: false, reason: 'no-self-identity' };+ const sanitized = sanitizeSyncCategories(categories);+ if (!sanitized) return { ok: false, reason: 'no-categories' };+ const url = `${peerBaseUrl(peer)}/api/instances/peers/sync-categories`;+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);+ try {+ const res = await peerFetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized }),+ signal: controller.signal+ }, peer);+ if (res.ok) {+ console.log(`🔁 Requested reciprocal sync from ${peer.name}: ${Object.keys(sanitized).filter(k => sanitized[k]).join(',') || 'none'}`);+ return { ok: true };+ }+ // 404 = peer predates this endpoint; not an error worth surfacing loudly.+ return { ok: false, reason: `http-${res.status}` };+ } catch (err) {+ return { ok: false, reason: err.message };+ } finally {+ clearTimeout(timeout);+ }+}+async function markDirection(peerId, direction) {await withData(async (data) => {const peer = data.peers.find(p => p.id === peerId);diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 4425534161..e1592af54f 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -43,7 +43,7 @@ vi.mock('../lib/ports.js', () => ({// fetch is stubbed per-test in beforeEach and restored in afterEach-import { readJSONFile } from '../lib/fileUtils.js';+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import {@@ -61,6 +61,8 @@ import {handleAnnounce,redactPeerForWire,sanitizePeerForClient,+ applyReciprocalSync,+ requestReciprocalSync,startPolling,stopPolling} from './instances.js';@@ -536,6 +538,98 @@ describe('instances.js', () => {});});+ // --- Bidirectional sync reciprocation ---++ describe('applyReciprocalSync', () => {+ it('mirrors a peer\'s enabled categories onto our local record for that peer', async () => {+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: false, goals: false } }];+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });++ const { changed, peer } = await applyReciprocalSync('inst-A', { brain: true });++ expect(changed).toBe(true);+ expect(peer.syncCategories.brain).toBe(true);+ expect(peer.syncEnabled).toBe(true); // recomputed from the resulting map+ expect(peer._reciprocalChanged).toBeUndefined(); // no transient marker leaks onto the record+ // And the persisted payload must not carry any transient marker either.+ const written = atomicWrite.mock.calls.at(-1)?.[1];+ expect(written.peers[0]._reciprocalChanged).toBeUndefined();+ });++ it('is a no-op (changed:false) when our record already matches — the echo guard', async () => {+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });++ const { changed } = await applyReciprocalSync('inst-A', { brain: true });++ expect(changed).toBe(false);+ });++ it('returns changed:false for an unknown peer instanceId', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });+ const { changed, peer } = await applyReciprocalSync('nope', { brain: true });+ expect(changed).toBe(false);+ expect(peer).toBeNull();+ });++ it('drops unknown/garbage category keys (only DEFAULT_SYNC_CATEGORIES keys applied)', async () => {+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: false } }];+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });++ const { peer } = await applyReciprocalSync('inst-A', { brain: true, __proto__: true, bogus: true });++ expect(peer.syncCategories.brain).toBe(true);+ expect(peer.syncCategories.bogus).toBeUndefined();+ });++ it('ignores a non-object categories payload', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });+ const { changed } = await applyReciprocalSync('inst-A', 'not-an-object');+ expect(changed).toBe(false);+ });+ });++ describe('requestReciprocalSync', () => {+ it('POSTs our self instanceId + sanitized categories to the peer', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me-id', name: 'me' }, peers: [] });+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });+ vi.stubGlobal('fetch', fetchMock);++ const result = await requestReciprocalSync(+ { id: 'p1', address: '10.0.0.2', port: 5555, name: 'B' },+ { brain: true, bogus: true }+ );++ expect(result.ok).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, opts] = fetchMock.mock.calls[0];+ expect(url).toContain('/api/instances/peers/sync-categories');+ const body = JSON.parse(opts.body);+ expect(body.instanceId).toBe('me-id');+ expect(body.syncCategories).toEqual({ brain: true }); // bogus dropped+ });++ it('returns ok:false (not throw) when the peer 404s the endpoint (older version)', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me-id' }, peers: [] });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }));++ const result = await requestReciprocalSync(+ { id: 'p1', address: '10.0.0.2', port: 5555, name: 'B' },+ { brain: true }+ );++ expect(result.ok).toBe(false);+ expect(result.reason).toBe('http-404');+ });++ it('returns ok:false when we have no self identity', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ const result = await requestReciprocalSync({ id: 'p1', address: '10.0.0.2', port: 5555 }, { brain: true });+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('no-self-identity');+ });+ });+// --- Probing ---describe('probePeer', () => {