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
address review (codex): serialize reciprocal-sync sends per peer
Adam Eivyd32125cd4ddd
diff --git a/server/routes/instances.js b/server/routes/instances.jsindex b190ea54f2..d9c3ed67cb 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -274,8 +274,11 @@ 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);+ // Go through the per-peer serialized queue (same path as the auto-reciprocate+ // on toggle) so a manual "Make mutual" can't race an in-flight toggle send and+ // land a stale map. The queue re-reads the freshest persisted categories.+ const result = await instances.enqueueReciprocalSync(peer.id);+ res.json(result ?? { ok: false, reason: 'no-result' });}));// POST /api/instances/peers/:id/probe — force immediate probediff --git a/server/services/instances.js b/server/services/instances.jsindex 92ae5f059c..268b359cd1 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -295,11 +295,10 @@ 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;+ // Set when a syncCategories change should be mirrored back to the peer so the+ // sync is bidirectional (the user owns all machines). The actual send reads+ // the freshest persisted map at send time via the serialized queue below.+ let reciprocate = false;const result = await withData(async (data) => {const peer = data.peers.find(p => p.id === id);if (!peer) return null;@@ -318,9 +317,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 };+ // Reciprocate so the peer enables the same categories toward us. Only when+ // we know the peer's identity (post-handshake).+ if (peer.instanceId) reciprocate = true;}// Optional proxy credential. `null` (or both fields blank) clears it; a// valid object replaces it; malformed input (sanitizePeerAuth → undefined)@@ -408,16 +407,47 @@ export async function updatePeer(id, updates) {});}// 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}`);- });+ // Fire-and-forget, but SERIALIZED per peer (see enqueueReciprocalSync): two+ // rapid toggles must not race — an earlier send arriving after a later one+ // would push a stale full map and undo the newer change on the peer.+ if (reciprocate && result?.instanceId) {+ enqueueReciprocalSync(result.id);}return result;}+// Per-peer tail that serializes reciprocal-sync sends. Two rapid category+// toggles for the same peer each want to push the full resulting map; if their+// fire-and-forget requests raced, the earlier (staler) map could land last on+// the peer and undo the newer change. Chaining per peer.id guarantees in-order+// delivery, and each send re-reads the FRESHEST persisted category map (not a+// value captured at enqueue time) so the final send always carries final state.+const reciprocalSyncTails = new Map();++export function enqueueReciprocalSync(peerId) {+ const prev = reciprocalSyncTails.get(peerId) || Promise.resolve();+ const next = prev+ .catch(() => {}) // a failed prior send must not break the chain+ .then(async () => {+ // Re-read the peer fresh at send time — the last enqueued send wins with+ // the latest persisted syncCategories, regardless of enqueue order.+ const data = await loadData();+ const peer = data.peers.find(p => p.id === peerId);+ if (!peer?.instanceId) return { ok: false, reason: 'no-peer-identity' };+ return requestReciprocalSync(peer, peer.syncCategories || {}).catch((err) => {+ console.log(`⚠️ peer: reciprocal sync request failed: ${err.message}`);+ return { ok: false, reason: err.message };+ });+ });+ reciprocalSyncTails.set(peerId, next);+ // Evict the tail once it settles and nothing newer has been chained, so the+ // map doesn't grow unbounded across many peers/toggles.+ next.finally(() => {+ if (reciprocalSyncTails.get(peerId) === next) reciprocalSyncTails.delete(peerId);+ });+ return next;+}+// --- Probing ---export async function probePeer(peer) {diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 7fabc4bf0d..92a5b3d73f 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -63,6 +63,7 @@ import {sanitizePeerForClient,applyReciprocalSync,requestReciprocalSync,+ enqueueReciprocalSync,startPolling,stopPolling} from './instances.js';@@ -653,6 +654,65 @@ describe('instances.js', () => {});});+ describe('enqueueReciprocalSync', () => {+ it('reads the FRESHEST persisted categories at send time (last enqueue wins, not enqueue-time snapshot)', async () => {+ // readJSONFile is re-read on each send; point it at the latest map so the+ // serialized send carries final state regardless of when it was enqueued.+ readJSONFile.mockResolvedValue({+ self: { instanceId: 'me-id' },+ peers: [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true, goals: true } }]+ });+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });+ vi.stubGlobal('fetch', fetchMock);++ await enqueueReciprocalSync('p1');++ const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);+ expect(body.syncCategories).toEqual({ brain: true, goals: true });+ });++ it('serializes per peer so sends leave in enqueue order (no stale-map race)', async () => {+ // Unique peer id so the module-level per-peer tail can't chain onto another+ // test's queue. The second send resolves immediately; the first blocks on+ // resolveFirst. If sends raced, order would be ['second', 'first']; ordered+ // serialization yields ['first', 'second'].+ readJSONFile.mockResolvedValue({+ self: { instanceId: 'me-id' },+ peers: [{ id: 'p-serial', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true } }]+ });+ const order = [];+ let resolveFirst;+ const fetchMock = vi.fn()+ .mockImplementationOnce(() => new Promise(r => { resolveFirst = () => { order.push('first'); r({ ok: true, status: 200 }); }; }))+ .mockImplementationOnce(async () => { order.push('second'); return { ok: true, status: 200 }; });+ vi.stubGlobal('fetch', fetchMock);++ const p1 = enqueueReciprocalSync('p-serial');+ const p2 = enqueueReciprocalSync('p-serial');+ // The second send resolves immediately; the first blocks until we release+ // it. If the two ran concurrently (unserialized), 'second' would land+ // first. Flush microtasks until the first send reaches its (blocked)+ // fetch, then release it — the recorded order proves serialization.+ // (beforeEach installs fake timers, so we flush the microtask queue+ // directly rather than waiting on a real-time setTimeout.)+ for (let i = 0; i < 20 && !resolveFirst; i++) await Promise.resolve();+ resolveFirst();+ await Promise.all([p1, p2]);+ expect(order).toEqual(['first', 'second']);+ });++ it('no-ops cleanly for a peer that lost its instanceId', async () => {+ readJSONFile.mockResolvedValue({+ self: { instanceId: 'me-id' },+ peers: [{ id: 'p-noinst', name: 'A', syncCategories: { brain: true } }] // no instanceId+ });+ vi.stubGlobal('fetch', vi.fn());+ const result = await enqueueReciprocalSync('p-noinst');+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('no-peer-identity');+ });+ });+// --- Probing ---describe('probePeer', () => {