Skip to content

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

fix: report unavailable full-sync coverage when reads fail (#7134)

[._.]/ Adam Eivy2864c111b9a3
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index b0724c0bbf..55ee74a8d6 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -607,9 +607,16 @@ function FullSyncCoverageBadge({ peerId, peerInstanceId, refreshKey }) {
if (!peerInstanceId) {
return <span className="text-[10px] text-gray-600">awaiting first connection…</span>;
}
- if (!loaded || !coverage) {
+ if (!loaded) {
return <span className="text-[10px] text-gray-600">checking coverage…</span>;
}
+ if (!coverage || coverage.available === false || coverage.partial === true) {
+ return (
+ <span className="flex items-center gap-1 text-[10px] text-port-warning" title="Coverage could not be verified. Any available counts are partial; retry on the next refresh.">
+ <AlertCircle size={11} /> Coverage unavailable
+ </span>
+ );
+ }
if (coverage.fullyMirrored) {
return (
<span className="flex items-center gap-1 text-[10px] text-port-success" title={`All ${coverage.total} record(s) confirmed-delivered to this peer`}>
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 598601fb97..964e7c7b66 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -256,6 +256,29 @@ describe('PeerCard snapshot progress', () => {
expect(badge('Pipeline').getByText('pending')).toBeInTheDocument();
});
+ it('shows unavailable for degraded coverage, request failure, and recovers on refresh', async () => {
+ getPeerFullSyncCoverage.mockResolvedValue({
+ available: false, partial: true, fullyMirrored: false, total: 2, confirmed: 2, pending: 0,
+ });
+ const props = { peer: { ...peer, fullSync: true, lastSeen: 'first' }, syncStatus, onRefresh: vi.fn() };
+ const view = renderUI(<PeerCard {...props} />);
+ fireEvent.click(screen.getByRole('button', { name: /sync categories/i }));
+ expect(await screen.findByText('Coverage unavailable')).toHaveClass('text-port-warning');
+ expect(screen.queryByText(/Fully mirrored/)).not.toBeInTheDocument();
+ expect(screen.getByText('Coverage unavailable')).toHaveAttribute('title', expect.stringContaining('partial'));
+
+ getPeerFullSyncCoverage.mockRejectedValue(new Error('Request failed'));
+ view.rerender(<PeerCard {...props} peer={{ ...props.peer, lastSeen: 'second' }} />);
+ await waitFor(() => expect(getPeerFullSyncCoverage).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('Coverage unavailable')).toBeInTheDocument();
+ expect(screen.queryByText('checking coverage…')).not.toBeInTheDocument();
+
+ getPeerFullSyncCoverage.mockResolvedValue({ fullyMirrored: false, total: 3, confirmed: 2, pending: 1 });
+ view.rerender(<PeerCard {...props} peer={{ ...props.peer, lastSeen: 'third' }} />);
+ expect(await screen.findByText('1 pending · 2/3 mirrored')).toBeInTheDocument();
+ expect(screen.queryByText('Coverage unavailable')).not.toBeInTheDocument();
+ });
+
// A slow or failed subscription endpoint must not hide a known mismatch.
it('shows known status while subscriptions are unresolved and after they fail', async () => {
let rejectSubscriptions;
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index 52d5253d68..3186c6c3d9 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -16,6 +16,7 @@ vi.mock('../services/instances.js', async (importOriginal) => ({
addPeer: vi.fn(),
sanitizePeerForClient: vi.fn((peer) => peer),
getAssignableInstances: vi.fn(),
+ getPeers: vi.fn(),
}));
// This suite's routes/instances.js import pulls getSelf/updateSelf from the
// identity leaf (#6836) — double it too so an untested route (e.g. GET /
@@ -34,6 +35,7 @@ vi.mock('../lib/tailscale.js', () => ({
getTailscaleStatus: vi.fn(),
}));
+import { getFullSyncCoverageForPeer } from '../services/sharing/peerSync.js';
import { getSyncStatus } from '../services/syncOrchestrator.js';
import * as instances from '../services/instances.js';
import { getTailscaleStatus } from '../lib/tailscale.js';
@@ -397,3 +399,20 @@ it('rejects main API and HTTP mirror ports for managed serving', async () => {
expect(response.status).toBe(400);
}
});
+
+describe('GET /api/instances/peers/:id/full-sync-coverage', () => {
+ it('preserves unavailable coverage and partial counts on the local endpoint', async () => {
+ instances.getPeers.mockResolvedValue([{ id: 'peer-1', instanceId: 'remote-1' }]);
+ const coverage = {
+ total: 2, confirmed: 2, pending: 0, fullyMirrored: false,
+ available: false, partial: true,
+ failedReads: [{ kind: 'universe', operation: 'records' }],
+ byKind: { universe: { total: 0, confirmed: 0, pending: 0, partial: true } },
+ };
+ getFullSyncCoverageForPeer.mockResolvedValue(coverage);
+ const res = await request(buildApp()).get('/api/instances/peers/peer-1/full-sync-coverage');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(coverage);
+ expect(getFullSyncCoverageForPeer).toHaveBeenCalledWith('remote-1');
+ });
+});
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 7ba976b641..f0b6c13470 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -156,9 +156,8 @@ export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {
* imports merge entry points from universeBuilder / pipeline.series).
*/
/**
- * Per-kind lister thunks for `listRecordsForKind` below. Each entry mirrors the
- * exact error handling the kind had before this was table-ized — every lister
- * here still swallows its own failure with `.catch(() => [])`. Universe/series
+ * Per-kind lister thunks for `listRecordsForKind` below. Read failures propagate
+ * so callers can distinguish unavailable inventory from an empty one. Universe/series
* are wrapped so their `import()` stays lazy, invoked only when that kind is
* actually requested — the map's own construction imports nothing.
*
@@ -175,40 +174,40 @@ const RECORD_KIND_LISTERS = {
// merge entry point).
universe: async () => {
const { listUniverses } = await import('../universeBuilder.js');
- return listUniverses({ includeDeleted: false }).catch(() => []);
+ return listUniverses({ includeDeleted: false });
},
// Dynamic-imported to avoid a static cycle (peerSync already imports its
// merge entry point).
series: async () => {
const { listSeries } = await import('../pipeline/series.js');
- return listSeries({ includeDeleted: false }).catch(() => []);
+ return listSeries({ includeDeleted: false });
},
- mediaCollection: () => listCollections({ includeDeleted: false }).catch(() => []),
- author: () => listAuthors({ includeDeleted: false }).catch(() => []),
- artist: () => listArtists({ includeDeleted: false }).catch(() => []),
- album: () => listAlbums({ includeDeleted: false }).catch(() => []),
- track: () => listTracks({ includeDeleted: false }).catch(() => []),
- creativeDirectorProject: () => listProjects({ includeDeleted: false }).catch(() => []),
- moodBoard: () => listBoards({ includeDeleted: false }).catch(() => []),
- fableLoom: () => listLooms({ includeDeleted: false }).catch(() => []),
+ mediaCollection: () => listCollections({ includeDeleted: false }),
+ author: () => listAuthors({ includeDeleted: false }),
+ artist: () => listArtists({ includeDeleted: false }),
+ album: () => listAlbums({ includeDeleted: false }),
+ track: () => listTracks({ includeDeleted: false }),
+ creativeDirectorProject: () => listProjects({ includeDeleted: false }),
+ moodBoard: () => listBoards({ includeDeleted: false }),
+ fableLoom: () => listLooms({ includeDeleted: false }),
// Live works as { id, updatedAt } (full-sync coverage compares updatedAt to
// detect a stale confirmed push; bare {id} stubs would report a changed
// manuscript as fully mirrored). Without this branch, enabling the
// writersRoomWorks category (or full-sync) would backfill nothing.
- writersRoomWork: () => listWorksForSync().catch(() => []),
+ writersRoomWork: () => listWorksForSync(),
// Live folders as { id, updatedAt } (#1645) — same coverage-compare reason
// as works. Body-less, so no asset/body manifest backfill.
- writersRoomFolder: () => listFoldersForSync().catch(() => []),
+ writersRoomFolder: () => listFoldersForSync(),
// Live exercises as { id, updatedAt } (#1645). updatedAt is derived from
// finishedAt ?? startedAt in the facade so coverage keys on the wire value.
- writersRoomExercise: () => listExercisesForSync().catch(() => []),
- musicVideoProject: () => listMusicVideoProjects({ includeDeleted: false }).catch(() => []),
+ writersRoomExercise: () => listExercisesForSync(),
+ musicVideoProject: () => listMusicVideoProjects({ includeDeleted: false }),
// Live feedback reactions as { id, updatedAt } (#2686) — same coverage-compare
// reason as folders. Body-less, so no asset manifest backfill.
- commissionFeedback: () => listCommissionFeedbackForSync().catch(() => []),
+ commissionFeedback: () => listCommissionFeedbackForSync(),
// Live commission briefs as { id, updatedAt } (#2686). Body-less on the wire
// (schedule/runs/assignment stripped), so no asset manifest backfill.
- creativeCommission: () => listCommissionsForSync().catch(() => []),
+ creativeCommission: () => listCommissionsForSync(),
};
/**
@@ -234,7 +233,10 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
const peers = await getPeers().catch(() => []);
const peer = peers.find(p => p.instanceId === peerId);
if (!peer || !peerAllowsOutbound(peer) || !peerHasCategory(peer, recordKind)) return [];
- const records = await listRecordsForKind(recordKind);
+ const records = await listRecordsForKind(recordKind).catch(() => {
+ console.log(`⚠️ peerSync: backfill inventory unavailable for ${recordKind}/records`);
+ return [];
+ });
if (records.length === 0) return [];
// Compute the set difference up front: which local records aren't yet
// subscribed to this peer? The peer:online convergence path fires this
@@ -288,18 +290,27 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
* sequence numbers, not row counts, and would misreport coverage). A record is
* "pending" when it has no subscription to this peer OR its subscription hasn't
* been confirmed-delivered yet. Returns per-kind breakdown plus totals, and
- * `fullyMirrored` (pending === 0).
+ * `fullyMirrored` only when all reads succeeded and pending === 0. Failed reads
+ * expose only kind/operation identifiers; retained counts are explicitly partial.
*/
export async function getFullSyncCoverageForPeer(peerId) {
- const empty = { total: 0, confirmed: 0, pending: 0, fullyMirrored: true, byKind: {} };
+ const empty = { total: 0, confirmed: 0, pending: 0, fullyMirrored: true, byKind: {}, available: true, partial: false, failedReads: [] };
if (!isNonBlankStr(peerId)) return empty;
// Each kind's record list + subscription list are independent I/O — fetch all
// kinds (and the two lists within a kind) concurrently.
const perKind = await Promise.all(PEER_SUBSCRIBABLE_KINDS.map(async (kind) => {
- const [records, subs] = await Promise.all([
- listRecordsForKind(kind).catch(() => []),
- listPeerSubscriptions({ peerId, recordKind: kind }).catch(() => []),
+ const results = await Promise.allSettled([
+ listRecordsForKind(kind),
+ listPeerSubscriptions({ peerId, recordKind: kind }),
]);
+ const failedReads = results.flatMap((result, index) => {
+ if (result.status === 'fulfilled') return [];
+ const operation = index === 0 ? 'records' : 'subscriptions';
+ console.log(`⚠️ peerSync: full-sync coverage unavailable for ${kind}/${operation}`);
+ return [{ kind, operation }];
+ });
+ const records = results[0].status === 'fulfilled' ? results[0].value : [];
+ const subs = results[1].status === 'fulfilled' ? results[1].value : [];
// Map each subscribed record to its confirmed-delivery water-mark (ms epoch).
const confirmedAtById = new Map(subs.filter(s => s.lastConfirmedPushedAt).map(s => [s.recordId, s.lastConfirmedPushedAt]));
// A record counts as mirrored only when a confirmed push covers its CURRENT
@@ -315,18 +326,21 @@ export async function getFullSyncCoverageForPeer(peerId) {
// No parseable updatedAt → can't prove staleness; trust the confirmation.
return !Number.isFinite(updatedAt) || confirmedAt >= updatedAt;
}).length;
- return { kind, total: kindTotal, confirmed: kindConfirmed, pending: kindTotal - kindConfirmed };
+ return { kind, total: kindTotal, confirmed: kindConfirmed, pending: kindTotal - kindConfirmed, failedReads };
}));
const byKind = {};
+ const failedReads = perKind.flatMap(k => k.failedReads);
let total = 0;
let confirmed = 0;
for (const k of perKind) {
byKind[k.kind] = { total: k.total, confirmed: k.confirmed, pending: k.pending };
+ if (k.failedReads.length > 0) byKind[k.kind].partial = true;
total += k.total;
confirmed += k.confirmed;
}
const pending = total - confirmed;
- return { total, confirmed, pending, fullyMirrored: pending === 0, byKind };
+ const available = failedReads.length === 0;
+ return { total, confirmed, pending, fullyMirrored: available && pending === 0, byKind, available, partial: !available, failedReads };
}
/**
@@ -700,8 +714,8 @@ export async function syncNowForPeer(peerId) {
if (!peer?.instanceId) return { ok: false };
for (const kind of PEER_SUBSCRIBABLE_KINDS) {
if (peerHasCategory(peer, kind)) {
- await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch((err) => {
- console.log(`⚠️ peerSync: syncNow backfill ${kind} → ${peerId} failed: ${err.message}`);
+ await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {
+ console.log(`⚠️ peerSync: syncNow backfill failed for ${kind}`);
});
}
}
@@ -773,7 +787,9 @@ export function installPeerSyncListener() {
// full-sync peer whose instanceId we only just learned) still back-
// subscribes every kind here.
if (peerHasCategory(peer, kind)) {
- await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {});
+ await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {
+ console.log(`⚠️ peerSync: peer:online backfill failed for ${kind}`);
+ });
}
}
await retryPendingPushesForPeer(peer.instanceId).catch(() => {});
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 37c0ad0768..7e303892e3 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -367,6 +367,8 @@ beforeEach(async () => {
// return Promises; production code can assume this, but the test mock
// has to match, including listIssuesForSeries so a buildPushPayload path
// that bundles child issues doesn't choke on an un-overridden mock.
+ vi.mocked(listUniverses).mockReset().mockResolvedValue([]);
+ vi.mocked(listSeries).mockReset().mockResolvedValue([]);
vi.mocked(getUniverse).mockReset().mockResolvedValue(undefined);
vi.mocked(getSeries).mockReset().mockResolvedValue(undefined);
vi.mocked(getIssue).mockReset().mockResolvedValue(undefined);
@@ -659,7 +661,37 @@ describe('peerSync', () => {
it('reports fully-mirrored with zero total when there are no local records', async () => {
// All listers default to [] in the suite-level beforeEach.
const cov = await getFullSyncCoverageForPeer('peer-a');
- expect(cov).toMatchObject({ total: 0, confirmed: 0, pending: 0, fullyMirrored: true });
+ expect(cov).toMatchObject({ total: 0, confirmed: 0, pending: 0, fullyMirrored: true, available: true, partial: false, failedReads: [] });
+ });
+
+ // An inventory failure must survive both lazy and direct lister boundaries.
+ it('marks failed inventories unavailable even when the remaining subset is confirmed', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.mocked(listUniverses).mockRejectedValue(new Error('private database details'));
+ vi.mocked(listAuthors).mockRejectedValue(new Error('private author contents'));
+ vi.mocked(listSeries).mockResolvedValue([{ id: 's1' }]);
+ await writeFile(join(tmp, 'sharing', 'peer_subscriptions.json'), JSON.stringify({
+ subscriptions: [{ id: 'sub-s1', peerId: 'peer-a', recordKind: 'series', recordId: 's1', lastConfirmedPushedAt: Date.now() }],
+ }));
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov).toMatchObject({ available: false, partial: true, fullyMirrored: false, total: 1, confirmed: 1, pending: 0 });
+ expect(cov.failedReads).toEqual([
+ { kind: 'universe', operation: 'records' },
+ { kind: 'author', operation: 'records' },
+ ]);
+ expect(cov.byKind.universe).toMatchObject({ partial: true });
+ expect(JSON.stringify(cov)).not.toContain('private');
+ expect(log.mock.calls.flat().join(' ')).not.toContain('private');
+ expect(log.mock.calls.filter(([message]) => message.includes('coverage unavailable'))).toHaveLength(2);
+ log.mockRestore();
+ });
+
+ it('reports unavailable when subscription storage cannot be read, including empty inventories', async () => {
+ await writeFile(join(tmp, 'sharing', 'peer_subscriptions.json'), 'invalid private JSON');
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov).toMatchObject({ available: false, partial: true, fullyMirrored: false, total: 0, pending: 0 });
+ expect(cov.failedReads).toEqual(PEER_SUBSCRIBABLE_KINDS.map(kind => ({ kind, operation: 'subscriptions' })));
+ expect(JSON.stringify(cov)).not.toContain('private');
});
it('counts a record with no subscription as pending (real ID diff, not cursors)', async () => {
@@ -1219,6 +1251,26 @@ describe('peerSync', () => {
expect(vi.mocked(peerFetch)).not.toHaveBeenCalled();
});
+ it('continues peer-online backfill after a kind inventory fails without logging private errors', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { instanceEvents } = await import('../instanceEvents.js');
+ const { installPeerSyncListener } = await import('./peerSync.js');
+ installPeerSyncListener();
+ vi.mocked(listUniverses).mockRejectedValue(new Error('private inventory details'));
+ vi.mocked(listSeries).mockResolvedValue([{ id: 's1' }]);
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ instanceEvents.emit('peer:online', {
+ instanceId: 'peer-a', enabled: true, syncEnabled: true,
+ directions: ['outbound'], syncCategories: { universe: true, pipeline: true },
+ });
+ await __drainForTests();
+ expect(await findPeerSubscription('peer-a', 'series', 's1')).not.toBeNull();
+ expect(log).toHaveBeenCalledWith('⚠️ peerSync: backfill inventory unavailable for universe/records');
+ expect(log.mock.calls.flat().join(' ')).not.toContain('private inventory details');
+ log.mockRestore();
+ });
+
it('converges from peer:online when the toggle fired before instanceId was known', async () => {
// Regression for the addPeer→toggle→probe ordering: addPeer creates
// a peer with instanceId=null. The user can flip syncCategories on