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

add interactive integration-flows doc to Dev Tools (/devtools/flows)

[._.]/ Adam Eivy91a926fc45eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 08f0a5e257..e2612f0ac8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Dev Tools
+
+- **New interactive Integration Flows doc at `/devtools/flows`.** A single-page visual map of how PortOS packages talk to each other: ~60 components (client pages, client services, routes & sockets, server services, server lib, data stores, external systems) laid out in columns, with 10 documented end-to-end flows — Create Image, Start a Story, Voice Command, CoS Agent Run, Scheduled Task, Start/Stop App (PM2), Shell Session, Run Backup, Peer Sync, and Self-Update. Clicking a flow dims everything else, draws its numbered hops with transport-coded edges (HTTP / SSE / Socket.IO / EventEmitter / process spawn / file+DB I/O), and annotates what's passed at each hop; clicking a node shows its file, role, and the flows it participates in. The renderer (`client/public/flows.html`, dependency-free) is driven entirely by `client/public/flows.json`, so new flows are documented by editing JSON — an integrity test (`client/src/lib/flowsDoc.test.js`) verifies every referenced node/transport resolves and every referenced source file still exists, so refactors can't silently rot the doc. Launchable from the Dev Tools sidebar, ⌘K ("Flows"), and voice nav; selected flow is deep-linkable via `?flow=`, and "Open full screen" opens the standalone doc in a new tab.
+
## Security
- **RSS feed fetches now pin the connection to the SSRF-vetted IP, closing a DNS-rebinding TOCTOU.** `feeds.js` previously resolved a feed hostname, verified it wasn't private, then made a *separate, unpinned* fetch — undici re-resolved at connect time, so an attacker's DNS could answer public during validation and private (home-network / cloud-metadata) at the actual connect. Feed fetches now route through the shared `safeUrlFetch` guard (the same one moodBoard/Pinterest uses since #1859): the hostname is resolved once and the connection is pinned to that exact vetted address, re-validated and re-pinned on every redirect hop. `safeUrlFetch` gained a strict `blockPrivate` mode so feeds keep their historical block-all-private posture (an arbitrary user-added feed URL still can't be aimed at the LAN) while gaining the pin, and a `throwOnUnsafe: false` option so the feeds path returns its existing friendly "Could not fetch feed" result instead of a bubbled 400 (#2046).
diff --git a/client/public/flows.html b/client/public/flows.html
new file mode 100644
index 0000000000..76fac39f11
--- /dev/null
+++ b/client/public/flows.html
@@ -0,0 +1,499 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>PortOS Integration Flows</title>
+<style>
+ :root {
+ --bg: #0f0f0f;
+ --card: #1a1a1a;
+ --border: #2a2a2a;
+ --accent: #3b82f6;
+ --success: #22c55e;
+ --warning: #f59e0b;
+ --error: #ef4444;
+ --text: #e5e7eb;
+ --muted: #9ca3af;
+ }
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+ html, body { height: 100%; }
+ /* The scroll containers below re-declare the body background because some
+ browsers paint composited scroll regions white when they inherit none. */
+ body {
+ background: var(--bg);
+ color: var(--text);
+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+ header {
+ display: flex;
+ align-items: baseline;
+ gap: 12px;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--border);
+ flex: none;
+ background: var(--bg);
+ color: var(--text);
+ }
+ header h1 { font-size: 16px; font-weight: 600; }
+ header .sub { color: var(--muted); font-size: 12px; }
+ body.embed header { display: none; }
+ #app { flex: 1; display: flex; min-height: 0; }
+
+ /* Sidebar */
+ #sidebar {
+ width: 300px;
+ flex: none;
+ border-right: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: var(--bg);
+ color: var(--text);
+ }
+ #flowList { overflow-y: auto; padding: 8px; flex: none; max-height: 45%; background: var(--bg); }
+ .cat { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; margin: 10px 6px 4px; }
+ .flow-btn {
+ display: block;
+ width: 100%;
+ text-align: left;
+ background: none;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ color: var(--text);
+ padding: 6px 8px;
+ cursor: pointer;
+ font: inherit;
+ }
+ .flow-btn:hover { background: var(--card); }
+ .flow-btn.active { background: var(--card); border-color: var(--accent); }
+ .flow-btn .n { color: var(--muted); font-size: 11px; }
+ #detail {
+ flex: 1;
+ overflow-y: auto;
+ border-top: 1px solid var(--border);
+ padding: 10px;
+ min-height: 0;
+ background: var(--bg);
+ }
+ #detail .desc { color: var(--muted); font-size: 12.5px; margin-bottom: 10px; }
+ #detail h2 { font-size: 14px; margin-bottom: 4px; }
+ .step {
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 7px 8px;
+ margin-bottom: 6px;
+ cursor: pointer;
+ background: var(--card);
+ }
+ .step.hl { border-color: var(--accent); }
+ .step .route { font-size: 12.5px; font-weight: 600; }
+ .step .route .num {
+ display: inline-block;
+ min-width: 18px;
+ height: 18px;
+ border-radius: 9px;
+ background: var(--accent);
+ color: #fff;
+ font-size: 11px;
+ line-height: 18px;
+ text-align: center;
+ margin-right: 6px;
+ }
+ .step .label { font-size: 12px; margin-top: 2px; }
+ .step .payload { color: var(--muted); font-size: 11.5px; margin-top: 2px; }
+ .chip {
+ display: inline-block;
+ font-size: 10px;
+ border-radius: 4px;
+ padding: 0 5px;
+ margin-left: 6px;
+ border: 1px solid;
+ vertical-align: 1px;
+ }
+ .node-info { font-size: 12.5px; }
+ .node-info .file { color: var(--muted); font-family: ui-monospace, monospace; font-size: 11px; word-break: break-all; margin: 4px 0 8px; }
+ .node-info ul { margin: 4px 0 0 16px; }
+ .node-info li a { color: var(--accent); cursor: pointer; text-decoration: none; }
+ #resetBtn {
+ margin: 8px;
+ flex: none;
+ background: var(--card);
+ border: 1px solid var(--border);
+ color: var(--text);
+ border-radius: 6px;
+ padding: 6px;
+ cursor: pointer;
+ font: inherit;
+ }
+ #resetBtn:hover { border-color: var(--accent); }
+ #mobileSelect { display: none; }
+
+ /* Diagram */
+ #diagramWrap { flex: 1; overflow: auto; position: relative; min-width: 0; background: var(--bg); }
+ #diagram { position: relative; }
+ #edges { position: absolute; inset: 0; }
+ .colhead {
+ position: absolute;
+ top: 8px;
+ color: var(--muted);
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ text-align: center;
+ }
+ .node {
+ position: absolute;
+ background: var(--card);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px 8px;
+ font-size: 12px;
+ cursor: pointer;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ transition: opacity 0.15s, border-color 0.15s;
+ }
+ .node:hover { border-color: var(--muted); }
+ .node.dim { opacity: 0.22; }
+ .node.hl { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
+ .node.selected { border-color: var(--warning); box-shadow: 0 0 0 1px var(--warning); }
+ path.edge { fill: none; opacity: 0.14; transition: opacity 0.15s; }
+ path.edge.hl { opacity: 1; }
+ path.edge.hidden { opacity: 0; }
+ path.edge.focus { stroke-width: 3; }
+ .badge { pointer-events: none; }
+ .badge circle { fill: var(--accent); }
+ .badge text { fill: #fff; font-size: 10px; font-weight: 700; text-anchor: middle; dominant-baseline: central; }
+
+ /* Legend */
+ #legend {
+ position: sticky;
+ left: 0;
+ bottom: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 14px;
+ padding: 6px 12px;
+ border-top: 1px solid var(--border);
+ background: var(--bg);
+ font-size: 11px;
+ color: var(--muted);
+ }
+ #legend svg { vertical-align: middle; margin-right: 4px; }
+ #err { padding: 24px; color: var(--error); }
+
+ @media (max-width: 700px) {
+ #app { flex-direction: column; }
+ #sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--border); max-height: 45%; }
+ #flowList, #resetBtn { display: none; }
+ #mobileSelect {
+ display: block;
+ margin: 8px;
+ background: var(--card);
+ color: var(--text);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 6px;
+ font: inherit;
+ }
+ #detail { border-top: none; }
+ }
+</style>
+</head>
+<body>
+<header>
+ <h1>PortOS Integration Flows</h1>
+ <span class="sub">click a flow to trace it across the system &middot; click a node for details &middot; Esc to reset</span>
+</header>
+<div id="app">
+ <div id="sidebar">
+ <select id="mobileSelect" aria-label="Select flow"></select>
+ <div id="flowList"></div>
+ <button id="resetBtn" type="button">Show all</button>
+ <div id="detail"></div>
+ </div>
+ <div id="diagramWrap">
+ <div id="diagram"></div>
+ <div id="legend"></div>
+ </div>
+</div>
+<script>
+(async () => {
+ const EMBED = new URLSearchParams(location.search).get('embed') === '1';
+ if (EMBED) document.body.classList.add('embed');
+
+ let data;
+ try {
+ const res = await fetch('/flows.json');
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ data = await res.json();
+ } catch (err) {
+ document.getElementById('app').innerHTML = `<div id="err">Failed to load /flows.json: ${err.message}</div>`;
+ return;
+ }
+
+ const nodesById = new Map(data.nodes.map((n) => [n.id, n]));
+ const transportsById = new Map(data.transports.map((t) => [t.id, t]));
+ const groupsSorted = [...data.groups].sort((a, b) => a.column - b.column);
+
+ // ---- layout ----
+ const COL_W = 200, COL_GAP = 56, NODE_H = 30, NODE_GAP = 12, TOP = 42, PAD = 16;
+ const colNodes = groupsSorted.map((g) => data.nodes.filter((n) => n.group === g.id));
+ const pos = new Map(); // id -> {x, y, w, h}
+ groupsSorted.forEach((g, ci) => {
+ const x = PAD + ci * (COL_W + COL_GAP);
+ colNodes[ci].forEach((n, ri) => {
+ pos.set(n.id, { x, y: TOP + ri * (NODE_H + NODE_GAP), w: COL_W, h: NODE_H });
+ });
+ });
+ const width = PAD * 2 + groupsSorted.length * COL_W + (groupsSorted.length - 1) * COL_GAP;
+ const height = TOP + Math.max(...colNodes.map((c) => c.length)) * (NODE_H + NODE_GAP) + PAD;
+
+ const diagram = document.getElementById('diagram');
+ diagram.style.width = width + 'px';
+ diagram.style.height = height + 'px';
+
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('id', 'edges');
+ svg.setAttribute('width', width);
+ svg.setAttribute('height', height);
+ diagram.appendChild(svg);
+
+ groupsSorted.forEach((g, ci) => {
+ const head = document.createElement('div');
+ head.className = 'colhead';
+ head.textContent = g.label;
+ head.style.left = (PAD + ci * (COL_W + COL_GAP)) + 'px';
+ head.style.width = COL_W + 'px';
+ diagram.appendChild(head);
+ });
+
+ const nodeEls = new Map();
+ for (const n of data.nodes) {
+ const p = pos.get(n.id);
+ const el = document.createElement('div');
+ el.className = 'node';
+ el.textContent = n.label;
+ el.title = n.file ? `${n.label} — ${n.file}` : n.label;
+ el.style.left = p.x + 'px';
+ el.style.top = p.y + 'px';
+ el.style.width = p.w + 'px';
+ el.style.height = p.h + 'px';
+ el.addEventListener('click', () => showNode(n.id));
+ diagram.appendChild(el);
+ nodeEls.set(n.id, el);
+ }
+
+ // ---- edges ----
+ // Deduplicate edges shared by multiple flows; curve parallel edges apart.
+ const edgeKey = (s) => `${s.from}|${s.to}|${s.transport}`;
+ const edges = new Map(); // key -> SVG path element
+ const pairCount = new Map();
+ const allSteps = data.flows.flatMap((f) => f.steps);
+ for (const s of allSteps) {
+ const key = edgeKey(s);
+ if (edges.has(key)) continue;
+ const pairKey = [s.from, s.to].sort().join('|');
+ const idx = pairCount.get(pairKey) || 0;
+ pairCount.set(pairKey, idx + 1);
+ const a = pos.get(s.from), b = pos.get(s.to);
+ const forward = a.x < b.x;
+ const x1 = forward ? a.x + a.w : a.x;
+ const x2 = forward ? b.x : b.x + b.w;
+ const y1 = a.y + a.h / 2, y2 = b.y + b.h / 2;
+ const bend = Math.max(36, Math.abs(x2 - x1) * 0.35) * (forward ? 1 : -1);
+ const lift = idx * 14 * (idx % 2 ? 1 : -1); // spread parallel edges
+ const d = `M ${x1} ${y1} C ${x1 + bend} ${y1 + lift}, ${x2 - bend} ${y2 + lift}, ${x2} ${y2}`;
+ const t = transportsById.get(s.transport);
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ path.setAttribute('d', d);
+ path.setAttribute('class', 'edge');
+ path.setAttribute('stroke', t.color);
+ path.setAttribute('stroke-width', '2');
+ if (t.dash) path.setAttribute('stroke-dasharray', t.dash);
+ svg.appendChild(path);
+ edges.set(key, path);
+ }
+
+ let badgeLayer = null;
+
+ // ---- legend ----
+ const legend = document.getElementById('legend');
+ legend.innerHTML = data.transports.map((t) =>
+ `<span><svg width="26" height="8"><line x1="0" y1="4" x2="26" y2="4" stroke="${t.color}" stroke-width="2"${t.dash ? ` stroke-dasharray="${t.dash}"` : ''}/></svg>${t.label}</span>`
+ ).join('');
+
+ // ---- sidebar flow list ----
+ const flowList = document.getElementById('flowList');
+ const mobileSelect = document.getElementById('mobileSelect');
+ const detail = document.getElementById('detail');
+ const DEFAULT_DETAIL = '<div class="desc">Select a flow to see each hop annotated with its transport and payload, or click any node to see what it is and which flows pass through it.</div>';
+ detail.innerHTML = DEFAULT_DETAIL;
+ const flowBtns = [];
+ const categories = [...new Set(data.flows.map((f) => f.category))];
+ mobileSelect.innerHTML = '<option value="">Overview (all flows)</option>';
+ for (const cat of categories) {
+ const h = document.createElement('div');
+ h.className = 'cat';
+ h.textContent = cat;
+ flowList.appendChild(h);
+ const og = document.createElement('optgroup');
+ og.label = cat;
+ for (const f of data.flows.filter((x) => x.category === cat)) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'flow-btn';
+ btn.dataset.flow = f.id;
+ btn.innerHTML = `${f.label} <span class="n">· ${f.steps.length} hops</span>`;
+ btn.addEventListener('click', () => selectFlow(f.id));
+ flowList.appendChild(btn);
+ flowBtns.push(btn);
+ const opt = document.createElement('option');
+ opt.value = f.id;
+ opt.textContent = f.label;
+ og.appendChild(opt);
+ }
+ mobileSelect.appendChild(og);
+ }
+ mobileSelect.addEventListener('change', () => selectFlow(mobileSelect.value || null));
+ document.getElementById('resetBtn').addEventListener('click', () => selectFlow(null));
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') selectFlow(null); });
+
+ // ---- selection ----
+ let activeFlowId = null;
+
+ function syncUrl(flowId) {
+ if (EMBED) {
+ // The host page's ?flow= param is the source of truth in embed mode.
+ if (window.parent !== window) {
+ window.parent.postMessage({ type: 'flows:select', flow: flowId }, location.origin);
+ }
+ return;
+ }
+ const params = new URLSearchParams(location.search);
+ if (flowId) params.set('flow', flowId); else params.delete('flow');
+ history.replaceState(null, '', `${location.pathname}${params.size ? '?' + params : ''}`);
+ }
+
+ function clearHighlights() {
+ for (const el of nodeEls.values()) el.classList.remove('dim', 'hl', 'selected');
+ for (const path of edges.values()) path.classList.remove('hl', 'hidden', 'focus');
+ if (badgeLayer) { badgeLayer.remove(); badgeLayer = null; }
+ }
+
+ function selectFlow(flowId, { fromUrl = false } = {}) {
+ activeFlowId = flowId;
+ clearHighlights();
+ flowBtns.forEach((b) => b.classList.toggle('active', b.dataset.flow === flowId));
+ mobileSelect.value = flowId || '';
+ if (!fromUrl) syncUrl(flowId);
+
+ const flow = data.flows.find((f) => f.id === flowId);
+ if (!flow) {
+ activeFlowId = null;
+ detail.innerHTML = DEFAULT_DETAIL;
+ return;
+ }
+
+ const usedNodes = new Set(flow.steps.flatMap((s) => [s.from, s.to]));
+ const usedEdges = new Set(flow.steps.map(edgeKey));
+ for (const [id, el] of nodeEls) {
+ const on = usedNodes.has(id);
+ el.classList.toggle('dim', !on);
+ el.classList.toggle('hl', on);
+ }
+ for (const [key, path] of edges) {
+ const on = usedEdges.has(key);
+ path.classList.toggle('hidden', !on);
+ path.classList.toggle('hl', on);
+ }
+
+ // numbered hop badges at each highlighted edge's midpoint
+ badgeLayer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ flow.steps.forEach((s, i) => {
+ const path = edges.get(edgeKey(s));
+ const mid = path.getPointAtLength(path.getTotalLength() * (0.42 + (i % 3) * 0.08));
+ const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ g.setAttribute('class', 'badge');
+ g.innerHTML = `<circle cx="${mid.x}" cy="${mid.y}" r="9"/><text x="${mid.x}" y="${mid.y}">${i + 1}</text>`;
+ badgeLayer.appendChild(g);
+ });
+ svg.appendChild(badgeLayer);
+
+ // bring the flow's nodes into view
+ const wrap = document.getElementById('diagramWrap');
+ const xs = [...usedNodes].map((id) => pos.get(id).x);
+ const ys = [...usedNodes].map((id) => pos.get(id).y);
+ wrap.scrollTo({
+ left: Math.max(0, (Math.min(...xs) + Math.max(...xs) + COL_W) / 2 - wrap.clientWidth / 2),
+ top: Math.max(0, (Math.min(...ys) + Math.max(...ys) + NODE_H) / 2 - wrap.clientHeight / 2),
+ behavior: 'smooth'
+ });
+
+ // step panel
+ detail.innerHTML = `<h2>${flow.label}</h2><div class="desc">${flow.description}</div>` +
+ flow.steps.map((s, i) => {
+ const t = transportsById.get(s.transport);
+ return `<div class="step" data-i="${i}">
+ <div class="route"><span class="num">${i + 1}</span>${nodesById.get(s.from).label} → ${nodesById.get(s.to).label}<span class="chip" style="color:${t.color};border-color:${t.color}">${t.label}</span></div>
+ <div class="label">${s.label}</div>
+ <div class="payload">${s.payload}</div>
+ </div>`;
+ }).join('');
+ detail.querySelectorAll('.step').forEach((el) => {
+ const step = flow.steps[Number(el.dataset.i)];
+ const path = edges.get(edgeKey(step));
+ const fromEl = nodeEls.get(step.from), toEl = nodeEls.get(step.to);
+ const focusEdge = (on) => {
+ el.classList.toggle('hl', on);
+ path.classList.toggle('focus', on);
+ fromEl.classList.toggle('selected', on);
+ toEl.classList.toggle('selected', on);
+ };
+ el.addEventListener('mouseenter', () => focusEdge(true));
+ el.addEventListener('mouseleave', () => focusEdge(false));
+ el.addEventListener('click', () => {
+ fromEl.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
+ });
+ });
+ detail.scrollTop = 0;
+ }
+
+ function showNode(nodeId) {
+ const n = nodesById.get(nodeId);
+ if (activeFlowId) selectFlow(null); else clearHighlights();
+ nodeEls.get(nodeId).classList.add('selected');
+ const inFlows = data.flows.filter((f) => f.steps.some((s) => s.from === nodeId || s.to === nodeId));
+ detail.innerHTML = `<div class="node-info">
+ <h2>${n.label}</h2>
+ ${n.file ? `<div class="file">${n.file}</div>` : ''}
+ <div class="desc">${n.desc || ''}</div>
+ ${inFlows.length ? `Appears in:<ul>${inFlows.map((f) => `<li><a data-flow="${f.id}">${f.label}</a></li>`).join('')}</ul>` : 'Not part of any documented flow yet.'}
+ </div>`;
+ detail.querySelectorAll('a[data-flow]').forEach((a) =>
+ a.addEventListener('click', () => selectFlow(a.dataset.flow))
+ );
+ }
+
+ // embed mode: the host page pushes selection changes (⌘K, in-app links) here
+ if (EMBED) {
+ window.addEventListener('message', (event) => {
+ if (event.origin !== location.origin) return;
+ if (event.data?.type !== 'flows:select') return;
+ const id = event.data.flow || null;
+ if (id !== activeFlowId) selectFlow(id, { fromUrl: true });
+ });
+ }
+
+ // deep link: ?flow=<id>, stale ids degrade to the overview inside selectFlow
+ const initial = new URLSearchParams(location.search).get('flow');
+ if (initial) selectFlow(initial, { fromUrl: true });
+})();
+</script>
+</body>
+</html>
diff --git a/client/public/flows.json b/client/public/flows.json
new file mode 100644
index 0000000000..65e3b13950
--- /dev/null
+++ b/client/public/flows.json
@@ -0,0 +1,256 @@
+{
+ "version": 1,
+ "groups": [
+ { "id": "client-pages", "label": "Client Pages", "column": 0 },
+ { "id": "client-services", "label": "Client Services", "column": 1 },
+ { "id": "server-routes", "label": "Routes & Sockets", "column": 2 },
+ { "id": "server-services", "label": "Server Services", "column": 3 },
+ { "id": "server-lib", "label": "Server Lib", "column": 4 },
+ { "id": "data-stores", "label": "Data Stores", "column": 5 },
+ { "id": "external", "label": "External Systems", "column": 6 }
+ ],
+ "transports": [
+ { "id": "http", "label": "HTTP REST", "color": "#3b82f6" },
+ { "id": "sse", "label": "SSE stream", "color": "#f59e0b", "dash": "2 4" },
+ { "id": "socket", "label": "Socket.IO", "color": "#22c55e", "dash": "8 4" },
+ { "id": "call", "label": "Direct call", "color": "#9ca3af" },
+ { "id": "emitter", "label": "EventEmitter (in-process)", "color": "#a855f7", "dash": "10 3 2 3" },
+ { "id": "spawn", "label": "Process spawn", "color": "#ef4444", "dash": "14 4" },
+ { "id": "storage", "label": "File / DB I/O", "color": "#14b8a6", "dash": "1 3" }
+ ],
+ "nodes": [
+ { "id": "page.imageGen", "label": "ImageGen", "group": "client-pages", "file": "client/src/pages/ImageGen.jsx", "desc": "Image generation UI: prompt, model picker, init image, gallery." },
+ { "id": "page.startStory", "label": "Start a Story", "group": "client-pages", "file": "client/src/pages/StartStory.jsx", "desc": "Entry chooser: new story, import, or Story Builder." },
+ { "id": "page.storyBuilder", "label": "Story Builder", "group": "client-pages", "file": "client/src/pages/StoryBuilder.jsx", "desc": "Guided step-by-step story creation with AI-generated steps." },
+ { "id": "page.chiefOfStaff", "label": "Chief of Staff", "group": "client-pages", "file": "client/src/pages/ChiefOfStaff.jsx", "desc": "CoS tasks, agents, schedules, and autopilot controls." },
+ { "id": "page.apps", "label": "Apps", "group": "client-pages", "file": "client/src/pages/Apps.jsx", "desc": "Managed-app dashboard: start/stop/restart, status, deploys." },
+ { "id": "page.shell", "label": "Shell", "group": "client-pages", "file": "client/src/pages/Shell.jsx", "desc": "Browser terminal attached to server-side PTY sessions." },
+ { "id": "page.sharing", "label": "Sharing", "group": "client-pages", "file": "client/src/pages/Sharing.jsx", "desc": "Federation: peers, subscriptions, sync status." },
+ { "id": "page.settings", "label": "Settings", "group": "client-pages", "file": "client/src/pages/Settings.jsx", "desc": "System settings including the self-update panel." },
+ { "id": "page.backupWidget", "label": "Backup Widget", "group": "client-pages", "file": "client/src/components/BackupWidget.jsx", "desc": "Backup trigger + snapshot list (dashboard widget and Settings tab)." },
+
+ { "id": "svc.apiCore", "label": "apiCore (request)", "group": "client-services", "file": "client/src/services/apiCore.js", "desc": "Shared HTTP helper: JSON handling, error toasts, silent mode." },
+ { "id": "svc.apiStoryBuilder", "label": "apiStoryBuilder", "group": "client-services", "file": "client/src/services/apiStoryBuilder.js", "desc": "Story Builder session/step API wrappers." },
+ { "id": "svc.apiApps", "label": "apiApps", "group": "client-services", "file": "client/src/services/apiApps.js", "desc": "Managed-app lifecycle API wrappers." },
+ { "id": "svc.apiSystem", "label": "apiSystem", "group": "client-services", "file": "client/src/services/apiSystem.js", "desc": "System API wrappers: backup, update, health." },
+ { "id": "svc.apiPeerSync", "label": "apiPeerSync", "group": "client-services", "file": "client/src/services/apiPeerSync.js", "desc": "Peer-sync API wrappers: sync-now, subscriptions, pull-record." },
+ { "id": "svc.apiSchedules", "label": "apiSchedules", "group": "client-services", "file": "client/src/services/apiSchedules.js", "desc": "Automation-schedule API wrappers." },
+ { "id": "svc.socketClient", "label": "socket.js client", "group": "client-services", "file": "client/src/services/socket.js", "desc": "Single shared Socket.IO client connection for the whole app." },
+ { "id": "svc.voiceClient", "label": "voiceClient", "group": "client-services", "file": "client/src/services/voiceClient.js", "desc": "Mic capture, turn submission, and TTS playback for the voice agent." },
+
+ { "id": "route.imageGen", "label": "routes/imageGen", "group": "server-routes", "file": "server/routes/imageGen.js", "desc": "Image generation endpoints: generate, cancel, gallery, job events." },
+ { "id": "route.storyBuilder", "label": "routes/storyBuilder", "group": "server-routes", "file": "server/routes/storyBuilder.js", "desc": "Story Builder CRUD, step generation, SSE progress." },
+ { "id": "route.cos", "label": "routes/cos*", "group": "server-routes", "file": "server/routes/cosAgentRoutes.js", "desc": "CoS task/agent/job/schedule endpoints (cos*Routes family)." },
+ { "id": "route.apps", "label": "routes/apps", "group": "server-routes", "file": "server/routes/apps.js", "desc": "Managed-app endpoints: start/stop/restart, config, status." },
+ { "id": "route.backup", "label": "routes/backup", "group": "server-routes", "file": "server/routes/backup.js", "desc": "Backup endpoints: run, snapshots, restore, restore-db." },
+ { "id": "route.peerSync", "label": "routes/peerSync", "group": "server-routes", "file": "server/routes/peerSync.js", "desc": "Local sync commands + peer-facing push/manifest/record endpoints." },
+ { "id": "route.update", "label": "routes/update", "group": "server-routes", "file": "server/routes/update.js", "desc": "Self-update endpoints: check, sync-fork, execute." },
+ { "id": "route.schedules", "label": "routes/automationSchedules", "group": "server-routes", "file": "server/routes/automationSchedules.js", "desc": "Automation schedule CRUD endpoints." },
+ { "id": "sock.hub", "label": "Socket.IO hub", "group": "server-routes", "file": "server/services/socket.js", "desc": "initSocket(io): shell, logs, app-ops, and subscription handlers." },
+ { "id": "sock.voice", "label": "voice socket handlers", "group": "server-routes", "file": "server/sockets/voice.js", "desc": "registerVoiceHandlers: voice:turn / voice:text entry points." },
+
+ { "id": "svc.mediaJobQueue", "label": "mediaJobQueue", "group": "server-services", "file": "server/services/mediaJobQueue/index.js", "desc": "Unified job queue for image/video/training/audio; local vs codex lanes; SSE client attach." },
+ { "id": "svc.imageGen", "label": "imageGen service", "group": "server-services", "file": "server/services/imageGen/index.js", "desc": "Image generation backends: local (mflux), codex, external; param prep and variants." },
+ { "id": "svc.storyBuilderRunner", "label": "storyBuilderRunner", "group": "server-services", "file": "server/services/storyBuilderRunner.js", "desc": "Runs story steps: phase frames to SSE clients, persists results, promotes to pipeline." },
+ { "id": "svc.pipeline", "label": "pipeline", "group": "server-services", "file": "server/services/pipeline/autoRunner.js", "desc": "Comic/story pipeline: series/issues stores, text+visual stage auto-runner." },
+ { "id": "svc.voicePipeline", "label": "voice pipeline", "group": "server-services", "file": "server/services/voice/pipeline.js", "desc": "Voice turn orchestration: STT → LLM tool loop → TTS streaming." },
+ { "id": "svc.voiceTools", "label": "voice tools", "group": "server-services", "file": "server/services/voice/tools.js", "desc": "Voice agent tool schemas + dispatch: navigation, UI actions, timers, calendar." },
+ { "id": "svc.cos", "label": "cos", "group": "server-services", "file": "server/services/cos.js", "desc": "CoS task lifecycle: create/approve/queue; emits task:ready." },
+ { "id": "svc.subAgentSpawner", "label": "subAgentSpawner", "group": "server-services", "file": "server/services/subAgentSpawner.js", "desc": "Turns a ready task into a running agent: prompt build, model selection, worktree prep." },
+ { "id": "svc.cosRunnerClient", "label": "cosRunnerClient", "group": "server-services", "file": "server/services/cosRunnerClient.js", "desc": "Client for the standalone CoS Runner process (Socket.IO + HTTP health)." },
+ { "id": "svc.cosAgents", "label": "cosAgents", "group": "server-services", "file": "server/services/cosAgents.js", "desc": "Agent state index (date-bucketed JSON) + agent:* event fan-out to the UI." },
+ { "id": "svc.pm2", "label": "pm2 service", "group": "server-services", "file": "server/services/pm2.js", "desc": "PM2 wrapper: CLI spawn + programmatic connect, strict jlist status." },
+ { "id": "svc.shell", "label": "shell", "group": "server-services", "file": "server/services/shell.js", "desc": "PTY session manager: spawn, single-subscriber attach, safe env allowlist." },
+ { "id": "svc.backup", "label": "backup", "group": "server-services", "file": "server/services/backup.js", "desc": "rsync snapshots + pg_dump + manifest; effective-exclude computation." },
+ { "id": "svc.backupScheduler", "label": "backupScheduler", "group": "server-services", "file": "server/services/backupScheduler.js", "desc": "Registers the daily backup cron; re-reads settings every run." },
+ { "id": "svc.eventScheduler", "label": "eventScheduler", "group": "server-services", "file": "server/services/eventScheduler.js", "desc": "Generic cron engine: schedule/cancel named jobs." },
+ { "id": "svc.peerSync", "label": "sharing/peerSync", "group": "server-services", "file": "server/services/sharing/peerSync.js", "desc": "Federation orchestrator: push/receive, assets, subscriptions, integrity." },
+ { "id": "svc.updateChecker", "label": "updateChecker", "group": "server-services", "file": "server/services/updateChecker.js", "desc": "Upstream release poll, origin classification, fork-sync gate." },
+ { "id": "svc.updateExecutor", "label": "updateExecutor", "group": "server-services", "file": "server/services/updateExecutor.js", "desc": "Detached update.sh spawn that survives PM2 restarting PortOS itself." },
+ { "id": "svc.taskSchedule", "label": "taskSchedule", "group": "server-services", "file": "server/services/taskSchedule.js", "desc": "Unified v2 schedule store (interval/cron) with prompt versioning." },
+ { "id": "svc.cosJobScheduler", "label": "cosJobScheduler", "group": "server-services", "file": "server/services/cosJobScheduler.js", "desc": "Fires due scheduled jobs: inline script/shell or task:ready for AI agents." },
+
+ { "id": "lib.promptRunner", "label": "promptRunner", "group": "server-lib", "file": "server/lib/promptRunner.js", "desc": "Assembles prompts from templates + context and runs them through a provider." },
+ { "id": "lib.aiProvider", "label": "aiProvider + aiToolkit", "group": "server-lib", "file": "server/lib/aiProvider.js", "desc": "Provider registry/resolution: CLI providers, local backends, model selection." },
+ { "id": "lib.peerHttpClient", "label": "peerHttpClient", "group": "server-lib", "file": "server/lib/peerHttpClient.js", "desc": "peerFetch: authenticated HTTP to federated peer instances." },
+ { "id": "lib.navManifest", "label": "navManifest", "group": "server-lib", "file": "server/lib/navManifest.js", "desc": "NAV_COMMANDS + resolveNavCommand — shared by ⌘K palette and voice nav." },
+
+ { "id": "store.postgres", "label": "PostgreSQL", "group": "data-stores", "file": "server/lib/db.js", "desc": "Primary datastore (pg Pool via db.js with test-DB write guard): catalog, universes, pipeline, memory, story sessions." },
+ { "id": "store.jsonFiles", "label": "data/*.json", "group": "data-stores", "desc": "JSON file state: task-schedule.json, update.json, agent index buckets, settings, queue persistence." },
+ { "id": "store.diskAssets", "label": "data/ assets", "group": "data-stores", "desc": "Disk assets: image gallery, video history, uploads, LoRA datasets, backup snapshots." },
+
+ { "id": "ext.aiCli", "label": "AI CLI providers", "group": "external", "desc": "claude / codex CLIs spawned per run via aiToolkit CLI spawning." },
+ { "id": "ext.localLlm", "label": "Local LLM", "group": "external", "file": "server/services/lmStudioManager.js", "desc": "LM Studio / Ollama HTTP backends for local completions and embeddings." },
+ { "id": "ext.pm2", "label": "PM2 daemon", "group": "external", "desc": "Process manager for PortOS itself, managed apps, and the CoS Runner." },
+ { "id": "ext.cosRunner", "label": "CoS Runner (portos-cos)", "group": "external", "file": "server/cos-runner/index.js", "desc": "Standalone PM2 process that spawns and streams AI agent CLIs, isolated from the main server." },
+ { "id": "ext.pythonRunners", "label": "Python media runners", "group": "external", "desc": "mflux/diffusers image, video, and LoRA-training runner processes." },
+ { "id": "ext.whisper", "label": "Whisper (STT)", "group": "external", "desc": "Speech-to-text binary transcribing voice turns." },
+ { "id": "ext.tts", "label": "Piper / Kokoro (TTS)", "group": "external", "desc": "Text-to-speech binaries synthesizing reply audio sentence-by-sentence." },
+ { "id": "ext.pty", "label": "PTY (node-pty)", "group": "external", "desc": "Pseudo-terminal processes running the user's shell." },
+ { "id": "ext.peers", "label": "Federated peers", "group": "external", "desc": "Other PortOS installs reachable over the private network." },
+ { "id": "ext.updateSh", "label": "update.sh", "group": "external", "file": "update.sh", "desc": "Detached updater script: git pull --rebase --autostash + PM2 restart." },
+ { "id": "ext.rsync", "label": "rsync + pg_dump", "group": "external", "desc": "Snapshot copy and database dump tools invoked by the backup service." }
+ ],
+ "flows": [
+ {
+ "id": "create-image",
+ "label": "Create Image",
+ "category": "Media",
+ "description": "Generate an image through the unified media job queue, with live progress over SSE and the result saved to the gallery.",
+ "steps": [
+ { "from": "page.imageGen", "to": "route.imageGen", "transport": "http", "label": "POST /api/image-gen/generate", "payload": "multipart FormData: prompt, model, options, optional init image (direct fetch — multipart bypasses the JSON request() helper)" },
+ { "from": "route.imageGen", "to": "svc.mediaJobQueue", "transport": "call", "label": "enqueueJob()", "payload": "normalized job { id, kind: 'image', owner, params } after Zod validation" },
+ { "from": "svc.mediaJobQueue", "to": "svc.imageGen", "transport": "call", "label": "dispatch by lane", "payload": "job params routed to local (mflux) / codex / external backend" },
+ { "from": "svc.imageGen", "to": "ext.pythonRunners", "transport": "spawn", "label": "spawn runner CLI", "payload": "resolved CLI args: model path, prompt, steps, dimensions, seed" },
+ { "from": "ext.pythonRunners", "to": "svc.mediaJobQueue", "transport": "call", "label": "stdout progress", "payload": "STAGE: markers + per-step progress parsed from runner output" },
+ { "from": "svc.mediaJobQueue", "to": "page.imageGen", "transport": "sse", "label": "GET /api/image-gen/:jobId/events", "payload": "progress frames: stage, percent, preview; terminal completed/failed event" },
+ { "from": "svc.mediaJobQueue", "to": "store.diskAssets", "transport": "storage", "label": "persist result", "payload": "final image written to the gallery + job record; catalog attach hooks fire on completion" }
+ ]
+ },
+ {
+ "id": "start-story",
+ "label": "Start a Story",
+ "category": "Story",
+ "description": "Create a story through the guided Story Builder: each step is generated by an AI provider, streamed back over SSE, persisted to Postgres, and finally promoted into the comic pipeline.",
+ "steps": [
+ { "from": "page.startStory", "to": "page.storyBuilder", "transport": "call", "label": "react-router navigate", "payload": "chooser routes to Story Builder (or Importer / Universes)" },
+ { "from": "page.storyBuilder", "to": "svc.apiStoryBuilder", "transport": "call", "label": "createStorySession / generateStoryStep", "payload": "session id, step id, generation options" },
+ { "from": "svc.apiStoryBuilder", "to": "route.storyBuilder", "transport": "http", "label": "POST /api/story-builder/:id/steps/:stepId/generate", "payload": "JSON body validated by Zod schemas" },
+ { "from": "route.storyBuilder", "to": "svc.storyBuilderRunner", "transport": "call", "label": "startStepRun()", "payload": "session + step context; run registered for SSE attach" },
+ { "from": "svc.storyBuilderRunner", "to": "lib.promptRunner", "transport": "call", "label": "run step prompt", "payload": "assembled prompt: step template + story-so-far + canon context" },
+ { "from": "lib.promptRunner", "to": "lib.aiProvider", "transport": "call", "label": "resolve provider", "payload": "provider + model selection from settings" },
+ { "from": "lib.aiProvider", "to": "ext.aiCli", "transport": "spawn", "label": "provider run", "payload": "prompt executed via CLI provider (or local LLM backend)" },
+ { "from": "svc.storyBuilderRunner", "to": "page.storyBuilder", "transport": "sse", "label": "GET /:id/steps/:stepId/progress", "payload": "phase frames: { runId, phase, status, partial text }" },
+ { "from": "svc.storyBuilderRunner", "to": "store.postgres", "transport": "storage", "label": "persist step", "payload": "step result saved via storyBuilderStore (db.js)" },
+ { "from": "svc.storyBuilderRunner", "to": "svc.pipeline", "transport": "call", "label": "promote to pipeline", "payload": "finished story becomes pipeline series/issues; autoRunner chains idea → prose → scripts stages" }
+ ]
+ },
+ {
+ "id": "voice-command",
+ "label": "Voice Command",
+ "category": "Voice",
+ "description": "A spoken command round-trip: audio in over Socket.IO, whisper transcription, local-LLM tool loop (including UI navigation via the shared nav manifest), and synthesized speech streamed back.",
+ "steps": [
+ { "from": "svc.voiceClient", "to": "svc.socketClient", "transport": "call", "label": "emit voice:turn", "payload": "recorded audio buffer + mimeType" },
+ { "from": "svc.socketClient", "to": "sock.voice", "transport": "socket", "label": "voice:turn", "payload": "{ audio, mimeType } over the shared Socket.IO connection" },
+ { "from": "sock.voice", "to": "svc.voicePipeline", "transport": "call", "label": "run voice turn", "payload": "audio handed to the pipeline with socket for reply frames" },
+ { "from": "svc.voicePipeline", "to": "ext.whisper", "transport": "spawn", "label": "transcribe", "payload": "WAV audio → transcript text" },
+ { "from": "svc.voicePipeline", "to": "ext.localLlm", "transport": "http", "label": "streamChat", "payload": "transcript + intent-scoped tool specs; streamed completion" },
+ { "from": "svc.voicePipeline", "to": "svc.voiceTools", "transport": "call", "label": "dispatchTool", "payload": "tool calls { name, args } from the LLM loop" },
+ { "from": "svc.voiceTools", "to": "lib.navManifest", "transport": "call", "label": "resolveNavCommand", "payload": "spoken target fuzzy-matched against NAV_COMMANDS aliases (ui_navigate)" },
+ { "from": "svc.voiceTools", "to": "svc.voiceClient", "transport": "socket", "label": "UI action events", "payload": "navigation / UI action requests executed by the client" },
+ { "from": "svc.voicePipeline", "to": "ext.tts", "transport": "spawn", "label": "synthesize", "payload": "reply sentences → WAV audio via piper/kokoro" },
+ { "from": "svc.voicePipeline", "to": "svc.voiceClient", "transport": "socket", "label": "voice:tts:audio", "payload": "{ sentence, wav } frames played back as they arrive" }
+ ]
+ },
+ {
+ "id": "cos-agent-run",
+ "label": "CoS Agent Run",
+ "category": "Agents",
+ "description": "A Chief-of-Staff task becomes a running AI agent: task:ready fires the spawner, the standalone CoS Runner process executes the provider CLI, and output streams back to the UI.",
+ "steps": [
+ { "from": "page.chiefOfStaff", "to": "svc.apiCore", "transport": "call", "label": "create / approve task", "payload": "task fields via the shared request() helper" },
+ { "from": "svc.apiCore", "to": "route.cos", "transport": "http", "label": "POST /api/cos/...", "payload": "task CRUD JSON, Zod-validated" },
+ { "from": "route.cos", "to": "svc.cos", "transport": "call", "label": "task lifecycle", "payload": "task created/queued in CoS state" },
+ { "from": "svc.cos", "to": "svc.subAgentSpawner", "transport": "emitter", "label": "cosEvents 'task:ready'", "payload": "task { id, taskType, prompt, repoPath, metadata }" },
+ { "from": "svc.subAgentSpawner", "to": "svc.cosRunnerClient", "transport": "call", "label": "spawnViaRunner", "payload": "spawn config: provider, model, cwd/worktree, built prompt" },
+ { "from": "svc.cosRunnerClient", "to": "ext.cosRunner", "transport": "socket", "label": "spawn request", "payload": "Socket.IO + HTTP to portos-cos on PORTS.COS" },
+ { "from": "ext.cosRunner", "to": "ext.aiCli", "transport": "spawn", "label": "run agent CLI", "payload": "claude/codex spawned in the task's worktree with the prompt" },
+ { "from": "ext.cosRunner", "to": "svc.cosRunnerClient", "transport": "socket", "label": "output stream", "payload": "parsed agent output lines + completion status" },
+ { "from": "svc.cosRunnerClient", "to": "svc.cosAgents", "transport": "call", "label": "record output", "payload": "batched output lines + lifecycle updates" },
+ { "from": "svc.cosAgents", "to": "store.jsonFiles", "transport": "storage", "label": "persist agent index", "payload": "date-bucketed agent state JSON" },
+ { "from": "svc.cosAgents", "to": "page.chiefOfStaff", "transport": "socket", "label": "agent:output / agent:completed", "payload": "live output lines and final summary rendered in the UI" }
+ ]
+ },
+ {
+ "id": "scheduled-task",
+ "label": "Scheduled Task / Autopilot",
+ "category": "Agents",
+ "description": "A user-configured schedule fires on cron: inline script/shell jobs run directly; AI jobs emit task:ready and continue as a CoS Agent Run.",
+ "steps": [
+ { "from": "page.chiefOfStaff", "to": "svc.apiSchedules", "transport": "call", "label": "save schedule", "payload": "cron expression / interval + job config" },
+ { "from": "svc.apiSchedules", "to": "route.schedules", "transport": "http", "label": "POST /api/automation-schedules", "payload": "schedule JSON, Zod-validated" },
+ { "from": "route.schedules", "to": "svc.taskSchedule", "transport": "call", "label": "persist schedule", "payload": "unified v2 schedule entry (interval/cron, prompt version)" },
+ { "from": "svc.taskSchedule", "to": "store.jsonFiles", "transport": "storage", "label": "write data/task-schedule.json", "payload": "schedule state on disk — takes effect without restart" },
+ { "from": "svc.taskSchedule", "to": "svc.cosJobScheduler", "transport": "call", "label": "cron fire", "payload": "due job evaluated with spawn guard" },
+ { "from": "svc.cosJobScheduler", "to": "svc.subAgentSpawner", "transport": "emitter", "label": "cosEvents 'task:ready'", "payload": "AI jobs become tasks — continues as the CoS Agent Run flow" },
+ { "from": "svc.cosJobScheduler", "to": "page.chiefOfStaff", "transport": "socket", "label": "jobs:executed / tasks:changed", "payload": "execution results surface in the schedule UI" }
+ ]
+ },
+ {
+ "id": "start-app-pm2",
+ "label": "Start / Stop App (PM2)",
+ "category": "System",
+ "description": "Managed-app lifecycle: the Apps page drives PM2 through the pm2 service; status flows back via the HTTP response and apps:changed socket events.",
+ "steps": [
+ { "from": "page.apps", "to": "svc.apiApps", "transport": "call", "label": "startApp(id)", "payload": "app id" },
+ { "from": "svc.apiApps", "to": "route.apps", "transport": "http", "label": "POST /api/apps/:id/start", "payload": "app id in the path; no body" },
+ { "from": "route.apps", "to": "svc.pm2", "transport": "call", "label": "startApp", "payload": "process name + start options from the app's ecosystem config" },
+ { "from": "svc.pm2", "to": "ext.pm2", "transport": "spawn", "label": "pm2 CLI / connectAndRun", "payload": "pm2 start/stop/restart against the daemon" },
+ { "from": "ext.pm2", "to": "svc.pm2", "transport": "call", "label": "jlist status", "payload": "strict process list → per-app pm2Status/overallStatus" },
+ { "from": "svc.pm2", "to": "page.apps", "transport": "socket", "label": "apps:changed", "payload": "notifyAppsChanged broadcast; UI updates local state" }
+ ]
+ },
+ {
+ "id": "shell-session",
+ "label": "Shell Session",
+ "category": "System",
+ "description": "A browser terminal attached to a server-side PTY: keystrokes down and raw terminal output back, all over Socket.IO, with single-subscriber attach semantics.",
+ "steps": [
+ { "from": "page.shell", "to": "svc.socketClient", "transport": "call", "label": "emit shell:start / shell:attach", "payload": "{ sessionId, claim } — auto-pick paths claim, manual paths don't displace" },
+ { "from": "svc.socketClient", "to": "sock.hub", "transport": "socket", "label": "shell:* events", "payload": "start/attach/input/resize routed to shell handlers" },
+ { "from": "sock.hub", "to": "svc.shell", "transport": "call", "label": "session management", "payload": "single-subscriber attach; sessions persist across reconnects" },
+ { "from": "svc.shell", "to": "ext.pty", "transport": "spawn", "label": "pty.spawn", "payload": "user shell with buildSafeEnv allowlisted environment" },
+ { "from": "ext.pty", "to": "svc.shell", "transport": "call", "label": "PTY data", "payload": "raw terminal output bytes" },
+ { "from": "svc.shell", "to": "page.shell", "transport": "socket", "label": "shell:output / shell:exit", "payload": "terminal data rendered by xterm; exit code on close" }
+ ]
+ },
+ {
+ "id": "run-backup",
+ "label": "Run Backup",
+ "category": "System",
+ "description": "Snapshot backup: rsync with anchored excludes plus a Postgres dump and manifest, with progress broadcast over Socket.IO. The scheduled path re-reads settings on every cron run.",
+ "steps": [
+ { "from": "page.backupWidget", "to": "svc.apiSystem", "transport": "call", "label": "runBackup()", "payload": "no arguments — server reads saved backup settings" },
+ { "from": "svc.apiSystem", "to": "route.backup", "transport": "http", "label": "POST /api/backup/run", "payload": "empty body; settings are server-side" },
+ { "from": "route.backup", "to": "svc.backup", "transport": "call", "label": "runBackup", "payload": "destPath + computeEffectiveExcludes() result" },
+ { "from": "svc.backup", "to": "ext.rsync", "transport": "spawn", "label": "rsync + pg_dump", "payload": "anchored rsync filters; pg_dump of the portos database" },
+ { "from": "svc.backup", "to": "store.diskAssets", "transport": "storage", "label": "write snapshot", "payload": "snapshot dir + db.sql + manifest at the destination" },
+ { "from": "svc.backup", "to": "page.backupWidget", "transport": "socket", "label": "backup:started / backup:completed", "payload": "{ snapshotId, filesChanged, pgBackup } progress and result" },
+ { "from": "svc.backupScheduler", "to": "svc.eventScheduler", "transport": "call", "label": "register daily cron", "payload": "cron expression from settings.backup (scheduled path)" },
+ { "from": "svc.eventScheduler", "to": "svc.backup", "transport": "call", "label": "cron fire", "payload": "re-reads destPath/excludes/enabled fresh on every run" }
+ ]
+ },
+ {
+ "id": "peer-sync",
+ "label": "Peer Sync",
+ "category": "Sync",
+ "description": "Federation between PortOS installs: subscribed records push to peers over HTTP with LWW merge on receive; version gates keep newer peers from corrupting older ones.",
+ "steps": [
+ { "from": "page.sharing", "to": "svc.apiPeerSync", "transport": "call", "label": "syncNow()", "payload": "optional peer/subscription filter" },
+ { "from": "svc.apiPeerSync", "to": "route.peerSync", "transport": "http", "label": "POST /api/peer-sync/sync-now", "payload": "sync command JSON" },
+ { "from": "route.peerSync", "to": "svc.peerSync", "transport": "call", "label": "orchestrate push", "payload": "records gathered per subscription; schema-version gated" },
+ { "from": "svc.peerSync", "to": "lib.peerHttpClient", "transport": "call", "label": "peerFetch", "payload": "authenticated request built from peer URL + credentials" },
+ { "from": "lib.peerHttpClient", "to": "ext.peers", "transport": "http", "label": "POST peer /api/peer-sync/push", "payload": "push payload: record + sidecar + asset manifest (peerSyncPushSchema)" },
+ { "from": "ext.peers", "to": "route.peerSync", "transport": "http", "label": "inbound push (receiving side)", "payload": "the same endpoint on the receiving install accepts pushes from peers" },
+ { "from": "svc.peerSync", "to": "store.postgres", "transport": "storage", "label": "applyIncomingPush", "payload": "LWW-timestamp merge + integrity check; missing assets pulled back from the sender" },
+ { "from": "svc.peerSync", "to": "page.sharing", "transport": "socket", "label": "sync:applied / peers:updated", "payload": "sync results and peer presence updates" }
+ ]
+ },
+ {
+ "id": "self-update",
+ "label": "Self-Update",
+ "category": "System",
+ "description": "PortOS updates itself: the fork-aware gate decides whether the pull is safe, then a double-forked update.sh survives PM2 killing its parent while it pulls and restarts.",
+ "steps": [
+ { "from": "page.settings", "to": "svc.apiSystem", "transport": "call", "label": "executeUpdate()", "payload": "{ acknowledgeFork? } from the Update tab buttons" },
+ { "from": "svc.apiSystem", "to": "route.update", "transport": "http", "label": "POST /api/update/execute", "payload": "fork acknowledgement flag; 412 FORK_SYNC_REQUIRED if a fork hasn't synced" },
+ { "from": "route.update", "to": "svc.updateChecker", "transport": "call", "label": "fork gate", "payload": "remoteInfo (isUpstream/isFork) vs lastForkSync freshness" },
+ { "from": "route.update", "to": "svc.updateExecutor", "transport": "call", "label": "executeUpdate", "payload": "target version + options" },
+ { "from": "svc.updateExecutor", "to": "ext.updateSh", "transport": "spawn", "label": "double-fork detached spawn", "payload": "update.sh detached so it survives PM2 tree-kill during its own pm2 restart" },
+ { "from": "ext.updateSh", "to": "ext.pm2", "transport": "spawn", "label": "git pull + pm2 restart", "payload": "git pull --rebase --autostash from origin, then PM2 restarts PortOS" },
+ { "from": "svc.updateExecutor", "to": "page.settings", "transport": "socket", "label": "portos:update:step", "payload": "{ step, status, message } progress frames until the restart" }
+ ]
+ }
+ ]
+}
diff --git a/client/src/App.jsx b/client/src/App.jsx
index cbd029a60c..880f91123d 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -22,6 +22,7 @@ const UsagePage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ d
const ProcessesPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ default: m.ProcessesPage })));
const AgentsPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ default: m.AgentsPage })));
const DataDog = lazyWithReload(() => import('./pages/DataDog'));
+const FlowsDoc = lazyWithReload(() => import('./pages/FlowsDoc'));
const GitHub = lazyWithReload(() => import('./pages/GitHub'));
const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
@@ -200,6 +201,7 @@ export default function App() {
<Route path="apps" element={<Apps />} />
<Route path="devtools" element={<Navigate to="/devtools/runs" replace />} />
<Route path="devtools/datadog" element={<DataDog />} />
+ <Route path="devtools/flows" element={<FlowsDoc />} />
<Route path="devtools/github" element={<GitHub />} />
<Route path="devtools/history" element={<HistoryPage />} />
<Route path="devtools/image-clean" element={<ImageClean />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index e4f95cc231..037c3d3da7 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -238,6 +238,7 @@ const navItems = [
{ to: '/devtools/runner', label: 'Code', icon: Code2 },
{ to: '/data', label: 'Data', icon: HardDrive },
{ to: '/devtools/datadog', label: 'DataDog', icon: Dog },
+ { to: '/devtools/flows', label: 'Flows', icon: WorkflowIcon },
{ to: '/devtools/github', label: 'GitHub', icon: GitBranch },
{ to: '/devtools/history', label: 'History', icon: History },
{ to: '/devtools/image-clean', label: 'Image Cleaner', icon: Eraser },
@@ -1118,6 +1119,7 @@ export default function Layout() {
{(() => {
const isFullWidth = location.pathname === '/character' ||
location.pathname === '/ai' ||
+ location.pathname === '/devtools/flows' ||
location.pathname === '/ask' ||
location.pathname.startsWith('/ask/') ||
location.pathname.startsWith('/calendar') ||
diff --git a/client/src/lib/flowsDoc.test.js b/client/src/lib/flowsDoc.test.js
new file mode 100644
index 0000000000..981d1f9e17
--- /dev/null
+++ b/client/src/lib/flowsDoc.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// Integrity checks for the integration-flows document rendered by
+// client/public/flows.html (launched from /devtools/flows).
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, '..', '..', '..');
+const flowsDoc = JSON.parse(
+ readFileSync(resolve(here, '..', '..', 'public', 'flows.json'), 'utf8')
+);
+
+const uniqueIds = (items) => {
+ const ids = items.map((x) => x.id);
+ return new Set(ids).size === ids.length;
+};
+
+describe('flows.json', () => {
+ it('has unique group, transport, node, and flow ids', () => {
+ expect(uniqueIds(flowsDoc.groups)).toBe(true);
+ expect(uniqueIds(flowsDoc.transports)).toBe(true);
+ expect(uniqueIds(flowsDoc.nodes)).toBe(true);
+ expect(uniqueIds(flowsDoc.flows)).toBe(true);
+ });
+
+ it('gives every group a label and a distinct column', () => {
+ const columns = flowsDoc.groups.map((g) => g.column);
+ expect(new Set(columns).size).toBe(flowsDoc.groups.length);
+ for (const group of flowsDoc.groups) {
+ expect(group.label, group.id).toBeTruthy();
+ }
+ });
+
+ it('assigns every node to a declared group', () => {
+ const groupIds = new Set(flowsDoc.groups.map((g) => g.id));
+ for (const node of flowsDoc.nodes) {
+ expect(groupIds.has(node.group), `${node.id} → ${node.group}`).toBe(true);
+ }
+ });
+
+ it('references only declared nodes and transports from flow steps', () => {
+ const nodeIds = new Set(flowsDoc.nodes.map((n) => n.id));
+ const transportIds = new Set(flowsDoc.transports.map((t) => t.id));
+ for (const flow of flowsDoc.flows) {
+ expect(flow.steps.length, flow.id).toBeGreaterThan(0);
+ for (const step of flow.steps) {
+ const at = `${flow.id}: ${step.from} → ${step.to}`;
+ expect(nodeIds.has(step.from), at).toBe(true);
+ expect(nodeIds.has(step.to), at).toBe(true);
+ expect(transportIds.has(step.transport), at).toBe(true);
+ expect(step.label, at).toBeTruthy();
+ expect(step.payload, at).toBeTruthy();
+ }
+ }
+ });
+
+ it('annotates every flow, node, and transport for the renderer', () => {
+ for (const flow of flowsDoc.flows) {
+ expect(flow.label, flow.id).toBeTruthy();
+ expect(flow.category, flow.id).toBeTruthy();
+ expect(flow.description, flow.id).toBeTruthy();
+ }
+ for (const node of flowsDoc.nodes) {
+ expect(node.label, node.id).toBeTruthy();
+ expect(node.desc, node.id).toBeTruthy();
+ }
+ for (const transport of flowsDoc.transports) {
+ expect(transport.label, transport.id).toBeTruthy();
+ expect(transport.color, transport.id).toMatch(/^#[0-9a-f]{6}$/);
+ }
+ });
+
+ it('points node files at paths that still exist', () => {
+ // Catches refactors that move/rename a module the doc references.
+ for (const node of flowsDoc.nodes) {
+ if (!node.file) continue;
+ expect(existsSync(resolve(repoRoot, node.file)), `${node.id} → ${node.file}`).toBe(true);
+ }
+ });
+
+ it('only documents nodes that participate in at least one flow', () => {
+ const used = new Set(flowsDoc.flows.flatMap((f) => f.steps.flatMap((s) => [s.from, s.to])));
+ for (const node of flowsDoc.nodes) {
+ expect(used.has(node.id), `${node.id} is orphaned`).toBe(true);
+ }
+ });
+});
diff --git a/client/src/pages/FlowsDoc.jsx b/client/src/pages/FlowsDoc.jsx
new file mode 100644
index 0000000000..e7e02334da
--- /dev/null
+++ b/client/src/pages/FlowsDoc.jsx
@@ -0,0 +1,57 @@
+import { useEffect, useRef, useState } from 'react';
+import { ExternalLink } from 'lucide-react';
+import useDrawerTab from '../hooks/useDrawerTab';
+
+// Thin host for the standalone integration-flows doc (client/public/flows.html).
+// This page's ?flow= param is the source of truth for the open flow: selections
+// made inside the iframe arrive via postMessage, and outside changes (⌘K, links)
+// push back into the already-mounted doc — in embed mode the doc never writes
+// its own URL.
+export default function FlowsDoc() {
+ const [flow, setFlow] = useDrawerTab('flow', null);
+ const iframeRef = useRef(null);
+ // Captured once: updating src after mount would reload the doc on every click.
+ const [iframeSrc] = useState(() =>
+ `/flows.html?embed=1${flow ? `&flow=${encodeURIComponent(flow)}` : ''}`
+ );
+
+ useEffect(() => {
+ const onMessage = (event) => {
+ if (event.origin !== window.location.origin) return;
+ if (event.data?.type !== 'flows:select') return;
+ setFlow(event.data.flow || null);
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+ }, [setFlow]);
+
+ useEffect(() => {
+ iframeRef.current?.contentWindow?.postMessage(
+ { type: 'flows:select', flow },
+ window.location.origin
+ );
+ }, [flow]);
+
+ return (
+ <div className="absolute inset-0 flex flex-col">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-port-border flex-none">
+ <h1 className="text-lg font-semibold">Integration Flows</h1>
+ <a
+ href={`/flows.html${flow ? `?flow=${encodeURIComponent(flow)}` : ''}`}
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-center gap-1.5 text-sm text-port-accent hover:underline"
+ >
+ <ExternalLink size={14} />
+ Open full screen
+ </a>
+ </div>
+ <iframe
+ ref={iframeRef}
+ title="PortOS integration flows"
+ src={iframeSrc}
+ className="flex-1 w-full border-0"
+ />
+ </div>
+ );
+}
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 9e35624aba..5050e0a206 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -104,6 +104,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.browser', path: '/browser', label: 'Browser', section: 'Dev Tools', aliases: ['browser'] },
{ id: 'nav.devtools.runner', path: '/devtools/runner', label: 'Code', section: 'Dev Tools', aliases: ['devtools-runner'] },
{ id: 'nav.devtools.datadog', path: '/devtools/datadog', label: 'DataDog', section: 'Dev Tools', aliases: ['datadog', 'devtools-datadog'] },
+ { id: 'nav.devtools.flows', path: '/devtools/flows', label: 'Flows', section: 'Dev Tools', aliases: ['flows', 'integration-flows', 'workflows'], keywords: ['architecture', 'diagram', 'data flow', 'integrations', 'how it works'] },
{ id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },
{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },
{ id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },