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([issue-1072]): directional sync counts + realtime sync progress on federation cards
Adam Eivy971d3edb73a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 714131f5af..eed00a5167 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,7 @@- **[issue-1050] More reliable database exports** — manual database exports now pick a PostgreSQL dump tool that matches the database being exported, so an export no longer fails on machines with several Postgres versions installed.- **[issue-909] CyberCity theme colors** — internal refactor of how the 3D city picks up your theme accent, replacing a fragile shared-state mechanism with a cleaner one; no change to how the city looks.- **[issue-1064] Smoother CyberCity theme switching** — changing your theme now recolors the 3D city in place instead of rebuilding the whole scene, so the switch is seamless with no rebuild flash or blank frame.+- **[issue-1072] Federation cards show what's pending in each direction, live** — each peer's sync card now reads in plain language — "in sync", "3 to pull", "12 to push" — for every category, instead of the cryptic `0/54` sequence numbers (those move to a hover tooltip for debugging). For the first time the card shows both directions: how many of the peer's items you still need to pull *and* how many of your own items the peer hasn't pulled yet. A new **Sync now** button on the card kicks off an immediate sync with that peer, and the card animates live while a sync runs — each category flips to "syncing…" as work lands and settles to the new summary the moment it finishes, no manual refresh needed.## Fixeddiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9a78155b8a..46c98261ae 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -97,5 +97,6 @@ grep -i "what you want to do" client/src/lib/README.md| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. || `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |+| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. || `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 8217738a3d..92c75b84e0 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -64,6 +64,7 @@ export * from './singToScore.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';+export * from './syncCounts.js';export * from './universeBuilderExpand.js';export * from './wrSceneCursor.js';export * from './writingGuide.js';diff --git a/client/src/lib/syncCounts.js b/client/src/lib/syncCounts.jsnew file mode 100644index 0000000000..1703a7d8cc--- /dev/null+++ b/client/src/lib/syncCounts.js@@ -0,0 +1,66 @@+// Directional pending-sync counts for a delta-synced category (brain / memory).+//+// PortOS federation sync is PULL-based — each instance pulls changes from its+// peers — so "push pending" is really "items of ours the peer hasn't pulled yet."+// Two directions, both derived from monotonic change-log sequences:+//+// toPull = peerMax - ourCursor (their items we haven't pulled)+// toPush = ourLocalMax - peerCursorForUs (our items they haven't pulled)+//+// Sequences arrive as numbers (brain) or numeric strings (memory BIGSERIAL),+// so compare as BigInt to stay exact past Number.MAX_SAFE_INTEGER.+//+// Sentinel discipline (see CLAUDE.md): a MISSING input must NOT collapse to 0.+// - For pull, an absent `ourCursor` legitimately means "pulled nothing" → treat+// as 0 (the caller passes `ourCursor ?? 0`). An absent `peerMax` means the+// peer hasn't been probed yet → unknown (null).+// - For push, an absent `peerCursorForUs` means the peer is too old to report+// it (or hasn't probed us) → unknown (null), never a misleading 0.++function toBig(v) {+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) return BigInt(Math.trunc(v));+ if (typeof v === 'string' && /^\d+$/.test(v.trim())) return BigInt(v.trim());+ if (typeof v === 'bigint') return v >= 0n ? v : null;+ return null;+}++// Returns the positive difference `ahead - behind` as a Number, clamped at 0,+// or null when either side is absent/invalid (unknown). A peer that has pulled+// MORE than our reported max (clock skew, mid-sync probe) clamps to 0 rather+// than showing a confusing negative.+export function diffSeq(ahead, behind) {+ const a = toBig(ahead);+ const b = toBig(behind);+ if (a === null || b === null) return null;+ const d = a - b;+ return d > 0n ? Number(d) : 0;+}++// { toPull, toPush } — each a non-negative Number, or null when unknown.+export function directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs }) {+ return {+ // Absent cursor = we've pulled nothing yet, so default to 0 (not unknown).+ toPull: diffSeq(peerMax, ourCursor ?? 0),+ // Absent peer-cursor = peer didn't report it (old peer) → genuinely unknown.+ toPush: diffSeq(localMax, peerCursorForUs),+ };+}++// Plain-language one-liner for a directional pair. Used by the badge and easy+// to unit-test independently of React. `null` directions are omitted (unknown);+// when BOTH directions are known and zero, the category is "in sync".+export function describeDirectional({ toPull, toPush }) {+ const bothKnown = toPull !== null && toPush !== null;+ if (bothKnown && toPull === 0 && toPush === 0) {+ return { state: 'synced', text: 'in sync' };+ }+ const parts = [];+ if (toPull) parts.push(`${toPull} to pull`);+ if (toPush) parts.push(`${toPush} to push`);+ if (parts.length === 0) {+ // Either everything known is zero but a direction is unknown, or both+ // unknown. Fall back to a neutral pending label rather than lying "in sync".+ return { state: 'pending', text: bothKnown ? 'in sync' : 'checking…' };+ }+ return { state: 'behind', text: parts.join(' · ') };+}diff --git a/client/src/lib/syncCounts.test.js b/client/src/lib/syncCounts.test.jsnew file mode 100644index 0000000000..a692554bfd--- /dev/null+++ b/client/src/lib/syncCounts.test.js@@ -0,0 +1,96 @@+import { describe, it, expect } from 'vitest';+import { diffSeq, directionalCounts, describeDirectional } from './syncCounts.js';++describe('diffSeq', () => {+ it('subtracts numeric seqs', () => {+ expect(diffSeq(54, 10)).toBe(44);+ });++ it('subtracts numeric-string (BIGSERIAL) seqs', () => {+ expect(diffSeq('81', '5')).toBe(76);+ });++ it('clamps a negative difference to 0 (peer ahead of our reported max)', () => {+ expect(diffSeq(5, 10)).toBe(0);+ });++ it('returns 0 when equal', () => {+ expect(diffSeq(42, 42)).toBe(0);+ });++ it('stays exact past Number.MAX_SAFE_INTEGER', () => {+ const big = '9007199254740993'; // MAX_SAFE_INTEGER + 2+ const lo = '9007199254740990';+ expect(diffSeq(big, lo)).toBe(3);+ });++ it('returns null when either side is absent', () => {+ expect(diffSeq(undefined, 5)).toBeNull();+ expect(diffSeq(5, null)).toBeNull();+ expect(diffSeq(null, null)).toBeNull();+ });++ it('returns null for non-numeric strings rather than collapsing to 0', () => {+ expect(diffSeq('abc', 5)).toBeNull();+ expect(diffSeq(5, '')).toBeNull();+ });++ it('rejects negative numeric inputs as invalid', () => {+ expect(diffSeq(-1, 0)).toBeNull();+ });+});++describe('directionalCounts', () => {+ it('computes both directions from seqs', () => {+ expect(directionalCounts({ localMax: 100, peerMax: 54, ourCursor: 54, peerCursorForUs: 88 }))+ .toEqual({ toPull: 0, toPush: 12 });+ });++ it('treats an absent ourCursor as 0 pulled (pull defaults, not unknown)', () => {+ expect(directionalCounts({ localMax: 10, peerMax: 54, ourCursor: undefined, peerCursorForUs: 10 }))+ .toEqual({ toPull: 54, toPush: 0 });+ });++ it('treats an absent peerCursorForUs as unknown push (null, not 0)', () => {+ expect(directionalCounts({ localMax: 100, peerMax: 54, ourCursor: 54, peerCursorForUs: undefined }))+ .toEqual({ toPull: 0, toPush: null });+ });++ it('treats an absent peerMax as unknown pull (null)', () => {+ expect(directionalCounts({ localMax: 100, peerMax: undefined, ourCursor: 0, peerCursorForUs: 100 }))+ .toEqual({ toPull: null, toPush: 0 });+ });+});++describe('describeDirectional', () => {+ it('reports "in sync" when both directions are known-zero', () => {+ expect(describeDirectional({ toPull: 0, toPush: 0 })).toEqual({ state: 'synced', text: 'in sync' });+ });++ it('reports both pending directions in plain language', () => {+ expect(describeDirectional({ toPull: 3, toPush: 12 }))+ .toEqual({ state: 'behind', text: '3 to pull · 12 to push' });+ });++ it('reports a single direction when the other is zero', () => {+ expect(describeDirectional({ toPull: 0, toPush: 7 }))+ .toEqual({ state: 'behind', text: '7 to push' });+ expect(describeDirectional({ toPull: 5, toPush: 0 }))+ .toEqual({ state: 'behind', text: '5 to pull' });+ });++ it('does not claim "in sync" when push is unknown but pull is zero', () => {+ expect(describeDirectional({ toPull: 0, toPush: null }))+ .toEqual({ state: 'pending', text: 'checking…' });+ });++ it('reports the known direction even when the other is unknown', () => {+ expect(describeDirectional({ toPull: 9, toPush: null }))+ .toEqual({ state: 'behind', text: '9 to pull' });+ });++ it('shows "checking…" when both directions are unknown', () => {+ expect(describeDirectional({ toPull: null, toPush: null }))+ .toEqual({ state: 'pending', text: 'checking…' });+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 8414ee0004..a65f532afe 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, reciprocatePeer, probePeer, getTailnetInfo, provisionTailnetCert,+ removePeer, connectPeer, reciprocatePeer, probePeer, syncPeer, getTailnetInfo, provisionTailnetCert,getNetworkExposure,listPeerSubscriptions,} from '../services/api';@@ -23,6 +23,7 @@ import PeerAgentsSection from '../components/instances/PeerAgentsSection';import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';import { timeAgo } from '../utils/formatters';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';+import { directionalCounts, describeDirectional } from '../lib/syncCounts';const STATUS_COLORS = {online: 'text-port-success',@@ -447,40 +448,46 @@ function DirectionBadge({ directions = [] }) {return null;}-function SyncStatusBadge({ label, icon: Icon, localSeq: _localSeq, peerSeq, cursorSeq }) {- // cursorSeq = how far we've pulled from them (our cursor for their data)- // localSeq = our local max seq for this data type- // peerSeq = their max seq for this data type (from their sync-status endpoint)-- // "Inbound" = are we caught up with them? (our cursor vs their max)- const inboundSynced = peerSeq != null && cursorSeq != null && String(cursorSeq) === String(peerSeq);- const inboundBehind = peerSeq != null && cursorSeq != null && String(cursorSeq) !== String(peerSeq);-- if (peerSeq == null && cursorSeq == null) return null;+function SyncStatusBadge({ label, icon: Icon, localSeq, peerSeq, cursorSeq, peerCursorForUs, syncing }) {+ // cursorSeq = how far we've pulled from them (our cursor for their data)+ // localSeq = our local max seq for this data type+ // peerSeq = their max seq for this data type (their sync-status endpoint)+ // peerCursorForUs = how far THEY've pulled from us (their cursor into our data)+ //+ // Two directions, both in plain language (raw seqs live in the tooltip):+ // toPull = peerSeq - cursorSeq (their items we haven't pulled)+ // toPush = localSeq - peerCursorForUs (our items they haven't pulled)+ const { toPull, toPush } = directionalCounts({+ localMax: localSeq,+ peerMax: peerSeq,+ ourCursor: cursorSeq,+ peerCursorForUs,+ });+ const { state, text } = describeDirectional({ toPull, toPush });++ // Nothing known at all (no probe yet, no cursor) → render nothing.+ if (peerSeq == null && cursorSeq == null && peerCursorForUs == null && localSeq == null) return null;++ const StateIcon = syncing ? RefreshCw : state === 'synced' ? CheckCircle2 : state === 'behind' ? AlertCircle : Clock;+ const iconClass = syncing+ ? 'text-port-accent animate-spin'+ : state === 'synced' ? 'text-port-success' : state === 'behind' ? 'text-port-warning' : 'text-gray-500';+ const textClass = syncing+ ? 'text-port-accent'+ : state === 'synced' ? 'text-port-success' : state === 'behind' ? 'text-port-warning' : 'text-gray-400';++ // Raw sequences retained for debugging in the tooltip.+ const tooltip = `Pulled ${cursorSeq ?? 0} of their ${peerSeq ?? '?'} · `+ + `they pulled ${peerCursorForUs ?? '?'} of our ${localSeq ?? '?'}`;return (<div className="flex items-center gap-1.5 text-xs"><Icon size={12} className="text-gray-500" /><span className="text-gray-500">{label}:</span>- {peerSeq != null ? (- <span className="flex items-center gap-0.5" title={`Our cursor: ${cursorSeq ?? 0} / Their max: ${peerSeq}`}>- {inboundSynced ? (- <CheckCircle2 size={11} className="text-port-success" />- ) : inboundBehind ? (- <AlertCircle size={11} className="text-port-warning" />- ) : (- <Clock size={11} className="text-gray-500" />- )}- <span className={inboundSynced ? 'text-port-success' : inboundBehind ? 'text-port-warning' : 'text-gray-400'}>- {cursorSeq ?? 0}/{peerSeq}- </span>- </span>- ) : (- <span className="flex items-center gap-0.5" title="Waiting for peer sync status">- <Clock size={11} className="text-gray-500" />- <span className="text-gray-500">{cursorSeq ?? 0}/?</span>- </span>- )}+ <span className="flex items-center gap-1" title={tooltip}>+ <StateIcon size={11} className={iconClass} />+ <span className={textClass}>{syncing ? 'syncing…' : text}</span>+ </span></div>);}@@ -620,7 +627,7 @@ function SyncCategoriesPanel({ peer, onRefresh }) {);}-function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum, livePushCovered, subsLoaded = true }) {+function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum, livePushCovered, subsLoaded = true, syncing = false }) {// `livePushCovered` is true when this peer has at least one per-record// peer-sync subscription for a record kind that maps to this category// (universe-subs → 'universe', series-subs → 'pipeline'). The orchestrator@@ -639,7 +646,12 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum,<div className="flex items-center gap-1.5 text-xs"><Icon size={12} className="text-gray-500" /><span className="text-gray-500">{label}:</span>- {livePushCovered ? (+ {syncing ? (+ <>+ <RefreshCw size={11} className="text-port-accent animate-spin" />+ <span className="text-port-accent">syncing…</span>+ </>+ ) : livePushCovered ? (<><ArrowLeftRight size={11} className="text-port-accent" /><span className="text-port-accent" title="Per-record push pipeline owns this category; snapshot cursor is intentionally stale">@@ -666,12 +678,16 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum,);}-function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = true }) {+function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = true, syncing = false }) {if (!syncStatus || !peer.instanceId) return null;const cursor = syncStatus.cursors?.[peer.instanceId];const remoteSyncSeqs = peer.remoteSyncSeqs;const categories = peer.syncCategories || {};+ // The peer's cursor into OUR data (how far it has pulled from us) — the+ // push-frontier toward this peer. Present only when our probe passed `forPeer`+ // and the peer is new enough to report it; absent → push count is "unknown".+ const peerCursorForUs = remoteSyncSeqs?.cursorForYou ?? null;// No sync data available at allif (!cursor && !remoteSyncSeqs) return null;@@ -720,6 +736,8 @@ function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = tlocalSeq={syncStatus.local?.brainSeq}peerSeq={remoteSyncSeqs?.brainSeq}cursorSeq={cursor?.brainSeq}+ peerCursorForUs={peerCursorForUs?.brainSeq}+ syncing={syncing}/>)}{showMemory && (@@ -729,6 +747,8 @@ function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = tlocalSeq={syncStatus.local?.memorySeq}peerSeq={remoteSyncSeqs?.memorySeq}cursorSeq={cursor?.memorySeq}+ peerCursorForUs={peerCursorForUs?.memorySeq}+ syncing={syncing}/>)}{enabledSnapshots.map(cat => {@@ -743,6 +763,7 @@ function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = tremoteChecksum={remoteChecksums[cat]}livePushCovered={livePushCovered.has(cat)}subsLoaded={peerSubsLoaded}+ syncing={syncing}/>);})}@@ -961,6 +982,31 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {// is [] and SyncStatusSection can't tell a live-push category from a behind// one, so it would flash "behind". Gates the snapshot badges' "behind" state.const [peerSubsLoaded, setPeerSubsLoaded] = useState(false);+ // Live sync activity, driven by the `sync:progress` socket event. `syncing`+ // is true between this peer's `start` and `complete`; while it's true every+ // enabled category badge shows "syncing…". On `complete` it clears and the+ // parent's peers refetch settles the card to the new directional summary.+ const [syncing, setSyncing] = useState(false);++ useEffect(() => {+ if (!peer.instanceId) return;+ const handleProgress = (payload) => {+ if (payload?.peerId !== peer.instanceId) return;+ if (payload.phase === 'start') {+ setSyncing(true);+ } 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.+ 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+ // needn't track per-category granularity.+ };+ socket.on('sync:progress', handleProgress);+ return () => socket.off('sync:progress', handleProgress);+ }, [peer.instanceId, onRefresh]);useEffect(() => {if (!peer.instanceId) {@@ -1033,6 +1079,20 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {setProbing(false);};+ const handleSync = async () => {+ // Optimistically flip the card into its syncing state — the server's+ // `sync:progress` start event will confirm it, but this gives instant+ // feedback even before the socket round-trips. The custom catch owns the+ // error UI, so request() must stay silent to avoid a double toast.+ setSyncing(true);+ const result = await syncPeer(peer.id, { silent: true }).catch(() => null);+ if (!result) {+ setSyncing(false);+ toast.error(`Couldn't sync with ${peer.name} — is it online?`);+ }+ // On success the `complete` progress event clears `syncing` and refreshes.+ };+const handleRemove = async () => {const result = await removePeer(peer.id).catch(() => null);if (!result) return;@@ -1080,6 +1140,14 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {)}</div><div className="flex items-center gap-1">+ <button+ onClick={handleSync}+ disabled={syncing || peer.status !== 'online'}+ className="p-1.5 text-gray-500 hover:text-port-accent transition-colors disabled:opacity-40 disabled:hover:text-gray-500"+ title={peer.status === 'online' ? 'Sync now' : 'Peer offline — cannot sync'}+ >+ <RefreshCcw size={14} className={syncing ? 'animate-spin text-port-accent' : ''} />+ </button><buttononClick={handleProbe}disabled={probing}@@ -1152,7 +1220,7 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {<SyncCategoriesPanel peer={peer} onRefresh={onRefresh} />- <SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} />+ <SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} syncing={syncing} /><PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />{peer.status === 'online' && (diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 3870c95834..294b7e4dad 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -175,6 +175,7 @@ export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'Dexport 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 syncPeer = (id, options) => request(`/instances/peers/${id}/sync`, { method: 'POST', ...options });export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);export const getTailnetInfo = () => request('/instances/tailnet-suffix');export const provisionTailnetCert = () => request('/instances/provision-cert', { method: 'POST' });diff --git a/server/routes/instances.js b/server/routes/instances.jsindex d9c3ed67cb..7281b53df6 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -9,7 +9,7 @@ import { z } from 'zod';import { execFile } from 'child_process';import { promisify } from 'util';import * as instances from '../services/instances.js';-import { getSyncStatus } from '../services/syncOrchestrator.js';+import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';import { provisionTailscaleCert } from '../services/certProvisioner.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';@@ -120,12 +120,22 @@ router.get('/', asyncHandler(async (req, res) => {}));// GET /api/instances/sync-status — local sync sequences + checksums (used by peers during probe)+// A probing peer may pass `?forPeer=<its instanceId>` to also receive OUR cursor+// into its data (`cursorForYou`) — how far we've pulled from it. That cursor is+// the peer's push-frontier toward us, so it can render an outbound "N to push"+// count. Older peers omit the param and get the legacy (inbound-only) shape.+const syncStatusQuerySchema = z.object({+ forPeer: z.string().guid().optional()+});router.get('/sync-status', asyncHandler(async (req, res) => {- const status = await getSyncStatus({ includeChecksums: true });+ const { forPeer } = syncStatusQuerySchema.parse(req.query);+ const status = await getSyncStatus({ includeChecksums: true, forPeer });res.json({brainSeq: status.local.brainSeq,memorySeq: status.local.memorySeq,- checksums: status.local.checksums+ checksums: status.local.checksums,+ // Present only when `forPeer` was supplied and we've synced it before.+ ...(status.cursorForYou ? { cursorForYou: status.cursorForYou } : {})});}));@@ -290,6 +300,22 @@ router.post('/peers/:id/probe', asyncHandler(async (req, res) => {res.json(instances.sanitizePeerForClient(result));}));+// POST /api/instances/peers/:id/sync — force an immediate sync with this peer.+// Probe first so the cursor-reset detection has fresh remoteSyncSeqs, then run+// the full sync. syncWithPeer emits `sync:progress` events so the card animates+// live and settles to the new directional summary without a manual refresh.+router.post('/peers/:id/sync', 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 probed = await instances.probePeer(peer);+ if (probed?.status !== 'online') {+ throw new ServerError('Peer is offline — cannot sync', { status: 409, code: 'PEER_OFFLINE' });+ }+ const result = await syncWithPeer(probed);+ res.json({ ok: true, result });+}));+// GET /api/instances/peers/:id/query — proxy GET to peerrouter.get('/peers/:id/query', asyncHandler(async (req, res) => {const { path } = querySchema.parse(req.query);diff --git a/server/services/instances.js b/server/services/instances.jsindex 268b359cd1..1492f23b5a 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -461,12 +461,20 @@ export async function probePeer(peer) {// opposed to an unreachable one. The Instances UI reads this to prompt for a// credential instead of showing a generic offline state.let authRequired = false;+ // Pass our own instanceId as `forPeer` so the peer also returns ITS cursor+ // into our data (`cursorForYou`) — our push-frontier toward it. Best-effort:+ // an unresolved/unknown id just omits the param and we get the inbound-only+ // shape (push count renders "unknown" client-side, never a misleading 0).+ const ourInstanceId = await getInstanceId().catch(() => null);+ const forPeerQs = typeof ourInstanceId === 'string' && ourInstanceId && ourInstanceId !== UNKNOWN_INSTANCE_ID+ ? `?forPeer=${encodeURIComponent(ourInstanceId)}`+ : '';try {// Fetch health details, apps, and sync status in parallelconst [healthRes, appsRes, syncRes] = await Promise.all([peerFetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }, peer),peerFetch(`${baseUrl}/api/apps`, { signal: controller.signal }, peer).catch(() => null),- peerFetch(`${baseUrl}/api/instances/sync-status`, { signal: controller.signal }, peer).catch(() => null)+ peerFetch(`${baseUrl}/api/instances/sync-status${forPeerQs}`, { signal: controller.signal }, peer).catch(() => null)]);if (!healthRes.ok) {const err = new Error(`HTTP ${healthRes.status}`);diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 92a5b3d73f..c83dbfcbe9 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -455,8 +455,10 @@ describe('instances.js', () => {// Relay pins the Basic header at connect time, so a credential change// must tear it down to reconnect with the new extraHeaders.expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');- // Immediate re-probe fired (bypasses the nextProbeAt backoff gate).- expect(fetch).toHaveBeenCalled();+ // Immediate re-probe fired (bypasses the nextProbeAt backoff gate). The+ // probe is fire-and-forget and now resolves our instanceId (one extra+ // microtask) before fetching sync-status, so wait for the fetch.+ await vi.waitFor(() => expect(fetch).toHaveBeenCalled());});it('should NOT reconnect or re-probe on a no-op credential write', async () => {diff --git a/server/services/socket.js b/server/services/socket.jsindex bcce4c5aa4..41d37d9f12 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -852,6 +852,11 @@ function setupInstanceEventForwarding() {const sanitized = Array.isArray(data) ? data.map(sanitizePeerForClient) : data;broadcastToInstances('instances:peers:updated', sanitized);});+ // Realtime sync lifecycle for the Instances cards: { phase, peerId, ... }.+ // No secrets — just a peer instanceId + counts — so forward as-is.+ instanceEvents.on('sync:progress', (data) => {+ broadcastToInstances('sync:progress', data);+ });}// Set up peer agent event forwarding (remote agent streaming)diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex b116cfba5b..f37b178857 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -32,6 +32,19 @@ let syncTimer = null;let peerOnlineHandler = null;const syncingPeers = new Set();+// --- Realtime sync progress ---+//+// Emit per-peer sync lifecycle events so the Instances UI can animate a card+// while a sync is actively churning (vs. only updating after a manual probe).+// `socket.js` forwards `sync:progress` to instance subscribers. Phases:+// { phase: 'start', peerId }+// { phase: 'applied', peerId, category, applied } // one per category with changes+// { phase: 'complete', peerId, totalApplied }+// Fire-and-forget; a missing/uninitialized emitter must never break a sync.+function emitSyncProgress(payload) {+ if (typeof instanceEvents?.emit === 'function') instanceEvents.emit('sync:progress', payload);+}+// --- Cursor persistence ---async function loadCursors() {@@ -105,7 +118,7 @@ async function syncImageFromPeer(peer, avatarPath) {/*** Get sync status: local sequences + per-peer cursors + optional local checksums*/-export async function getSyncStatus({ includeChecksums = false } = {}) {+export async function getSyncStatus({ includeChecksums = false, forPeer = null } = {}) {const isPostgres = getBackendName() === 'postgres';const snapshotCategories = includeChecksums ? dataSync.getSupportedCategories() : [];const [brainSeq, memorySeq, catalogSeqs, cursors, ...checksumResults] = await Promise.all([@@ -122,7 +135,16 @@ export async function getSyncStatus({ includeChecksums = false } = {}) {local.checksums[snapshotCategories[i]] = checksumResults[i]?.checksum ?? null;}}- return { local, cursors };+ const result = { local, cursors };+ // When a peer asks "how much of MY data have you pulled?" (it passes its own+ // instanceId as `forPeer`), return OUR cursor into that peer's data — i.e. how+ // far we've consumed from it. That cursor IS the peer's push-frontier toward+ // us, so the requesting peer can render an outbound "N to push" count without+ // us tracking its local max. Null when we've never synced that peer.+ if (isNonEmptyStr(forPeer)) {+ result.cursorForYou = cursors[forPeer] ?? null;+ }+ return result;}// --- Sync logic ---@@ -577,6 +599,7 @@ export async function syncWithPeer(peer) {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)@@ -585,11 +608,22 @@ export async function syncWithPeer(peer) {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) => {+ if (applied > 0) emitSyncProgress({ phase: 'applied', peerId, category, applied });+ };++ // Track whether the normal `complete` emit fired, so the `finally` can settle+ // a card whose sync threw mid-flight instead of leaving it spinning forever.+ let completed = false;+try {// --- Brain sync (delta-based) ---let brainResult = { brainSeq: cursor.brainSeq ?? 0, totalApplied: 0 };if (categories.brain) {brainResult = await syncBrainFromPeer(peer, cursor);+ reportApplied('brain', brainResult.totalApplied);}// --- Memory sync (delta-based, PostgreSQL only) ---@@ -598,6 +632,7 @@ export async function syncWithPeer(peer) {const isPostgres = getBackendName() === 'postgres';if (isPostgres) {memoryResult = await syncMemoryFromPeer(peer, cursor);+ reportApplied('memory', memoryResult.totalApplied);}}@@ -607,6 +642,7 @@ export async function syncWithPeer(peer) {const isPostgres = getBackendName() === 'postgres';if (isPostgres) {catalogResult = await syncCatalogFromPeer(peer, peerId, cursor);+ reportApplied('catalog', catalogResult.totalApplied);}}@@ -644,6 +680,7 @@ export async function syncWithPeer(peer) {for (let i = 0; i < enabledDataCats.length; i++) {const result = settled[i].status === 'fulfilled' ? settled[i].value : { totalApplied: 0, checksum: null };dataCategoryResults[enabledDataCats[i]] = result;+ reportApplied(enabledDataCats[i], result.totalApplied);}}@@ -677,9 +714,18 @@ export async function syncWithPeer(peer) {console.log(`🔄 Synced with ${peer.name}: ${parts.join(', ')} changes`);}+ const totalApplied = brainResult.totalApplied + memoryResult.totalApplied+ + catalogResult.totalApplied+ + Object.values(dataCategoryResults).reduce((sum, r) => sum + (r?.totalApplied || 0), 0);+ completed = true;+ emitSyncProgress({ phase: 'complete', peerId, totalApplied });+return { brain: brainResult, memory: memoryResult, catalog: catalogResult, ...dataCategoryResults };} finally {syncingPeers.delete(peerId);+ // If the sync threw before the normal complete emit, still settle the card+ // out of its "syncing" state (a stuck spinner is worse than a silent stop).+ if (!completed) emitSyncProgress({ phase: 'complete', peerId, totalApplied: 0 });}}diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 044ac15859..4333d58294 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -16,6 +16,7 @@ vi.mock('./instances.js', () => ({}));vi.mock('./brainSyncLog.js', () => ({getChangesSince: vi.fn(),+ getCurrentSeq: vi.fn(() => 0),compactLog: vi.fn().mockResolvedValue(0)}));vi.mock('./brainSync.js', () => ({@@ -56,7 +57,7 @@ vi.mock('./sharing/peerSync.js', () => ({}),}));vi.mock('./instanceEvents.js', () => ({- instanceEvents: { on: vi.fn(), removeListener: vi.fn() }+ instanceEvents: { on: vi.fn(), removeListener: vi.fn(), emit: vi.fn() }}));vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),@@ -84,7 +85,9 @@ import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';import { applyRemoteChanges as applyMemoryChanges } from './memorySync.js';import { applyRemoteChanges as applyCatalogChanges } from './catalogSync.js';import { instanceEvents } from './instanceEvents.js';-import { syncWithPeer, syncAllPeers, initSyncOrchestrator, stopSyncOrchestrator } from './syncOrchestrator.js';+import { getCurrentSeq } from './brainSyncLog.js';+import { getMaxSequence } from './memorySync.js';+import { syncWithPeer, syncAllPeers, getSyncStatus, initSyncOrchestrator, stopSyncOrchestrator } from './syncOrchestrator.js';const mockFetch = vi.fn();@@ -568,6 +571,72 @@ describe('syncOrchestrator', () => {});});+ describe('getSyncStatus forPeer / cursorForYou', () => {+ it('returns our cursor into the requesting peer as cursorForYou', async () => {+ getCurrentSeq.mockReturnValue(120);+ getMaxSequence.mockResolvedValue('45');+ // Our stored cursors: how far we've pulled from each peer. The requesting+ // peer ('peer-A') wants its own entry back as its push-frontier toward us.+ readJSONFile.mockImplementation(async () => ({+ 'peer-A': { brainSeq: 88, memorySeq: '30', lastSyncAt: '2026-01-01T00:00:00.000Z' },+ 'peer-B': { brainSeq: 5 },+ }));++ const status = await getSyncStatus({ forPeer: 'peer-A' });+ expect(status.cursorForYou).toEqual({ brainSeq: 88, memorySeq: '30', lastSyncAt: '2026-01-01T00:00:00.000Z' });+ // Our own local maxes are reported under `local`.+ expect(status.local.brainSeq).toBe(120);+ });++ it('returns null cursorForYou when we have never synced the requesting peer', async () => {+ readJSONFile.mockImplementation(async () => ({ 'peer-B': { brainSeq: 5 } }));+ const status = await getSyncStatus({ forPeer: 'peer-A' });+ expect(status.cursorForYou).toBeNull();+ });++ it('omits cursorForYou entirely when no forPeer is supplied (legacy shape)', async () => {+ readJSONFile.mockImplementation(async () => ({ 'peer-A': { brainSeq: 88 } }));+ const status = await getSyncStatus({});+ expect(status).not.toHaveProperty('cursorForYou');+ });+ });++ describe('sync:progress events', () => {+ it('emits start → applied → complete around a sync that moves records', async () => {+ mockFetch+ .mockResolvedValueOnce({ ok: true, json: async () => ({ changes: [{ id: 'b1' }], maxSeq: 1, hasMore: false }) })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ changes: [], maxSeq: 1, hasMore: false }) })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ memories: [], maxSequence: '0', hasMore: false }) });+ applyBrainChanges.mockResolvedValue({ inserted: 1, updated: 0, deleted: 0, skipped: 0 });++ await syncWithPeer({ ...mockPeer, syncCategories: { brain: true, memory: true } });++ const progressCalls = instanceEvents.emit.mock.calls+ .filter(([event]) => event === 'sync:progress')+ .map(([, payload]) => payload);+ expect(progressCalls[0]).toEqual({ phase: 'start', peerId: 'peer-inst-1' });+ expect(progressCalls).toContainEqual({ phase: 'applied', peerId: 'peer-inst-1', category: 'brain', applied: 1 });+ const complete = progressCalls.find(p => p.phase === 'complete');+ expect(complete).toMatchObject({ phase: 'complete', peerId: 'peer-inst-1' });+ expect(complete.totalApplied).toBeGreaterThanOrEqual(1);+ });++ 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 }) });+ await syncWithPeer({ ...mockPeer, syncCategories: { brain: true } });++ const progress = instanceEvents.emit.mock.calls+ .filter(([event]) => event === 'sync:progress')+ .map(([, payload]) => payload);+ const completes = progress.filter(p => p.phase === 'complete');+ // Exactly one complete, and no spurious second one from the finally guard.+ expect(completes).toEqual([{ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0 }]);+ // No `applied` events when nothing moved.+ expect(progress.some(p => p.phase === 'applied')).toBe(false);+ });+ });+describe('syncAllPeers', () => {it('iterates online peers with instanceId', async () => {const onlinePeer = { ...mockPeer };