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

feat: bidirectional peer registration via announce endpoint

Adam Eivy97da8f7a5ee1
diff --git a/.changelog/v0.24.x.md b/.changelog/v0.24.x.md
new file mode 100644
index 0000000000..ccb1316e30
--- /dev/null
+++ b/.changelog/v0.24.x.md
@@ -0,0 +1,16 @@
+# Release v0.24.x - Changelog
+
+Released: YYYY-MM-DD
+
+## Overview
+
+Bidirectional peer registration — adding a peer on one instance now automatically registers the connection on both sides.
+
+## Features
+
+### Bidirectional peer discovery
+- **Announce-on-add** — when you add a peer, your instance announces itself to the remote so both sides know about each other
+- **Announce-on-probe** — every 30s health probe re-announces to the remote, keeping both sides in sync even after restarts
+- **Deduplication** — peers are matched by `instanceId` (primary) or `address:port` (fallback) to prevent duplicate entries
+- **New endpoint** `POST /api/instances/peers/announce` — receives peer announcements with Zod-validated `instanceId`, `port`, and optional `name`
+- **instanceId tracking** — peer records now store the remote's `instanceId` from health responses for reliable identity matching
diff --git a/package-lock.json b/package-lock.json
index e7e639dd95..7afb24f0d2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "0.23.2",
+ "version": "0.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "0.23.2",
+ "version": "0.24.0",
"license": "MIT",
"workspaces": [
"packages/*",
diff --git a/package.json b/package.json
index 55db4fdeb9..35d636c021 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "0.23.2",
+ "version": "0.24.0",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/routes/instances.js b/server/routes/instances.js
index a711ead895..371d0431b0 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -23,6 +23,12 @@ const updatePeerSchema = z.object({
enabled: z.boolean().optional()
});
+const announceSchema = z.object({
+ port: z.number().int().min(1).max(65535),
+ instanceId: z.string().uuid(),
+ name: z.string().optional()
+});
+
const querySchema = z.object({
path: z.string().startsWith('/api/', 'Path must start with /api/')
});
@@ -51,6 +57,27 @@ router.put('/self', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// POST /api/instances/peers/announce — receive announcement from remote peer
+router.post('/peers/announce', asyncHandler(async (req, res) => {
+ const data = announceSchema.parse(req.body);
+ // Derive caller IP from req.ip, stripping ::ffff: prefix for IPv4-mapped addresses
+ const address = req.ip?.replace(/^::ffff:/, '') ?? req.socket.remoteAddress?.replace(/^::ffff:/, '');
+ if (!address) throw new ServerError('Could not determine caller IP', { status: 400 });
+
+ const result = await instances.handleAnnounce({
+ address,
+ port: data.port,
+ instanceId: data.instanceId,
+ name: data.name
+ });
+
+ const self = await instances.getSelf();
+ res.status(result.created ? 201 : 200).json({
+ self: { instanceId: self?.instanceId, name: self?.name },
+ peer: result.peer
+ });
+}));
+
// POST /api/instances/peers — add a peer
router.post('/peers', asyncHandler(async (req, res) => {
const data = addPeerSchema.parse(req.body);
diff --git a/server/services/instances.js b/server/services/instances.js
index f59ad8acf4..ea6deac49c 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -85,23 +85,27 @@ export async function getPeers() {
}
export async function addPeer({ address, port = 5554, name }) {
- return withData(async (data) => {
- const peer = {
+ const peer = await withData(async (data) => {
+ const entry = {
id: crypto.randomUUID(),
address,
port,
name: name || address,
+ instanceId: null,
addedAt: new Date().toISOString(),
lastSeen: null,
lastHealth: null,
status: 'unknown',
enabled: true
};
- data.peers.push(peer);
- console.log(`🌐 Peer added: ${peer.name} (${peer.address}:${peer.port})`);
+ data.peers.push(entry);
+ console.log(`🌐 Peer added: ${entry.name} (${entry.address}:${entry.port})`);
instanceEvents.emit('peers:updated', data.peers);
- return peer;
+ return entry;
});
+ // Announce ourselves to the remote peer (fire-and-forget)
+ announceSelf(peer.address, peer.port);
+ return peer;
}
export async function removePeer(id) {
@@ -133,7 +137,7 @@ export async function probePeer(peer) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
- let status, lastHealth, lastSeen;
+ let status, lastHealth, lastSeen, remoteInstanceId;
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -141,6 +145,7 @@ export async function probePeer(peer) {
status = 'online';
lastHealth = json;
lastSeen = new Date().toISOString();
+ remoteInstanceId = json.instanceId ?? null;
} catch {
status = 'offline';
lastHealth = peer.lastHealth; // preserve last known
@@ -149,14 +154,22 @@ export async function probePeer(peer) {
clearTimeout(timeout);
}
- return withData(async (data) => {
- const stored = data.peers.find(p => p.id === peer.id);
- if (!stored) return null;
- stored.status = status;
- stored.lastSeen = lastSeen;
- stored.lastHealth = lastHealth;
- return stored;
+ const stored = await withData(async (data) => {
+ const entry = data.peers.find(p => p.id === peer.id);
+ if (!entry) return null;
+ entry.status = status;
+ entry.lastSeen = lastSeen;
+ entry.lastHealth = lastHealth;
+ if (remoteInstanceId) entry.instanceId = remoteInstanceId;
+ return entry;
});
+
+ // Announce ourselves on successful probe (fire-and-forget)
+ if (status === 'online') {
+ announceSelf(peer.address, peer.port);
+ }
+
+ return stored;
}
export async function probeAllPeers() {
@@ -193,6 +206,74 @@ export async function queryPeer(id, apiPath) {
}
}
+// --- Announce (Bidirectional Registration) ---
+
+export async function handleAnnounce({ address, port, instanceId, name }) {
+ return withData(async (data) => {
+ // Check for existing peer by instanceId
+ let existing = data.peers.find(p => p.instanceId === instanceId);
+ // Fallback: check by address + port
+ if (!existing) {
+ existing = data.peers.find(p => p.address === address && p.port === port);
+ }
+
+ if (existing) {
+ existing.lastSeen = new Date().toISOString();
+ existing.status = 'online';
+ existing.instanceId = instanceId;
+ if (name) existing.name = name;
+ console.log(`🌐 Peer announced (existing): ${existing.name} (${address}:${port})`);
+ instanceEvents.emit('peers:updated', data.peers);
+ return { created: false, peer: existing };
+ }
+
+ // Create new peer entry
+ const peer = {
+ id: crypto.randomUUID(),
+ address,
+ port,
+ name: name || address,
+ instanceId,
+ addedAt: new Date().toISOString(),
+ lastSeen: new Date().toISOString(),
+ lastHealth: null,
+ status: 'online',
+ enabled: true
+ };
+ data.peers.push(peer);
+ console.log(`🌐 Peer announced (new): ${peer.name} (${address}:${port})`);
+ instanceEvents.emit('peers:updated', data.peers);
+ return { created: true, peer };
+ });
+}
+
+async function announceSelf(address, port) {
+ const data = await loadData();
+ if (!data.self) return;
+
+ const selfPort = parseInt(process.env.PORT, 10) || 5554;
+ const url = `http://${address}:${port}/api/instances/peers/announce`;
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+ try {
+ await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ port: selfPort,
+ instanceId: data.self.instanceId,
+ name: data.self.name
+ }),
+ signal: controller.signal
+ });
+ } catch {
+ // Fire-and-forget — peer may be offline or not running PortOS
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
// --- Polling ---
export function startPolling() {