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: add Instances page for PortOS federation across Tailscale network

Adam Eivyd3caf06bddc8
diff --git a/.changelog/v0.23.x.md b/.changelog/v0.23.x.md
new file mode 100644
index 0000000000..227c7fde8c
--- /dev/null
+++ b/.changelog/v0.23.x.md
@@ -0,0 +1,18 @@
+# Release v0.23.x - Changelog
+
+Released: YYYY-MM-DD
+
+## Overview
+
+PortOS Federation — connect and monitor multiple PortOS instances across your Tailscale network.
+
+## Features
+
+### Instances page (Federation)
+- **Peer registration** — manually add other PortOS instances by Tailscale IP address
+- **Health monitoring** — automatic 30s polling shows memory, CPU, uptime, app count, and CoS agent status for each peer
+- **Self identity** — each instance auto-generates a unique ID and editable display name on first run
+- **Query proxy** — send arbitrary `/api/*` requests to remote peers from the local UI (Health, Apps, CoS Status presets included)
+- **Real-time updates** — Socket.IO subscription pushes peer status changes to the Instances page without polling the client
+- **Server-to-server architecture** — local server proxies all remote requests; clients never talk to peers directly (no CORS issues)
+- **Health endpoint enrichment** — `/api/health` and `/api/health/system` now include `hostname` and `instanceId` fields for peer identification
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 87b4f37b6b..40bac2f311 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -16,6 +16,7 @@ import Uploads from './pages/Uploads';
import Shell from './pages/Shell';
import BrowserPage from './pages/Browser';
import Jira from './pages/Jira';
+import Instances from './pages/Instances';
// Lazy load heavier pages for code splitting
// DevTools pages are large (~2300 lines total) so lazy load them
@@ -65,6 +66,7 @@ export default function App() {
<Route path="uploads" element={<Uploads />} />
<Route path="shell" element={<Shell />} />
<Route path="browser" element={<BrowserPage />} />
+ <Route path="instances" element={<Instances />} />
<Route path="jira" element={<Jira />} />
<Route path="city" element={<CyberCity />} />
<Route path="city/settings" element={<CyberCity />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 089fe1cfec..8e7d9f4827 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -34,7 +34,8 @@ import {
Globe,
Newspaper,
Building2,
- Ticket
+ Ticket,
+ Network
} from 'lucide-react';
import packageJson from '../../package.json';
import Logo from './Logo';
@@ -58,6 +59,7 @@ const navItems = [
]
},
{ to: '/apps', label: 'Apps', icon: Package, single: true },
+ { to: '/instances', label: 'Instances', icon: Network, single: true },
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
{ to: '/browser', label: 'Browser', icon: Globe, single: true },
{ to: '/jira', label: 'JIRA', icon: Ticket, single: true },
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
new file mode 100644
index 0000000000..00417415aa
--- /dev/null
+++ b/client/src/pages/Instances.jsx
@@ -0,0 +1,447 @@
+import { useState, useEffect, useCallback } from 'react';
+import {
+ Network, Plus, Trash2, RefreshCw, Edit3, Check, X,
+ Wifi, WifiOff, CircleDot, ChevronDown, ChevronRight,
+ Cpu, HardDrive, Activity, Bot, MonitorSmartphone, Search
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+import socket from '../services/socket';
+import {
+ getInstances, updateSelfInstance, addPeer, updatePeer,
+ removePeer, probePeer, queryPeer
+} from '../services/api';
+
+const STATUS_COLORS = {
+ online: 'text-port-success',
+ offline: 'text-port-error',
+ unknown: 'text-gray-500'
+};
+
+const STATUS_ICONS = {
+ online: Wifi,
+ offline: WifiOff,
+ unknown: CircleDot
+};
+
+const QUERY_PRESETS = [
+ { label: 'Health', path: '/api/health/system' },
+ { label: 'Apps', path: '/api/apps' },
+ { label: 'CoS Status', path: '/api/cos/status' },
+ { label: 'Processes', path: '/api/health' }
+];
+
+function formatBytes(bytes) {
+ if (!bytes) return '—';
+ const gb = bytes / (1024 * 1024 * 1024);
+ if (gb >= 1) return `${gb.toFixed(1)} GB`;
+ const mb = bytes / (1024 * 1024);
+ return `${Math.round(mb)} MB`;
+}
+
+function timeAgo(iso) {
+ if (!iso) return 'Never';
+ const diff = Date.now() - new Date(iso).getTime();
+ const secs = Math.floor(diff / 1000);
+ if (secs < 60) return `${secs}s ago`;
+ const mins = Math.floor(secs / 60);
+ if (mins < 60) return `${mins}m ago`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `${hrs}h ago`;
+ return `${Math.floor(hrs / 24)}d ago`;
+}
+
+function HealthSummary({ health }) {
+ if (!health) return <span className="text-gray-500 text-xs">No data</span>;
+ return (
+ <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
+ <div className="flex items-center gap-1.5 text-gray-400">
+ <HardDrive size={12} />
+ <span>Mem {health.system?.memory?.usagePercent ?? '?'}%</span>
+ </div>
+ <div className="flex items-center gap-1.5 text-gray-400">
+ <Cpu size={12} />
+ <span>CPU {health.system?.cpu?.usagePercent ?? '?'}%</span>
+ </div>
+ <div className="flex items-center gap-1.5 text-gray-400">
+ <Activity size={12} />
+ <span>Up {health.system?.uptimeFormatted ?? '?'}</span>
+ </div>
+ <div className="flex items-center gap-1.5 text-gray-400">
+ <MonitorSmartphone size={12} />
+ <span>{health.apps?.total ?? '?'} apps</span>
+ </div>
+ {health.cos && (
+ <div className="flex items-center gap-1.5 text-gray-400 col-span-2">
+ <Bot size={12} />
+ <span>{health.cos.activeAgents ?? 0} agents, {health.cos.queuedTasks ?? 0} queued</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SelfCard({ self, onUpdate }) {
+ const [editing, setEditing] = useState(false);
+ const [name, setName] = useState('');
+
+ const startEdit = () => {
+ setName(self?.name || '');
+ setEditing(true);
+ };
+
+ const saveName = async () => {
+ if (!name.trim()) return;
+ await updateSelfInstance({ name: name.trim() });
+ onUpdate();
+ setEditing(false);
+ toast.success('Instance name updated');
+ };
+
+ if (!self) return null;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">This Instance</h3>
+ <Network size={16} className="text-port-accent" />
+ </div>
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ {editing ? (
+ <div className="flex items-center gap-2 flex-1">
+ <input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && saveName()}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white focus:outline-none focus:border-port-accent"
+ autoFocus
+ />
+ <button onClick={saveName} className="text-port-success hover:text-port-success/80">
+ <Check size={16} />
+ </button>
+ <button onClick={() => setEditing(false)} className="text-gray-500 hover:text-white">
+ <X size={16} />
+ </button>
+ </div>
+ ) : (
+ <>
+ <span className="text-white font-semibold text-lg">{self.name}</span>
+ <button onClick={startEdit} className="text-gray-500 hover:text-white">
+ <Edit3 size={14} />
+ </button>
+ </>
+ )}
+ </div>
+ <p className="text-xs text-gray-500 font-mono">{self.instanceId}</p>
+ </div>
+ </div>
+ );
+}
+
+function AddPeerForm({ onAdd }) {
+ const [address, setAddress] = useState('');
+ const [port, setPort] = useState('5554');
+ const [name, setName] = useState('');
+ const [adding, setAdding] = useState(false);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ if (!address.trim()) return;
+ setAdding(true);
+ const data = { address: address.trim(), port: parseInt(port, 10) || 5554 };
+ if (name.trim()) data.name = name.trim();
+ await addPeer(data);
+ setAddress('');
+ setPort('5554');
+ setName('');
+ setAdding(false);
+ onAdd();
+ toast.success('Peer added');
+ };
+
+ return (
+ <form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-xl p-5">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3 flex items-center gap-2">
+ <Plus size={14} /> Add Peer
+ </h3>
+ <div className="flex flex-wrap gap-2">
+ <input
+ value={address}
+ onChange={e => setAddress(e.target.value)}
+ placeholder="100.64.x.x"
+ pattern="^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"
+ required
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent flex-1 min-w-[140px]"
+ />
+ <input
+ value={port}
+ onChange={e => setPort(e.target.value)}
+ placeholder="5554"
+ type="number"
+ min="1"
+ max="65535"
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent w-20"
+ />
+ <input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder="Name (optional)"
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent flex-1 min-w-[120px]"
+ />
+ <button
+ type="submit"
+ disabled={adding || !address.trim()}
+ className="bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium transition-colors"
+ >
+ {adding ? 'Adding...' : 'Add'}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+function QueryPanel({ peerId }) {
+ const [expanded, setExpanded] = useState(false);
+ const [selectedPreset, setSelectedPreset] = useState(0);
+ const [customPath, setCustomPath] = useState('');
+ const [result, setResult] = useState(null);
+ const [loading, setLoading] = useState(false);
+
+ const runQuery = async () => {
+ const path = customPath.trim() || QUERY_PRESETS[selectedPreset].path;
+ if (!path.startsWith('/api/')) {
+ toast.error('Path must start with /api/');
+ return;
+ }
+ setLoading(true);
+ setResult(null);
+ const data = await queryPeer(peerId, path).catch(err => ({ _error: err.message }));
+ setResult(data);
+ setLoading(false);
+ };
+
+ return (
+ <div className="mt-3 border-t border-port-border pt-3">
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-white transition-colors"
+ >
+ <Search size={12} />
+ <span>Query</span>
+ {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ </button>
+ {expanded && (
+ <div className="mt-2 space-y-2">
+ <div className="flex gap-2">
+ <select
+ value={selectedPreset}
+ onChange={e => { setSelectedPreset(Number(e.target.value)); setCustomPath(''); }}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent"
+ >
+ {QUERY_PRESETS.map((p, i) => (
+ <option key={i} value={i}>{p.label}</option>
+ ))}
+ </select>
+ <input
+ value={customPath}
+ onChange={e => setCustomPath(e.target.value)}
+ placeholder="or custom /api/..."
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
+ />
+ <button
+ onClick={runQuery}
+ disabled={loading}
+ className="bg-port-accent/20 hover:bg-port-accent/30 text-port-accent px-2 py-1 rounded text-xs transition-colors disabled:opacity-50"
+ >
+ {loading ? '...' : 'Run'}
+ </button>
+ </div>
+ {result && (
+ <pre className="bg-port-bg rounded p-2 text-xs text-gray-300 overflow-auto max-h-64 whitespace-pre-wrap">
+ {result._error
+ ? <span className="text-port-error">{result._error}</span>
+ : JSON.stringify(result, null, 2)
+ }
+ </pre>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PeerCard({ peer, onRefresh }) {
+ const [editingName, setEditingName] = useState(false);
+ const [name, setName] = useState('');
+ const [probing, setProbing] = useState(false);
+ const [confirmRemove, setConfirmRemove] = useState(false);
+
+ const StatusIcon = STATUS_ICONS[peer.status] || CircleDot;
+
+ const handleProbe = async () => {
+ setProbing(true);
+ await probePeer(peer.id);
+ onRefresh();
+ setProbing(false);
+ };
+
+ const handleRemove = async () => {
+ await removePeer(peer.id);
+ onRefresh();
+ toast.success('Peer removed');
+ };
+
+ const handleToggle = async () => {
+ await updatePeer(peer.id, { enabled: !peer.enabled });
+ onRefresh();
+ };
+
+ const saveName = async () => {
+ if (!name.trim()) return;
+ await updatePeer(peer.id, { name: name.trim() });
+ onRefresh();
+ setEditingName(false);
+ };
+
+ return (
+ <div className={`bg-port-card border border-port-border rounded-xl p-5 transition-opacity ${!peer.enabled ? 'opacity-50' : ''}`}>
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <StatusIcon size={16} className={STATUS_COLORS[peer.status]} />
+ {editingName ? (
+ <div className="flex items-center gap-1">
+ <input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && saveName()}
+ className="bg-port-bg border border-port-border rounded px-2 py-0.5 text-sm text-white focus:outline-none focus:border-port-accent w-32"
+ autoFocus
+ />
+ <button onClick={saveName} className="text-port-success hover:text-port-success/80"><Check size={14} /></button>
+ <button onClick={() => setEditingName(false)} className="text-gray-500 hover:text-white"><X size={14} /></button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5">
+ <span className="text-white font-medium">{peer.name}</span>
+ <button onClick={() => { setName(peer.name); setEditingName(true); }} className="text-gray-600 hover:text-white">
+ <Edit3 size={12} />
+ </button>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={handleProbe}
+ disabled={probing}
+ className="p-1.5 text-gray-500 hover:text-white transition-colors disabled:opacity-50"
+ title="Probe now"
+ >
+ <RefreshCw size={14} className={probing ? 'animate-spin' : ''} />
+ </button>
+ <button
+ onClick={handleToggle}
+ className={`p-1.5 transition-colors text-xs font-mono ${peer.enabled ? 'text-port-success hover:text-port-success/80' : 'text-gray-600 hover:text-white'}`}
+ title={peer.enabled ? 'Disable polling' : 'Enable polling'}
+ >
+ {peer.enabled ? 'ON' : 'OFF'}
+ </button>
+ {confirmRemove ? (
+ <div className="flex items-center gap-1">
+ <button onClick={handleRemove} className="text-port-error hover:text-port-error/80 text-xs">Yes</button>
+ <button onClick={() => setConfirmRemove(false)} className="text-gray-500 hover:text-white text-xs">No</button>
+ </div>
+ ) : (
+ <button
+ onClick={() => setConfirmRemove(true)}
+ className="p-1.5 text-gray-600 hover:text-port-error transition-colors"
+ title="Remove peer"
+ >
+ <Trash2 size={14} />
+ </button>
+ )}
+ </div>
+ </div>
+
+ <p className="text-xs text-gray-500 font-mono mb-3">{peer.address}:{peer.port}</p>
+
+ <HealthSummary health={peer.lastHealth} />
+
+ <div className="mt-2 text-xs text-gray-600">
+ Last seen: {timeAgo(peer.lastSeen)}
+ </div>
+
+ <QueryPanel peerId={peer.id} />
+ </div>
+ );
+}
+
+export default function Instances() {
+ const [self, setSelf] = useState(null);
+ const [peers, setPeers] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const fetchData = useCallback(async () => {
+ const data = await getInstances();
+ setSelf(data.self);
+ setPeers(data.peers);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+
+ socket.emit('instances:subscribe');
+ socket.on('instances:peers:updated', (updatedPeers) => {
+ setPeers(updatedPeers);
+ });
+
+ return () => {
+ socket.emit('instances:unsubscribe');
+ socket.off('instances:peers:updated');
+ };
+ }, [fetchData]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-gray-500">Loading instances...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center gap-3">
+ <Network size={24} className="text-port-accent" />
+ <h1 className="text-2xl font-bold text-white">Instances</h1>
+ <span className="text-sm text-gray-500">PortOS Federation</span>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <SelfCard self={self} onUpdate={fetchData} />
+ <AddPeerForm onAdd={fetchData} />
+ </div>
+
+ {peers.length > 0 && (
+ <div>
+ <h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
+ Peers ({peers.length})
+ </h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
+ {peers.map(peer => (
+ <PeerCard key={peer.id} peer={peer} onRefresh={fetchData} />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {peers.length === 0 && (
+ <div className="text-center py-12 text-gray-500">
+ <Network size={48} className="mx-auto mb-4 opacity-30" />
+ <p>No peers registered yet.</p>
+ <p className="text-sm mt-1">Add a Tailscale IP address to connect to another PortOS instance.</p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 8e7aeb3c47..ddf9e22c44 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1226,6 +1226,16 @@ export const navigateBrowser = (url) => request('/browser/navigate', {
body: JSON.stringify({ url })
});
+// Instances (Federation)
+export const getInstances = () => request('/instances');
+export const getSelfInstance = () => request('/instances/self');
+export const updateSelfInstance = (data) => request('/instances/self', { method: 'PUT', body: JSON.stringify(data) });
+export const addPeer = (data) => request('/instances/peers', { method: 'POST', body: JSON.stringify(data) });
+export const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });
+export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'DELETE' });
+export const probePeer = (id) => request(`/instances/peers/${id}/probe`, { method: 'POST' });
+export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/package-lock.json b/package-lock.json
index ca8431b3dd..a85bda3a65 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "0.22.2",
+ "version": "0.23.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "0.22.2",
+ "version": "0.23.0",
"license": "MIT",
"workspaces": [
"packages/*",
@@ -29,7 +29,7 @@
},
"client": {
"name": "portos-client",
- "version": "0.22.2",
+ "version": "0.22.1",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
@@ -9268,7 +9268,7 @@
},
"server": {
"name": "portos-server",
- "version": "0.22.2",
+ "version": "0.22.1",
"dependencies": {
"axios": "^1.7.9",
"cors": "^2.8.5",
diff --git a/package.json b/package.json
index d5ece5c40f..36507c0c04 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "0.22.2",
+ "version": "0.23.0",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/index.js b/server/index.js
index 37ee2a9d9b..cab932980a 100644
--- a/server/index.js
+++ b/server/index.js
@@ -40,6 +40,8 @@ import moltworldToolsRoutes from './routes/moltworldTools.js';
import moltworldWsRoutes from './routes/moltworldWs.js';
import jiraRoutes from './routes/jira.js';
import autobiographyRoutes from './routes/autobiography.js';
+import instancesRoutes from './routes/instances.js';
+import { ensureSelf, startPolling } from './services/instances.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
@@ -208,6 +210,7 @@ app.use('/api/digital-twin', digitalTwinRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
app.use('/api/browser', browserRoutes);
app.use('/api/jira', jiraRoutes);
+app.use('/api/instances', instancesRoutes);
// Initialize script runner
initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
@@ -236,4 +239,7 @@ httpServer.listen(PORT, HOST, () => {
// Set up process error handlers with io instance
setupProcessErrorHandlers(io);
+
+ // Initialize instance identity and start peer polling
+ ensureSelf().then(() => startPolling()).catch(err => console.error(`❌ Instance init failed: ${err.message}`));
});
diff --git a/server/routes/health.js b/server/routes/health.js
index 2d882c0ff1..9e5246ee1b 100644
--- a/server/routes/health.js
+++ b/server/routes/health.js
@@ -3,16 +3,20 @@ import os from 'os';
import { listProcesses } from '../services/pm2.js';
import * as apps from '../services/apps.js';
import * as cos from '../services/cos.js';
+import { getSelf } from '../services/instances.js';
const router = Router();
-router.get('/health', (req, res) => {
+router.get('/health', async (req, res) => {
console.log('💓 GET /api/health');
+ const self = await getSelf().catch(() => null);
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
- version: '0.1.0'
+ version: '0.1.0',
+ hostname: os.hostname(),
+ instanceId: self?.instanceId ?? null
});
});
@@ -24,10 +28,11 @@ router.get('/health/system', async (req, res) => {
const startTime = Date.now();
// Gather data in parallel
- const [pm2Processes, allApps, cosStatus] = await Promise.all([
+ const [pm2Processes, allApps, cosStatus, self] = await Promise.all([
listProcesses().catch(() => []),
apps.getAllApps({ includeArchived: false }).catch(() => []),
- cos.getStatus().catch(() => null)
+ cos.getStatus().catch(() => null),
+ getSelf().catch(() => null)
]);
// System metrics
@@ -120,6 +125,8 @@ router.get('/health/system', async (req, res) => {
res.json({
timestamp: new Date().toISOString(),
+ hostname: os.hostname(),
+ instanceId: self?.instanceId ?? null,
overallHealth,
warnings,
system: {
diff --git a/server/routes/instances.js b/server/routes/instances.js
new file mode 100644
index 0000000000..8d05759941
--- /dev/null
+++ b/server/routes/instances.js
@@ -0,0 +1,93 @@
+/**
+ * Instances API Routes
+ *
+ * Federation endpoints for managing PortOS peer instances.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import * as instances from '../services/instances.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+
+const router = Router();
+
+// Validation schemas
+const addPeerSchema = z.object({
+ address: z.string().regex(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, 'Must be a valid IP address'),
+ port: z.number().int().min(1).max(65535).default(5554),
+ name: z.string().optional()
+});
+
+const updatePeerSchema = z.object({
+ name: z.string().optional(),
+ enabled: z.boolean().optional()
+});
+
+const querySchema = z.object({
+ path: z.string().startsWith('/api/', 'Path must start with /api/')
+});
+
+// GET /api/instances — list self + all peers
+router.get('/', asyncHandler(async (req, res) => {
+ const self = await instances.getSelf();
+ const peers = await instances.getPeers();
+ res.json({ self, peers });
+}));
+
+// GET /api/instances/self — get this instance's identity
+router.get('/self', asyncHandler(async (req, res) => {
+ const self = await instances.getSelf();
+ res.json(self);
+}));
+
+// PUT /api/instances/self — update display name
+router.put('/self', asyncHandler(async (req, res) => {
+ const { name } = req.body;
+ if (!name || typeof name !== 'string') {
+ throw new ServerError('Name is required', { status: 400 });
+ }
+ const updated = await instances.updateSelf(name.trim());
+ if (!updated) throw new ServerError('Self identity not initialized', { status: 500 });
+ res.json(updated);
+}));
+
+// POST /api/instances/peers — add a peer
+router.post('/peers', asyncHandler(async (req, res) => {
+ const data = addPeerSchema.parse(req.body);
+ const peer = await instances.addPeer(data);
+ res.status(201).json(peer);
+}));
+
+// PUT /api/instances/peers/:id — update peer
+router.put('/peers/:id', asyncHandler(async (req, res) => {
+ const data = updatePeerSchema.parse(req.body);
+ const peer = await instances.updatePeer(req.params.id, data);
+ if (!peer) throw new ServerError('Peer not found', { status: 404 });
+ res.json(peer);
+}));
+
+// DELETE /api/instances/peers/:id — remove peer
+router.delete('/peers/:id', asyncHandler(async (req, res) => {
+ const removed = await instances.removePeer(req.params.id);
+ if (!removed) throw new ServerError('Peer not found', { status: 404 });
+ res.json({ success: true });
+}));
+
+// POST /api/instances/peers/:id/probe — force immediate probe
+router.post('/peers/:id/probe', 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 result = await instances.probePeer(peer);
+ res.json(result);
+}));
+
+// GET /api/instances/peers/:id/query — proxy GET to peer
+router.get('/peers/:id/query', asyncHandler(async (req, res) => {
+ const { path } = querySchema.parse(req.query);
+ const result = await instances.queryPeer(req.params.id, path);
+ if (result.error) throw new ServerError(result.error, { status: 502 });
+ res.json(result.data);
+}));
+
+export default router;
diff --git a/server/services/instanceEvents.js b/server/services/instanceEvents.js
new file mode 100644
index 0000000000..f8866bec6a
--- /dev/null
+++ b/server/services/instanceEvents.js
@@ -0,0 +1,3 @@
+import { EventEmitter } from 'events';
+
+export const instanceEvents = new EventEmitter();
diff --git a/server/services/instances.js b/server/services/instances.js
new file mode 100644
index 0000000000..09269e30f0
--- /dev/null
+++ b/server/services/instances.js
@@ -0,0 +1,213 @@
+/**
+ * Instances Service
+ *
+ * Manages PortOS federation — self identity, peer registration, health probing, and query proxying.
+ * Data persists to data/instances.json.
+ */
+
+import { writeFile } from 'fs/promises';
+import os from 'os';
+import crypto from 'crypto';
+import { dataPath, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+import { instanceEvents } from './instanceEvents.js';
+
+const INSTANCES_FILE = dataPath('instances.json');
+const PROBE_TIMEOUT_MS = 5000;
+const POLL_INTERVAL_MS = 30000;
+
+const withLock = createMutex();
+let pollTimer = null;
+
+// Default data shape
+const DEFAULT_DATA = {
+ self: null,
+ peers: []
+};
+
+// --- File I/O ---
+
+async function loadData() {
+ return await readJSONFile(INSTANCES_FILE, DEFAULT_DATA);
+}
+
+async function saveData(data) {
+ await ensureDir(PATHS.data);
+ const tmp = `${INSTANCES_FILE}.tmp`;
+ await writeFile(tmp, JSON.stringify(data, null, 2));
+ const { rename } = await import('fs/promises');
+ await rename(tmp, INSTANCES_FILE);
+}
+
+async function withData(fn) {
+ return withLock(async () => {
+ const data = await loadData();
+ const result = await fn(data);
+ await saveData(data);
+ return result;
+ });
+}
+
+// --- Self Identity ---
+
+export async function ensureSelf() {
+ return withData(async (data) => {
+ if (!data.self) {
+ data.self = {
+ instanceId: crypto.randomUUID(),
+ name: os.hostname()
+ };
+ console.log(`🌐 Instance identity created: ${data.self.name} (${data.self.instanceId})`);
+ }
+ return data.self;
+ });
+}
+
+export async function getSelf() {
+ const data = await loadData();
+ return data.self;
+}
+
+export async function updateSelf(name) {
+ return withData(async (data) => {
+ if (!data.self) return null;
+ data.self.name = name;
+ console.log(`🌐 Instance name updated: ${name}`);
+ return data.self;
+ });
+}
+
+// --- Peer CRUD ---
+
+export async function getPeers() {
+ const data = await loadData();
+ return data.peers;
+}
+
+export async function addPeer({ address, port = 5554, name }) {
+ return withData(async (data) => {
+ const peer = {
+ id: crypto.randomUUID(),
+ address,
+ port,
+ name: name || address,
+ 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})`);
+ instanceEvents.emit('peers:updated', data.peers);
+ return peer;
+ });
+}
+
+export async function removePeer(id) {
+ return withData(async (data) => {
+ const idx = data.peers.findIndex(p => p.id === id);
+ if (idx === -1) return null;
+ const [removed] = data.peers.splice(idx, 1);
+ console.log(`🌐 Peer removed: ${removed.name}`);
+ instanceEvents.emit('peers:updated', data.peers);
+ return removed;
+ });
+}
+
+export async function updatePeer(id, updates) {
+ return withData(async (data) => {
+ const peer = data.peers.find(p => p.id === id);
+ if (!peer) return null;
+ if (updates.name !== undefined) peer.name = updates.name;
+ if (updates.enabled !== undefined) peer.enabled = updates.enabled;
+ instanceEvents.emit('peers:updated', data.peers);
+ return peer;
+ });
+}
+
+// --- Probing ---
+
+export async function probePeer(peer) {
+ const url = `http://${peer.address}:${peer.port}/api/health/system`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+
+ let status, lastHealth, lastSeen;
+ try {
+ const res = await fetch(url, { signal: controller.signal });
+ const json = await res.json();
+ status = 'online';
+ lastHealth = json;
+ lastSeen = new Date().toISOString();
+ } catch {
+ status = 'offline';
+ lastHealth = peer.lastHealth; // preserve last known
+ lastSeen = peer.lastSeen;
+ } finally {
+ 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;
+ });
+}
+
+export async function probeAllPeers() {
+ const data = await loadData();
+ const enabled = data.peers.filter(p => p.enabled);
+ if (enabled.length === 0) return;
+
+ await Promise.allSettled(enabled.map(p => probePeer(p)));
+
+ // Re-read to get updated state and emit
+ const updated = await loadData();
+ instanceEvents.emit('peers:updated', updated.peers);
+}
+
+// --- Query Proxy ---
+
+export async function queryPeer(id, apiPath) {
+ const data = await loadData();
+ const peer = data.peers.find(p => p.id === id);
+ if (!peer) return { error: 'Peer not found' };
+
+ const url = `http://${peer.address}:${peer.port}${apiPath}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+
+ try {
+ const res = await fetch(url, { signal: controller.signal });
+ const json = await res.json();
+ return { success: true, data: json };
+ } catch (err) {
+ return { error: `Failed to query peer: ${err.message}` };
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+// --- Polling ---
+
+export function startPolling() {
+ if (pollTimer) return;
+ console.log(`🌐 Instance polling started (${POLL_INTERVAL_MS / 1000}s interval)`);
+
+ // Initial probe after a short delay
+ setTimeout(() => probeAllPeers(), 2000);
+
+ pollTimer = setInterval(() => probeAllPeers(), POLL_INTERVAL_MS);
+}
+
+export function stopPolling() {
+ if (pollTimer) {
+ clearInterval(pollTimer);
+ pollTimer = null;
+ console.log('🌐 Instance polling stopped');
+ }
+}
diff --git a/server/services/socket.js b/server/services/socket.js
index 4bbfab8fe5..525e9f3ca7 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -14,6 +14,7 @@ import { activityEvents } from './agentActivity.js';
import { brainEvents } from './brainStorage.js';
import { moltworldWsEvents } from './moltworldWs.js';
import { queueEvents } from './moltworldQueue.js';
+import { instanceEvents } from './instanceEvents.js';
import * as shellService from './shell.js';
import {
validateSocketData,
@@ -36,6 +37,8 @@ const errorSubscribers = new Set();
const notificationSubscribers = new Set();
// Store agent subscribers
const agentSubscribers = new Set();
+// Store instance subscribers
+const instanceSubscribers = new Set();
// Store io instance for broadcasting
let ioInstance = null;
@@ -238,6 +241,17 @@ export function initSocket(io) {
socket.emit('agents:unsubscribed');
});
+ // Instance subscriptions
+ socket.on('instances:subscribe', () => {
+ instanceSubscribers.add(socket);
+ socket.emit('instances:subscribed');
+ });
+
+ socket.on('instances:unsubscribe', () => {
+ instanceSubscribers.delete(socket);
+ socket.emit('instances:unsubscribed');
+ });
+
// Handle error recovery requests (can trigger auto-fix agents)
socket.on('error:recover', async (rawData) => {
const data = validateSocketData(errorRecoverSchema, rawData, socket, 'error:recover');
@@ -295,6 +309,7 @@ export function initSocket(io) {
errorSubscribers.delete(socket);
notificationSubscribers.delete(socket);
agentSubscribers.delete(socket);
+ instanceSubscribers.delete(socket);
// Clean up any shell sessions for this socket
const shellsClosed = shellService.cleanupSocketSessions(socket);
if (shellsClosed > 0) {
@@ -332,6 +347,9 @@ export function initSocket(io) {
// Set up Moltworld queue event forwarding
setupMoltworldQueueEventForwarding();
+
+ // Set up instance event forwarding
+ setupInstanceEventForwarding();
}
function cleanupStream(socketId) {
@@ -500,3 +518,15 @@ function setupMoltworldQueueEventForwarding() {
queueEvents.on('updated', (data) => broadcastToAgents('moltworld:queue:updated', data));
queueEvents.on('removed', (data) => broadcastToAgents('moltworld:queue:removed', data));
}
+
+// Broadcast to instance subscribers only
+function broadcastToInstances(event, data) {
+ for (const socket of instanceSubscribers) {
+ socket.emit(event, data);
+ }
+}
+
+// Set up instance event forwarding
+function setupInstanceEventForwarding() {
+ instanceEvents.on('peers:updated', (data) => broadcastToInstances('instances:peers:updated', data));
+}