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([issue-1072]): address review iter 2 (lock-release + refetch herd)
Adam Eivy0cca560ae3c9
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex c17f44296b..0424345b60 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -997,11 +997,13 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {} else if (payload.phase === 'complete') {setSyncing(false);// Pull the freshest cursors/seqs so the card settles to the new- // directional summary without waiting for the next 60s probe. Refresh- // even on a zero-applied complete: a convergence/no-op sync still- // advances `lastSyncAt` and snapshot checksums, so the badge would- // otherwise read stale until the next manual probe.- onRefresh();+ // directional summary. Only when records actually moved — otherwise the+ // 60s background `syncAllPeers` cycle would fire a full page refetch per+ // peer on every idle tick (a refetch herd). The manual "Sync now" path+ // (`handleSync`) does its own authoritative refetch on the awaited POST,+ // so a no-op manual sync still settles; this branch covers the+ // records-moved case for both manual and background syncs.+ if (payload.totalApplied > 0) onRefresh();}// `applied` events are informational (and drive the server-side log) —// the global `syncing` flag already animates every badge, so the client@@ -1090,16 +1092,14 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {setSyncing(true);const result = await syncPeer(peer.id, { silent: true }).catch(() => null);// The POST awaits the full sync server-side, so its resolution IS the- // authoritative completion for a manual sync — clear here rather than- // relying solely on the fire-and-forget `complete` socket event, which a- // transient socket disconnect could drop and leave the card stuck spinning.+ // authoritative completion for a manual sync — clear the spinner here+ // rather than relying solely on the fire-and-forget `complete` socket+ // event, which a transient socket disconnect could drop and leave the card+ // stuck. The refetch itself is owned by the `complete` handler (gated on+ // records-moved); a no-op manual sync changes nothing worth refetching.setSyncing(false);if (!result) {toast.error(`Couldn't sync with ${peer.name} — is it online?`);- } else {- // Settle to the new directional summary (the socket `complete` also- // refreshes when records moved; this covers the no-op/socket-miss case).- onRefresh();}};diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex f37b178857..a2bd796ad5 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -587,27 +587,6 @@ export async function syncWithPeer(peer) {if (syncingPeers.has(peerId)) return { brain: { totalApplied: 0 }, memory: { totalApplied: 0 } };syncingPeers.add(peerId);- // Our own instanceId — sent as `forPeer` so the SOURCE peer can scope each- // snapshot it serves us (excludes records it already pushes to us- // per-record). Resolved once per sync, best-effort; null/UNKNOWN → no- // scoping (full snapshots, legacy behavior).- const ourInstanceId = await getInstanceId().catch(() => null);- const scopedInstanceId = isNonEmptyStr(ourInstanceId) && ourInstanceId !== UNKNOWN_INSTANCE_ID- ? ourInstanceId- : null;-- const categories = getEffectiveCategories(peer);- const enabledNames = Object.entries(categories).filter(([, on]) => on).map(([k]) => k);- console.log(`🔄 Sync starting with ${peer.name || peerId}: categories=${enabledNames.join(',') || 'none'}`);- emitSyncProgress({ phase: 'start', peerId });-- // Read cursor snapshot outside lock so network I/O doesn't block other peers- // Also detect and reset stale cursors (e.g. peer DB was rebuilt)- const cursor = await readCursors((cursors) => {- const raw = { ...(cursors[peerId] || {}) };- return detectCursorReset(raw, peer);- });-// Emit an `applied` progress event for a category when it actually moved// records — keeps the per-category emits DRY across the delta + snapshot legs.const reportApplied = (category, applied) => {@@ -618,7 +597,33 @@ export async function syncWithPeer(peer) {// a card whose sync threw mid-flight instead of leaving it spinning forever.let completed = false;+ // Everything after acquiring the lock runs inside the try so the `finally`+ // ALWAYS releases `syncingPeers` and emits a terminal `complete` — even if+ // `getInstanceId`/`readCursors` throws before the sync body. Otherwise a+ // throw here would both leak the per-peer lock (permanent until restart) and+ // strand the card spinning with no `complete`.try {+ // Our own instanceId — sent as `forPeer` so the SOURCE peer can scope each+ // snapshot it serves us (excludes records it already pushes to us+ // per-record). Resolved once per sync, best-effort; null/UNKNOWN → no+ // scoping (full snapshots, legacy behavior).+ const ourInstanceId = await getInstanceId().catch(() => null);+ const scopedInstanceId = isNonEmptyStr(ourInstanceId) && ourInstanceId !== UNKNOWN_INSTANCE_ID+ ? ourInstanceId+ : null;++ const categories = getEffectiveCategories(peer);+ const enabledNames = Object.entries(categories).filter(([, on]) => on).map(([k]) => k);+ console.log(`🔄 Sync starting with ${peer.name || peerId}: categories=${enabledNames.join(',') || 'none'}`);+ emitSyncProgress({ phase: 'start', peerId });++ // Read cursor snapshot outside lock so network I/O doesn't block other peers+ // Also detect and reset stale cursors (e.g. peer DB was rebuilt)+ const cursor = await readCursors((cursors) => {+ const raw = { ...(cursors[peerId] || {}) };+ return detectCursorReset(raw, peer);+ });+// --- Brain sync (delta-based) ---let brainResult = { brainSeq: cursor.brainSeq ?? 0, totalApplied: 0 };if (categories.brain) {diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 4333d58294..94aefdfefb 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -621,6 +621,28 @@ describe('syncOrchestrator', () => {expect(complete.totalApplied).toBeGreaterThanOrEqual(1);});+ it('releases the per-peer lock and still emits complete when the cursor read throws', async () => {+ // readCursors → loadCursors → readJSONFile. A throw here (corrupt cursor+ // file, disk error) happens AFTER the lock is acquired and the `start`+ // emit fires — the finally must release the lock and emit a terminal+ // `complete`, or the peer is wedged "syncing" until restart.+ readJSONFile.mockRejectedValueOnce(new Error('cursor file corrupt'));+ await expect(syncWithPeer({ ...mockPeer, syncCategories: { brain: true } })).rejects.toThrow('cursor file corrupt');++ const progress = instanceEvents.emit.mock.calls+ .filter(([event]) => event === 'sync:progress')+ .map(([, payload]) => payload);+ expect(progress).toContainEqual({ phase: 'start', peerId: 'peer-inst-1' });+ expect(progress).toContainEqual({ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0 });++ // Lock released: a subsequent sync is NOT short-circuited by syncingPeers.+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) });+ instanceEvents.emit.mockClear();+ await syncWithPeer({ ...mockPeer, syncCategories: { brain: true } });+ const reran = instanceEvents.emit.mock.calls.some(([event, p]) => event === 'sync:progress' && p.phase === 'start');+ expect(reran).toBe(true);+ });+it('emits exactly one complete (totalApplied 0) for a no-op sync — card never sticks on "syncing"', async () => {// A category enabled but no changes available: lifecycle still settles.mockFetch.mockResolvedValue({ ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) });