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 codex review: mixed-version compat + receiver version + UI refresh
Adam Eivye44865b54c3a
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 66b704ecfe..06a7b65218 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -836,7 +836,7 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {}let cancelled = false;setPeerSubsLoaded(false);- listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true })+ const refetch = () => listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true }).then((r) => {if (!cancelled) setPeerSubs(r?.subscriptions || []);})@@ -846,7 +846,22 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {.finally(() => {if (!cancelled) setPeerSubsLoaded(true);});- return () => { cancelled = true; };+ refetch();+ // When a per-record schema block is persisted server-side, the+ // subscription's `blockedBySchema` field changes inside+ // peer_subscriptions.json. The parent Instances component already+ // refetches `peers` on this event, but its refresh doesn't re-run this+ // card's `peerSubs` effect (deps are `peer.instanceId` only). Without+ // a local subscription here, SchemaGapBadge keeps rendering the stale+ // `blockedBySchema` value until a full page reload.+ const handleSchemaSubChange = () => { refetch(); };+ socket.on('peerSync:subscription-blocked', handleSchemaSubChange);+ socket.on('peerSync:subscription-unblocked', handleSchemaSubChange);+ return () => {+ cancelled = true;+ socket.off('peerSync:subscription-blocked', handleSchemaSubChange);+ socket.off('peerSync:subscription-unblocked', handleSchemaSubChange);+ };}, [peer.instanceId]);const StatusIcon = STATUS_ICONS[peer.status] || CircleDot;diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 568fe25810..5daa3d84e4 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -52,6 +52,7 @@ import {buildPortosMeta,compareSchemaVersions,formatVersionGap,+ getPortosVersion,} from '../../lib/schemaVersions.js';import { getInstanceId, getPeers, UNKNOWN_INSTANCE_ID } from '../instances.js';import { instanceEvents } from '../instanceEvents.js';@@ -672,17 +673,41 @@ export async function pushRecordToPeer(sub, options = {}) {// hook), so the timeout is enforced inline with an AbortController so a// hung peer can't keep the push promise pending forever and block subsequent// debounced pushes for the same sub.- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);- const res = await peerFetch(url, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload),- signal: controller.signal,- }).catch((err) => {- console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);- return null;- }).finally(() => clearTimeout(timeoutId));+ const postPayload = async (body) => {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);+ return peerFetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ signal: controller.signal,+ }).catch((err) => {+ console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);+ return null;+ }).finally(() => clearTimeout(timeoutId));+ };+ let res = await postPayload(payload);+ // MIXED-VERSION COMPAT: an older receiver's push schema is still `.strict()`+ // without a `portosMeta` field, so it 400-rejects our envelope at Zod+ // validation BEFORE its schema-version gate code (which doesn't exist on+ // that version anyway) can run. Detect that specific rejection — Zod emits+ // "Unrecognized key(s) in object: 'portosMeta'" — and retry once without+ // the envelope so the push lands on the older peer. The older peer can't+ // see schemaVersions, but until the user upgrades it that's the+ // best-effort behavior we want (vs. permanently stranded pushes). Once+ // they upgrade, the next push round naturally re-includes `portosMeta`.+ if (res && res.status === 400 && payload.portosMeta) {+ const errBody = await res.clone().json().catch(() => null);+ const details = Array.isArray(errBody?.context?.details) ? errBody.context.details : [];+ const mentionsMeta = details.some((d) => /portosMeta/.test(`${d?.path || ''} ${d?.message || ''}`));+ if (errBody?.code === 'VALIDATION_ERROR' && mentionsMeta) {+ console.log(+ `ℹ️ peerSync: ${peer.name || peer.instanceId} is on a pre-version-gate PortOS — retrying push without portosMeta envelope`,+ );+ const { portosMeta: _strip, ...legacyPayload } = payload;+ res = await postPayload(legacyPayload);+ }+ }// 409 with `code: SCHEMA_VERSION_AHEAD` means the receiver is on an OLDER// PortOS and can't parse our newer storage layout. Persist the gap on the// subscription so the Instances UI can surface "Peer X needs to update@@ -698,10 +723,15 @@ export async function pushRecordToPeer(sub, options = {}) {// (see server/routes/peerSync.js `mapAndRethrow`), so reach in two levels// to get the original payload from the peerSync service.const details = isPlainObject(body.context?.details) ? body.context.details : {};+ // `peerPortosVersion` describes the REJECTING peer's PortOS version+ // (what we want to show in the SchemaGapBadge), so read+ // `receiverPortosVersion` from the receiver-supplied details — NOT+ // `senderPortosVersion`, which is our own version round-tripped from+ // the payload we sent.await persistSchemaVersionBlock(sub.id, {ahead: Array.isArray(details.ahead) ? details.ahead : [],behind: Array.isArray(details.behind) ? details.behind : [],- peerPortosVersion: typeof details.senderPortosVersion === 'string' ? details.senderPortosVersion : null,+ peerPortosVersion: typeof details.receiverPortosVersion === 'string' ? details.receiverPortosVersion : null,peerSchemaVersions: isPlainObject(details.receiverSchemaVersions) ? details.receiverSchemaVersions : null,});console.warn(@@ -1069,6 +1099,11 @@ export async function applyIncomingPush(payload) {console.warn(`⚠️ peerSync: rejecting push from ${sourceInstanceId} — ${formatVersionGap(versionDiff)} (sender PortOS ${senderPortosVersion || 'unknown'})`,);+ // Surface the receiver's PortOS version so the sender can show the user+ // *which* version their peer is on (the label the user thinks of as "the+ // peer's PortOS version"). Without this field the sender's UI would fall+ // back to its own version, which is misleading.+ const receiverPortosVersion = await getPortosVersion().catch(() => null);throw makeErr(`sender's schema is ahead — receiver cannot apply (${formatVersionGap(versionDiff)})`,ERR_SCHEMA_VERSION_AHEAD,@@ -1076,6 +1111,7 @@ export async function applyIncomingPush(payload) {ahead: versionDiff.ahead,behind: versionDiff.behind,senderPortosVersion,+ receiverPortosVersion,receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS,},);diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 7135f5f5cf..e90bd246b8 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -1445,19 +1445,22 @@ describe('peerSync', () => {it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {// Local code is at universes:5 (see server/lib/schemaVersions.js).// A push from a sender on universes:6 must NOT touch local state.- await expect(applyIncomingPush({+ const rejection = await applyIncomingPush({kind: 'universe',record: { id: 'u1', name: 'Foo' },assetManifest: [],sourceInstanceId: 'peer-a',portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } },- })).rejects.toMatchObject({- code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',- details: {- ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],- senderPortosVersion: '99.0.0',- },- });+ }).catch((err) => err);+ expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);+ expect(rejection.details.senderPortosVersion).toBe('99.0.0');+ // Receiver MUST stamp its OWN PortOS version so the sender can show+ // the user "peer X is on PortOS vY" — without this, the sender would+ // fall back to its own version (the one it sent) and mislabel the+ // peer in the SchemaGapBadge.+ expect(typeof rejection.details.receiverPortosVersion).toBe('string');+ expect(rejection.details.receiverPortosVersion.length).toBeGreaterThan(0);// mergeUniversesFromSync MUST NOT have been called — the gate runs// before the merge dispatch.expect(mergeUniversesFromSync).not.toHaveBeenCalled();@@ -1524,6 +1527,8 @@ describe('peerSync', () => {it('records a blockedBySchema marker on the subscription when the peer responds 409', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });// Receiver claims it's on universes:4 + PortOS 2.5.0; sender is at 5.+ // `receiverPortosVersion` is the rejecting peer's version — that's+ // the label the sender persists as `peerPortosVersion`.vi.mocked(peerFetch).mockResolvedValue({ok: false,status: 409,@@ -1534,7 +1539,8 @@ describe('peerSync', () => {details: {ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }],behind: [],- senderPortosVersion: '2.5.0',+ senderPortosVersion: '3.0.0',+ receiverPortosVersion: '2.5.0',receiverSchemaVersions: { universes: 4 },},},@@ -1634,6 +1640,63 @@ describe('peerSync', () => {expect(cleared.blockedBySchema).toBeUndefined();expect(cleared.lastPushedHash).toBeTruthy(); // succeeded → hash recorded});++ it('falls back without portosMeta when the peer is on a pre-version-gate PortOS (strict schema 400)', async () => {+ // Pre-version-gate receiver: its `peerSyncPushSchema` is `.strict()`+ // and has no `portosMeta` field, so it rejects our envelope as a+ // generic VALIDATION_ERROR before any schema-gate logic. The sender+ // must detect that specific shape, strip portosMeta, and retry —+ // otherwise universe/series pushes to not-yet-upgraded peers fail+ // hard and silently during a federation rollout.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ const firstCallBody = { ok: false, status: 400, json: async () => ({+ code: 'VALIDATION_ERROR',+ message: 'Validation failed',+ context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'portosMeta'" }] },+ }) };+ firstCallBody.clone = () => firstCallBody;+ const retryBody = { ok: true, status: 200, json: async () => ({}) };+ vi.mocked(peerFetch)+ .mockResolvedValueOnce(firstCallBody)+ .mockResolvedValueOnce(retryBody);+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ const result = await pushRecordToPeer(sub);+ expect(result.pushed).toBe(true);+ // Two network calls: the failed validating one + the retry without portosMeta.+ const calls = vi.mocked(peerFetch).mock.calls;+ expect(calls.length).toBe(2);+ const firstPayload = JSON.parse(calls[0][1].body);+ const retryPayload = JSON.parse(calls[1][1].body);+ expect(firstPayload.portosMeta).toBeDefined();+ expect(retryPayload.portosMeta).toBeUndefined();+ // Record content is preserved across the retry.+ expect(retryPayload.record.id).toBe('u1');+ expect(retryPayload.sourceInstanceId).toBe(firstPayload.sourceInstanceId);+ });++ it('does NOT retry on a 400 whose validation error is unrelated to portosMeta', async () => {+ // The retry is keyed on the `portosMeta` mention in the validation+ // details — any other 400 (oversized field, unknown record key, etc.)+ // is a genuine bug we want to surface, not silently retry.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ const errBody = { ok: false, status: 400, json: async () => ({+ code: 'VALIDATION_ERROR',+ message: 'Validation failed',+ context: { details: [{ path: 'record.name', message: 'String too long' }] },+ }) };+ errBody.clone = () => errBody;+ vi.mocked(peerFetch).mockResolvedValueOnce(errBody);+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ const result = await pushRecordToPeer(sub);+ expect(result.pushed).toBe(false);+ expect(result.reason).toBe('http-400');+ // Only ONE call — no retry.+ expect(vi.mocked(peerFetch).mock.calls.length).toBe(1);+ });});});});