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

address Copilot review: doc/code parity + plain-object guards + scoped event refetch

Adam Eivy97354af76855
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 06a7b65218..72cdb59869 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -854,7 +854,12 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
// 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(); };
+ // The event carries `peerId` so only the affected card refetches —
+ // every card listens, but skips events for other peers.
+ const handleSchemaSubChange = (payload) => {
+ if (payload?.peerId && payload.peerId !== peer.instanceId) return;
+ refetch();
+ };
socket.on('peerSync:subscription-blocked', handleSchemaSubChange);
socket.on('peerSync:subscription-unblocked', handleSchemaSubChange);
return () => {
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index 8ac6ac1959..be27f5ca9a 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -52,7 +52,9 @@ router.post('/:category/apply', asyncHandler(async (req, res) => {
throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });
}
const { data, portosMeta } = parsed.data;
- if (!data) throw new ServerError('Missing data field', { status: 400 });
+ // `z.unknown()` accepts falsy-but-present payloads (0, false, ''); only
+ // reject genuinely missing/null so we don't 400 a valid empty-ish snapshot.
+ if (data == null) throw new ServerError('Missing data field', { status: 400 });
const result = await dataSync.applyRemote(category, data, { portosMeta });
res.json(result);
}));
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index f7ce266afa..add874b134 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -39,6 +39,7 @@ import { adoptImportedSubscription, withReexportSuppressed } from './subscriptio
import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { mergePeerAnnotations } from '../mediaAnnotations.js';
import { isStr } from '../../lib/storyBible.js';
+import { isPlainObject } from '../../lib/objects.js';
function isSelfAuthored(senderInstanceId, localInstanceId) {
return !!localInstanceId
@@ -729,12 +730,12 @@ export async function processManifest(bucketId, manifestFilename) {
// PORTOS SCHEMA-VERSION GATE — even when the share-protocol schemaVersion
// is compatible, the manifest's per-category storage layout versions
// (`portosSchemaVersions`, e.g. `{ universes: 5 }`) may exceed what this
- // PortOS can apply. Reject without marking processed so a later upgrade
- // naturally re-imports (the watcher re-fires; the cursor still
- // dedups via `hasBeenProcessed` until the upgrade lands and the comparator
- // passes). Emits a `portos-schema-ahead` event the UI uses to render a
- // persistent "Update PortOS to import this share" badge.
- const senderSchemaVersions = manifest.portosSchemaVersions && typeof manifest.portosSchemaVersions === 'object'
+ // PortOS can apply. We refuse the import AND mark it processed (see the
+ // dedup rationale in the branch below) — so retry-after-upgrade is NOT
+ // automatic; the user clears the bucket cursor (or unshare/reshares) once
+ // they've upgraded. Emits a `portos-schema-ahead` event the UI uses to
+ // render a persistent "Update PortOS to import this share" badge.
+ const senderSchemaVersions = isPlainObject(manifest.portosSchemaVersions)
? manifest.portosSchemaVersions
: {};
const portosDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 53354b7ef8..e1d37a6a1e 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -18,6 +18,7 @@ import { randomUUID } from 'crypto';
import { join } from 'path';
import { readdir, rename } from 'fs/promises';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
+import { isPlainObject } from '../../lib/objects.js';
import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';
import { isStr } from '../../lib/storyBible.js';
import { universeCollectionNameFor, seriesCollectionNameFor } from '../mediaCollections.js';
@@ -159,7 +160,12 @@ export function buildManifest({
// ahead — the user is told to upgrade PortOS before the import can
// proceed. Optional on the wire so legacy manifests (no field) still
// validate; absent treated as "no contract" by the comparator.
- portosSchemaVersions: portosSchemaVersions && typeof portosSchemaVersions === 'object'
+ // Plain-object only: `typeof === 'object'` alone would accept arrays, and
+ // `{ ...[] }` spreads into numeric keys, producing a malformed
+ // `{ "0": ... }` map the importer's comparator can't read. `isPlainObject`
+ // rejects arrays + null (the realistic junk); exotic inputs like a Date
+ // spread to a harmless `{}` the comparator treats as "no contract".
+ portosSchemaVersions: isPlainObject(portosSchemaVersions)
? { ...portosSchemaVersions }
: null,
createdAt: new Date().toISOString(),
diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.js
index 2bc3b44d85..0e208be8ff 100644
--- a/server/services/sharing/manifest.test.js
+++ b/server/services/sharing/manifest.test.js
@@ -63,6 +63,37 @@ describe('sharing/manifest', () => {
expect(() => manifest.buildManifest({ kind: 'bogus' })).toThrow(/invalid kind/);
});
+ it('buildManifest stores a plain portosSchemaVersions object', () => {
+ const m = manifest.buildManifest({
+ kind: 'series', source: 'me', bucketId: 'b1', bucketName: 'c',
+ recordIds: [], assetRefs: [],
+ portosSchemaVersions: { universes: 5 },
+ });
+ expect(m.portosSchemaVersions).toEqual({ universes: 5 });
+ });
+
+ it('buildManifest normalizes an array portosSchemaVersions to null', () => {
+ // `typeof === 'object'` alone accepts arrays; spreading one would produce
+ // `{ "0": ... }` numeric-keyed garbage the importer's comparator can't
+ // read. Arrays (the realistic junk) must collapse to null.
+ for (const bad of [[5], [{ universes: 5 }], []]) {
+ const m = manifest.buildManifest({
+ kind: 'series', source: 'me', bucketId: 'b1', bucketName: 'c',
+ recordIds: [], assetRefs: [],
+ portosSchemaVersions: bad,
+ });
+ expect(m.portosSchemaVersions).toBeNull();
+ }
+ });
+
+ it('buildManifest defaults portosSchemaVersions to null when omitted', () => {
+ const m = manifest.buildManifest({
+ kind: 'series', source: 'me', bucketId: 'b1', bucketName: 'c',
+ recordIds: [], assetRefs: [],
+ });
+ expect(m.portosSchemaVersions).toBeNull();
+ });
+
it('manifestFilename is sortable + slug-safe', () => {
const m = manifest.buildManifest({
kind: 'series',
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 5daa3d84e4..50b820b77d 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -811,10 +811,14 @@ async function persistPushSuccess(subId, hash) {
* PortOS version string for the user-visible message.
*/
async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersion, peerSchemaVersions }) {
+ // Capture peerId inside the lock so the emitted event carries it — lets each
+ // Instances PeerCard filter on its own peer instead of every card refetching.
+ let blockedPeerId = null;
await withStateLock(async () => {
const state = await readState();
const sub = state.subscriptions.find((s) => s.id === subId);
if (!sub) return;
+ blockedPeerId = sub.peerId || null;
const now = new Date().toISOString();
sub.blockedBySchema = {
detectedAt: now,
@@ -826,19 +830,21 @@ async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersi
sub.updatedAt = now;
await writeState(state);
});
- peerSyncEvents.emit('subscription-blocked', { subId });
+ peerSyncEvents.emit('subscription-blocked', { subId, peerId: blockedPeerId });
}
async function clearSchemaVersionBlock(subId) {
+ let clearedPeerId = null;
await withStateLock(async () => {
const state = await readState();
const sub = state.subscriptions.find((s) => s.id === subId);
if (!sub || !sub.blockedBySchema) return;
+ clearedPeerId = sub.peerId || null;
delete sub.blockedBySchema;
sub.updatedAt = new Date().toISOString();
await writeState(state);
});
- peerSyncEvents.emit('subscription-unblocked', { subId });
+ peerSyncEvents.emit('subscription-unblocked', { subId, peerId: clearedPeerId });
}
async function buildPushPayload(sub, sourceInstanceId) {