Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: Tailcat dial-direction / managed serve for federated peers (#6486)
atomanticagentb53a40343e3e
diff --git a/client/src/components/instances/TailcatServePanel.jsx b/client/src/components/instances/TailcatServePanel.jsxnew file mode 100644index 0000000000..4407fd246d--- /dev/null+++ b/client/src/components/instances/TailcatServePanel.jsx@@ -0,0 +1,148 @@+/**+ * Machine-local Tailcat serve status — start/stop PortOS API :5555 over+ * tailcat, and Copy the tc… address for the other node to Dial-them.+ *+ * The full address is returned by the serve status API on purpose (our own+ * capability). Never log it; never put it on a peer record.+ */++import { useCallback, useEffect, useState } from 'react';+import { Copy, RefreshCw, Square, Play, CheckCircle2, AlertCircle, Clock } from 'lucide-react';+import toast from '../ui/Toast';+import Pill from '../ui/Pill';+import { getTailcatServe, startTailcatServe, retryTailcatServe, stopTailcatServe } from '../../services/api';+import { PORTS } from '../../lib/ports';+import { timeAgo } from '../../utils/formatters';++const STATUS_TONE = { active: 'success', pending: 'muted', failed: 'warning', stopped: 'muted' };+const STATUS_ICON = { active: CheckCircle2, pending: Clock, failed: AlertCircle, stopped: Clock };++export default function TailcatServePanel({ onChange, compact = false }) {+ const [status, setStatus] = useState(null);+ const [busy, setBusy] = useState(false);++ const load = useCallback(async () => {+ const data = await getTailcatServe({ silent: true }).catch(() => null);+ setStatus(data && typeof data === 'object' ? data : null);+ }, []);++ useEffect(() => { load(); }, [load]);++ const run = async (fn, successMsg) => {+ setBusy(true);+ const result = await fn().catch(() => null);+ setBusy(false);+ await load();+ if (!result) return;+ onChange?.();+ if (successMsg) toast.success(successMsg);+ };++ const copyAddress = async () => {+ const addr = status?.tcAddress;+ if (!addr) return;+ try {+ await navigator.clipboard.writeText(addr);+ toast.success('Tailcat address copied — paste it on the other PortOS as Dial them');+ } catch {+ toast.error('Could not copy to clipboard');+ }+ };++ const label = status?.live+ ? 'serving'+ : (status?.status || 'stopped');+ const tone = status?.live+ ? 'success'+ : (STATUS_TONE[status?.status] || 'muted');+ const StatusIcon = status?.live+ ? CheckCircle2+ : (STATUS_ICON[status?.status] || Clock);++ return (+ <div className={compact+ ? ''+ : 'bg-port-card border border-port-border rounded-xl p-5'}+ >+ {!compact && (+ <>+ <h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-1">+ Tailcat serve (this node)+ </h2>+ <p className="text-[11px] text-gray-500 mb-3 leading-snug">+ Expose this PortOS API (<span className="font-mono">:{PORTS.API}</span>) over+ tailcat so a peer that is a better outbound initiator can Dial them+ toward us. No Tailscale account. Copy the address out of band only.+ </p>+ </>+ )}++ <div className="bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex flex-wrap items-center gap-2">+ <Pill tone={tone} size="xs" bordered={false} icon={StatusIcon}>+ {label}+ </Pill>+ <span className="text-[11px] font-mono text-gray-500">+ serve :{status?.localPort || PORTS.API}+ {status?.keyName ? ` · key=${status.keyName}` : ''}+ </span>+ <div className="ml-auto flex items-center gap-1">+ {status?.hasAddress && status?.tcAddress && (+ <button+ type="button"+ onClick={copyAddress}+ disabled={busy}+ title="Copy full tc address for the other node"+ className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white disabled:opacity-50 border border-port-border rounded px-2 py-1 transition-colors"+ >+ <Copy size={11} /> Copy address+ </button>+ )}+ {!status?.live && (+ <button+ type="button"+ onClick={() => run(+ () => (status?.enabled || status?.status === 'failed'+ ? retryTailcatServe()+ : startTailcatServe({})),+ 'Tailcat serve started',+ )}+ disabled={busy}+ className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white disabled:opacity-50 border border-port-border rounded px-2 py-1 transition-colors"+ >+ {status?.status === 'failed' || status?.enabled+ ? <RefreshCw size={11} className={busy ? 'animate-spin' : ''} />+ : <Play size={11} />}+ {busy ? 'Working...' : (status?.status === 'failed' || status?.enabled ? 'Retry' : 'Start serve')}+ </button>+ )}+ {status?.live && (+ <button+ type="button"+ onClick={() => run(() => stopTailcatServe(), 'Tailcat serve stopped')}+ disabled={busy}+ className="inline-flex items-center gap-1 text-[11px] text-gray-500 hover:text-port-error disabled:opacity-50 border border-port-border rounded px-2 py-1 transition-colors"+ >+ <Square size={11} /> Stop+ </button>+ )}+ </div>+ </div>++ {status?.hasAddress && (+ <p className="text-[11px] font-mono text-gray-400 mt-2 break-all select-all">+ {status.tcAddressRedacted || 'tc…'}+ <span className="text-gray-600"> (redacted preview — use Copy for the full address)</span>+ </p>+ )}++ {status?.lastError && status?.status !== 'active' && (+ <p className="text-[11px] text-port-error mt-2 leading-snug break-words">+ {status.lastError}+ {status.lastErrorAt && <span className="text-gray-500"> · {timeAgo(status.lastErrorAt)}</span>}+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/instances/TailcatServePanel.test.jsx b/client/src/components/instances/TailcatServePanel.test.jsxnew file mode 100644index 0000000000..8e12de8d68--- /dev/null+++ b/client/src/components/instances/TailcatServePanel.test.jsx@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/api', () => ({+ getTailcatServe: vi.fn(),+ startTailcatServe: vi.fn(),+ retryTailcatServe: vi.fn(),+ stopTailcatServe: vi.fn(),+}));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++import { getTailcatServe, startTailcatServe, stopTailcatServe } from '../../services/api';+import TailcatServePanel from './TailcatServePanel';++const stopped = {+ enabled: false,+ status: 'stopped',+ live: false,+ localPort: 5555,+ keyName: 'portos-api',+ tcAddress: null,+ tcAddressRedacted: null,+ hasAddress: false,+ lastError: null,+ lastErrorAt: null,+};++const serving = {+ ...stopped,+ enabled: true,+ status: 'active',+ live: true,+ tcAddress: 'tcEXAMPLE' + 'E'.repeat(40),+ tcAddressRedacted: 'tcEX…EEEE',+ hasAddress: true,+};++describe('TailcatServePanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getTailcatServe.mockResolvedValue(stopped);+ });++ it('shows start control when serve is stopped', async () => {+ render(<TailcatServePanel />);+ expect(await screen.findByRole('button', { name: 'Start serve' })).toBeInTheDocument();+ expect(screen.getByText(/serve :5555/)).toBeInTheDocument();+ });++ it('starts serve and exposes a copy control when an address is known', async () => {+ getTailcatServe+ .mockResolvedValueOnce(stopped)+ .mockResolvedValue(serving);+ startTailcatServe.mockResolvedValue(serving);+ const user = userEvent.setup();+ render(<TailcatServePanel />);+ await user.click(await screen.findByRole('button', { name: 'Start serve' }));+ await waitFor(() => expect(startTailcatServe).toHaveBeenCalled());+ expect(await screen.findByRole('button', { name: 'Copy address' })).toBeInTheDocument();+ expect(screen.getByText(/tcEX…EEEE/)).toBeInTheDocument();+ });++ it('stops a live serve', async () => {+ getTailcatServe.mockResolvedValue(serving);+ stopTailcatServe.mockResolvedValue(stopped);+ const user = userEvent.setup();+ render(<TailcatServePanel />);+ await user.click(await screen.findByRole('button', { name: 'Stop' }));+ await waitFor(() => expect(stopTailcatServe).toHaveBeenCalled());+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex a6d8be8fcc..797bb54f52 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -21,6 +21,7 @@ import {getPeerFullSyncCoverage,getBrainParityReports,retryTailcatForward, forgetTailcatForward,+ startTailcatServe, getTailcatServe,} from '../services/api';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';@@ -32,6 +33,7 @@ import BrainParityPanel from '../components/instances/BrainParityPanel';import BrainParitySchedule from '../components/instances/BrainParitySchedule';import TailnetHelpBanner from '../components/instances/TailnetHelpBanner';import TailcatForwardsPanel from '../components/instances/TailcatForwardsPanel';+import TailcatServePanel from '../components/instances/TailcatServePanel';import TailcatForwardStatus from '../components/instances/TailcatForwardStatus';import { timeAgo, timeUntil } from '../utils/formatters';import { directionalCounts, describeDirectional } from '../lib/syncCounts';@@ -211,6 +213,8 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {// same default the form actually submits — see Instances.test.jsx).export function AddPeerForm({ onAdd, addressRef }) {const [mode, setMode] = useState('classic'); // 'classic' | 'tailcat'+ // Dial polarity for Tailcat: we dial their serve, or they dial ours.+ const [dialDirection, setDialDirection] = useState('dial-them'); // 'dial-them' | 'they-dial-us'const [address, setAddress] = useState('');const [tcAddress, setTcAddress] = useState('');const [tailcatHttps, setTailcatHttps] = useState(false);@@ -220,10 +224,18 @@ export function AddPeerForm({ onAdd, addressRef }) {const [username, setUsername] = useState('');const [password, setPassword] = useState('');const [adding, setAdding] = useState(false);+ const [serveBusy, setServeBusy] = useState(false);+ const [serveStatus, setServeStatus] = useState(null);++ const refreshServe = async () => {+ const data = await getTailcatServe({ silent: true }).catch(() => null);+ setServeStatus(data && typeof data === 'object' ? data : null);+ };const handleSubmit = async (e) => {e.preventDefault();if (mode === 'tailcat') {+ if (dialDirection === 'they-dial-us') return; // serve path uses its own buttonsif (!tcAddress.trim()) return;setAdding(true);const data = { tcAddress: tcAddress.trim() };@@ -262,7 +274,30 @@ export function AddPeerForm({ onAdd, addressRef }) {toast.success('Peer added');};- const canSubmit = mode === 'tailcat' ? !!tcAddress.trim() : !!address.trim();+ const ensureOurServe = async () => {+ setServeBusy(true);+ const result = await startTailcatServe({}).catch(() => null);+ setServeBusy(false);+ await refreshServe();+ if (!result) return;+ onAdd?.();+ toast.success('Tailcat serve is running — copy the address for the other node');+ };++ const copyOurAddress = async () => {+ const addr = serveStatus?.tcAddress;+ if (!addr) return;+ try {+ await navigator.clipboard.writeText(addr);+ toast.success('Address copied — paste it on the other PortOS as Dial them');+ } catch {+ toast.error('Could not copy to clipboard');+ }+ };++ const canSubmit = mode === 'tailcat'+ ? (dialDirection === 'dial-them' && !!tcAddress.trim())+ : !!address.trim();return (<form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-xl p-5">@@ -273,7 +308,7 @@ export function AddPeerForm({ onAdd, addressRef }) {<buttontype="button"aria-pressed={mode === 'classic'}- disabled={adding}+ disabled={adding || serveBusy}onClick={() => setMode('classic')}className={`text-xs px-2.5 py-1 rounded border transition-colors ${mode === 'classic' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}>@@ -282,14 +317,36 @@ export function AddPeerForm({ onAdd, addressRef }) {<buttontype="button"aria-pressed={mode === 'tailcat'}- disabled={adding}- onClick={() => setMode('tailcat')}+ disabled={adding || serveBusy}+ onClick={() => { setMode('tailcat'); refreshServe(); }}className={`text-xs px-2.5 py-1 rounded border transition-colors ${mode === 'tailcat' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}>- Tailcat address+ Tailcat</button></div>- {mode === 'tailcat' ? (+ {mode === 'tailcat' && (+ <div className="flex flex-wrap gap-2 mb-3" role="group" aria-label="Tailcat dial direction">+ <button+ type="button"+ aria-pressed={dialDirection === 'dial-them'}+ disabled={adding || serveBusy}+ onClick={() => setDialDirection('dial-them')}+ className={`text-xs px-2.5 py-1 rounded border transition-colors ${dialDirection === 'dial-them' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}+ >+ Dial them+ </button>+ <button+ type="button"+ aria-pressed={dialDirection === 'they-dial-us'}+ disabled={adding || serveBusy}+ onClick={() => { setDialDirection('they-dial-us'); refreshServe(); }}+ className={`text-xs px-2.5 py-1 rounded border transition-colors ${dialDirection === 'they-dial-us' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}+ >+ They dial us+ </button>+ </div>+ )}+ {mode === 'tailcat' && dialDirection === 'dial-them' ? (<div className="flex flex-wrap gap-2"><inputref={addressRef}@@ -315,6 +372,39 @@ export function AddPeerForm({ onAdd, addressRef }) {{adding ? 'Connecting...' : 'Add via tailcat'}</button></div>+ ) : mode === 'tailcat' && dialDirection === 'they-dial-us' ? (+ <div className="space-y-3">+ <p className="text-[11px] text-gray-500 leading-snug">+ Start serve on this node, copy our <span className="font-mono">tc…</span> address,+ and paste it into the <em>other</em> PortOS as <strong>Dial them</strong>.+ Use this when the other machine is a better outbound initiator+ (client firewall / Little Snitch often blocks home dials).+ </p>+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ disabled={serveBusy || serveStatus?.live}+ onClick={ensureOurServe}+ 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"+ >+ {serveBusy ? 'Starting...' : (serveStatus?.live ? 'Serve running' : 'Start serve')}+ </button>+ <button+ type="button"+ disabled={!serveStatus?.tcAddress || serveBusy}+ onClick={copyOurAddress}+ className="border border-port-border hover:border-port-accent disabled:opacity-50 text-gray-300 px-4 py-2 rounded text-sm transition-colors"+ >+ Copy our address+ </button>+ </div>+ {serveStatus?.hasAddress && (+ <p className="text-[11px] font-mono text-gray-400 break-all">+ {serveStatus.tcAddressRedacted || 'tc…'}+ <span className="text-gray-600"> (redacted — use Copy for the full address)</span>+ </p>+ )}+ </div>) : (<div className="flex flex-wrap gap-2"><input@@ -353,7 +443,7 @@ export function AddPeerForm({ onAdd, addressRef }) {</button></div>)}- {mode === 'tailcat' && (+ {mode === 'tailcat' && dialDirection === 'dial-them' && (<><label htmlFor="tailcat-https" className="flex items-center gap-2 text-sm text-gray-400 mt-3"><input id="tailcat-https" type="checkbox" checked={tailcatHttps}@@ -1523,6 +1613,8 @@ export default function Instances() {{/* Also outside the peer-count guard: a tailcat forward whose start failednever registered a peer, so this is the only surface that can retry it. */}+ <TailcatServePanel onChange={fetchData} />+<TailcatForwardsPanel onChange={fetchData} peerIds={peers.map((p) => p.id)} />{peers.length > 0 && (diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsxindex ea9acfec59..4e8a165492 100644--- a/client/src/pages/Instances.test.jsx+++ b/client/src/pages/Instances.test.jsx@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { AddPeerForm } from './Instances.jsx';import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';-import { addPeer, addTailcatPeer } from '../services/api';+import { addPeer, addTailcatPeer, startTailcatServe, getTailcatServe } from '../services/api';vi.mock('../services/api', () => ({getInstances: vi.fn(),@@ -23,6 +23,13 @@ vi.mock('../services/api', () => ({getTailcatForwards: vi.fn().mockResolvedValue({ forwards: [] }),retryTailcatForward: vi.fn(),forgetTailcatForward: vi.fn(),+ getTailcatServe: vi.fn().mockResolvedValue({+ enabled: false, status: 'stopped', live: false, localPort: 5555,+ keyName: 'portos-api', tcAddress: null, tcAddressRedacted: null, hasAddress: false,+ }),+ startTailcatServe: vi.fn(),+ retryTailcatServe: vi.fn(),+ stopTailcatServe: vi.fn(),}));vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));@@ -64,7 +71,7 @@ describe('AddPeerForm tailcat path', () => {it('submits a pasted tc address through addTailcatPeer (not classic addPeer)', async () => {render(<AddPeerForm onAdd={() => {}} />);- fireEvent.click(screen.getByRole('button', { name: 'Tailcat address' }));+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));const tc = 'tcEXAMPLE' + 'B'.repeat(40);fireEvent.change(screen.getByLabelText('Tailcat address'), { target: { value: tc } });fireEvent.click(screen.getByRole('button', { name: 'Add via tailcat' }));@@ -74,7 +81,7 @@ describe('AddPeerForm tailcat path', () => {it('sends HTTPS selection for a remote TLS install', async () => {render(<AddPeerForm onAdd={() => {}} />);- fireEvent.click(screen.getByRole('button', { name: 'Tailcat address' }));+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));const tc = 'tcEXAMPLE' + 'B'.repeat(40);fireEvent.change(screen.getByLabelText('Tailcat address'), { target: { value: tc } });fireEvent.click(screen.getByLabelText('Remote PortOS uses HTTPS'));@@ -93,9 +100,49 @@ describe('AddPeerForm tailcat path', () => {expect(addTailcatPeer).not.toHaveBeenCalled();});- it('documents the 15555 local forward standard in the tailcat hint', () => {+ it('documents the 15555 local forward standard in the tailcat hint', async () => {render(<AddPeerForm onAdd={() => {}} />);- fireEvent.click(screen.getByRole('button', { name: 'Tailcat address' }));+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));+ // Settling the silent getTailcatServe from switching into Tailcat mode.+ await waitFor(() => expect(getTailcatServe).toHaveBeenCalled());expect(screen.getAllByText(new RegExp(String(DEFAULT_TAILCAT_LOCAL_PORT))).length).toBeGreaterThan(0);});});++describe('AddPeerForm dial direction', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ addTailcatPeer.mockResolvedValue({ id: 'peer-tc', port: DEFAULT_TAILCAT_LOCAL_PORT, transport: 'tailcat' });+ getTailcatServe.mockResolvedValue({+ enabled: false, status: 'stopped', live: false, localPort: 5555,+ keyName: 'portos-api', tcAddress: null, tcAddressRedacted: null, hasAddress: false,+ });+ startTailcatServe.mockResolvedValue({+ enabled: true, status: 'active', live: true, localPort: 5555,+ keyName: 'portos-api',+ tcAddress: 'tcEXAMPLE' + 'D'.repeat(40),+ tcAddressRedacted: 'tcEX…DDDD',+ hasAddress: true,+ });+ });++ it('defaults to Dial them and still submits a pasted address', async () => {+ render(<AddPeerForm onAdd={() => {}} />);+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));+ expect(screen.getByRole('button', { name: 'Dial them' })).toHaveAttribute('aria-pressed', 'true');+ const tc = 'tcEXAMPLE' + 'B'.repeat(40);+ fireEvent.change(screen.getByLabelText('Tailcat address'), { target: { value: tc } });+ fireEvent.click(screen.getByRole('button', { name: 'Add via tailcat' }));+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc }));+ });++ it('switches to They dial us and starts serve instead of pasting', async () => {+ render(<AddPeerForm onAdd={() => {}} />);+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));+ fireEvent.click(screen.getByRole('button', { name: 'They dial us' }));+ expect(screen.queryByLabelText('Tailcat address')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Start serve' }));+ await waitFor(() => expect(startTailcatServe).toHaveBeenCalled());+ expect(addTailcatPeer).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 466574c3d4..a0b1840151 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -344,6 +344,12 @@ export const addTailcatPeer = (data) => request('/instances/peers/tailcat', { meexport const getTailcatForwards = (options) => request('/instances/peers/tailcat/forwards', options);export const retryTailcatForward = (id) => request(`/instances/peers/tailcat/forwards/${id}/retry`, { method: 'POST' });export const forgetTailcatForward = (id) => request(`/instances/peers/tailcat/forwards/${id}`, { method: 'DELETE' });+// Managed tailcat serve on this node (PORTS.API). Status may include the full+// tc address so the operator can Copy it — this is our own serve capability.+export const getTailcatServe = (options) => request('/instances/peers/tailcat/serve', options);+export const startTailcatServe = (data) => request('/instances/peers/tailcat/serve', { method: 'POST', body: JSON.stringify(data || {}) });+export const retryTailcatServe = () => request('/instances/peers/tailcat/serve/retry', { method: 'POST' });+export const stopTailcatServe = () => request('/instances/peers/tailcat/serve', { method: 'DELETE' });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 connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });diff --git a/docs/PORTS.md b/docs/PORTS.mdindex e69740f6e2..d346218b7c 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -42,7 +42,7 @@ Common port labels:| 18022 | PortOS model host | - | Opt-in bearer-authenticated inference queue for dedicated hosts; one active generation. See [fleet host](./features/fleet-llm-host.md). || 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Started explicitly from host setup or by the operator. Dedicated hosting opts into Docker restart persistence. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). || 18021 | SGLang (Docker) | - | Loopback SGLang Qwen3.8-27B container on a Hopper/Blackwell host. Operator-started (`docker compose up -d`) — PortOS never brings it up on boot. See [features/sglang-qwen38.md](./features/sglang-qwen38.md). |-| 15555 | tailcat forward (loopback) | - | Preferred local listener for federated peers over [tailcat](https://github.com/tailscale/tailcat) (`PORTS.TAILCAT_FORWARD` / `DEFAULT_TAILCAT_LOCAL_PORT`). Maps `127.0.0.1:15555` → remote PortOS `:5555`. If busy, PortOS picks the next free port. See [features/tailcat-peers.md](./features/tailcat-peers.md). |+| 15555 | tailcat forward (loopback) | - | Preferred local listener for federated peers over [tailcat](https://github.com/tailscale/tailcat) (`PORTS.TAILCAT_FORWARD` / `DEFAULT_TAILCAT_LOCAL_PORT`). Maps `127.0.0.1:15555` → remote PortOS `:5555` (the remote side runs `tailcat serve` on `PORTS.API`). If busy, PortOS picks the next free port. Dial polarity / managed serve: [features/tailcat-peers.md](./features/tailcat-peers.md). |## How `:5555`, `:5553`, and `:5554` Relatediff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 1719af42ff..ee75e28bae 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -73,6 +73,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.- Tailcat peer forwards — `data/tailcat-forwards.json`. `file-primary`, **intentionally machine-local — never federated**: each row stores the bearer `tc…` address needed to restart `tailcat forward` after a PortOS reboot or to retry one that failed to start, plus the local/remote port mapping, the optional peer Basic credential, and the last (redacted) startup error. A row is written *before* the forward is attempted, so a failed add stays retryable instead of discarding the operator's pasted capability. The capability must not cross the wire, reach an API response, or appear in logs in full — `listTailcatForwards()` returns only the redacted form (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.+- Tailcat serve — `data/tailcat-serve.json`. `file-primary`, **intentionally machine-local — never federated**: enabled flag, status, local PortOS API port (`5555`), key name (`portos-api`), last (redacted) startup error, and the listen `tc…` address needed to restore `tailcat serve` after reboot and to offer Copy in the Instances UI. Adapter: `server/services/tailcatServe.js`. See [features/tailcat-peers.md](./features/tailcat-peers.md).- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.---diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.mdindex d585228744..24a5add42b 100644--- a/docs/features/tailcat-peers.md+++ b/docs/features/tailcat-peers.md@@ -19,14 +19,39 @@ free loopback port and registers the peer at that local port instead.No `tailcat serve all`, no exit-node mode, and no Tailscale daemon are used.+## Dial direction (who initiates)++Two polarities, one transport. You do **not** need both directions for v1.++| Choice | This node does | Other node does | When to use |+| --- | --- | --- | --- |+| **Dial them** | Paste their `tc…`, run `tailcat forward`, register peer at `127.0.0.1:<local>` | Runs `tailcat serve` (PortOS-managed or CLI) for `:5555` | This node can dial out freely (common for a sandbox / VPS). |+| **They dial us** | PortOS starts **serve** for `:5555`, you **Copy** our `tc…` | Pastes our address as **Dial them** on their Instances UI | This node is a poor dialer (client firewall / Little Snitch often blocks home `tailcat forward`) but a good *listener*; the other side is a better outbound initiator. |++Hypothesis (non-binding): reverse polarity helps when the current node is a better+outbound initiator than the peer that should dial it — use the product option;+do not hardcode any particular host.++### Fleet sketch (replace cloud Tailscale with per-node tailcat)++1. Every PortOS enables **Tailcat serve (this node)** (stable key `portos-api`).+2. Each peer that should reach another uses **Dial them** with that node's+ copied `<tcADDR>` (machine-local forward → `127.0.0.1:15555`).+3. No Tailscale account, daemon, `serve all`, or exit-node.+4. If dials fail with `context deadline exceeded` / `tunnel_dial` while the+ far side self-dials fine via DERP, flip polarity: serve on the blocked+ dialer, dial from the good initiator.+## Operator flow (Instances UI)-1. Open **Instances → Add Peer → Tailcat address**.-2. Paste the peer's `tc…` address (received out of band).-3. PortOS ensures `tailcat` is installed, starts the forward, and calls the- normal peer registration against `127.0.0.1:<localPort>`. Select **Remote- PortOS uses HTTPS** if the remote install has enabled TLS.-4. Classic **Host / port** add remains unchanged (still rejects loopback).+1. Open **Instances → Add Peer → Tailcat**.+2. Choose **Dial them** or **They dial us**.+3. **Dial them:** paste the peer's `tc…` address (received out of band). PortOS+ ensures `tailcat` is installed, starts the forward, and registers a peer at+ `127.0.0.1:<localPort>`. Select **Remote PortOS uses HTTPS** if needed.+4. **They dial us:** start serve (or use the **Tailcat serve** panel), **Copy**+ our address, and paste it into the *other* PortOS as Dial them.+5. Classic **Host / port** add remains unchanged (still rejects loopback).### How `tailcat` gets installed@@ -57,12 +82,26 @@ announcements cannot replace the managed local host or forwarding port.Forwards are persisted in machine-local `data/tailcat-forwards.json` so PortOScan restart them on boot **and retry one that failed to start**. Graceful-shutdown stops forwards while retaining their restart metadata. The full `tc…`-string is a bearer capability — it is **never** logged in full, never placed on-the peer record returned to the UI or to other peers, never returned by an API-response, and must never appear in commits, PR bodies, docs, or tests. Use+shutdown stops forwards while retaining their restart metadata.++**Serve** is persisted separately in machine-local `data/tailcat-serve.json`+(enabled flag, status, local port, key name, last error, and the listen+address). PortOS runs `tailcat serve --full-address --json --key=portos-api 5555`+(not `serve all`, not exit-node), restores serve on boot when enabled, and stops+the child on shutdown. The serve status API returns the full `tc…` address so+the Instances UI can offer **Copy** — that is *this node's* capability to share+out of band. Forward listings still return only the redacted form of a *peer's*+pasted address. Logs always redact. Never place a serve or forward capability on+a peer record, never federate these files, and never commit real `tc…` values —placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.+| Serve surface | What it does |+| --- | --- |+| `GET /api/instances/peers/tailcat/serve` | Status: live/enabled/ports/key, copyable `tcAddress` when known, redacted preview, last error. |+| `POST …/serve` | Ensure serve is running for `PORTS.API` (5555). |+| `POST …/serve/retry` | Restart from the saved config. |+| `DELETE …/serve` | Stop serve and disable restore-on-boot. |+### The saved address is what makes a failed add recoverableThe row is written **before** the forward is attempted. That ordering is the@@ -179,7 +218,9 @@ dial remote port 5555: context deadline exceededUDP blocked *and* the relay refused leaves no path at all, so nothing everreaches the remote — which is also why the far side shows no activity. Allow-the `tailcat` binary outbound in the filter, then Retry the forward.+the `tailcat` binary outbound in the filter, then Retry the forward. If outbound+allow-listing is impractical on this host, switch to **They dial us**: serve+here and have the sandbox (or other good initiator) Dial them toward this node.### The DERP map has to be reachable — by Go@@ -260,9 +301,9 @@ tailcat forward <tcADDR> 15555:5555### Checklist for agents- [ ] PortOS up on sandbox `:5555`-- [ ] `tailcat serve --key=… 5555` (not `serve all`, not exit-node)-- [ ] Hand operator `<tcADDR>` out of band only-- [ ] Operator uses UI Tailcat add (local **15555 → 5555**)+- [ ] Prefer **Instances → Tailcat serve** (or CLI `tailcat serve --key=… 5555`) — not `serve all`, not exit-node+- [ ] Hand operator `<tcADDR>` out of band only (Copy from UI)+- [ ] Operator uses **Dial them** (local **15555 → 5555**), *or* if home dials time out, home uses **They dial us** and the sandbox Dials them- [ ] Never write real `tc…` values into git, PR text, or federated logs## Relateddiff --git a/server/routes/instances.js b/server/routes/instances.jsindex 36f04f7149..c8d8d80383 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -13,6 +13,7 @@ import { provisionTailscaleCert } from '../services/certProvisioner.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import * as tailcatPeer from '../services/tailcatPeer.js';+import * as tailcatServe from '../services/tailcatServe.js';import { getTailscaleStatus } from '../lib/tailscale.js';import { federatedMediaPeerSettingsSchema, validateRequest } from '../lib/validation.js';@@ -294,6 +295,35 @@ router.delete('/peers/tailcat/forwards/:id', asyncHandler(async (req, res) => {res.json(await tailcatPeer.forgetTailcatForward(req.params.id));}));++// GET /api/instances/peers/tailcat/serve — this node's managed tailcat serve status.+// Returns the full tc address when known so the operator can Copy it out of band+// (our own serve capability — unlike peer forwards, which stay redacted).+router.get('/peers/tailcat/serve', asyncHandler(async (_req, res) => {+ res.json(await tailcatServe.getTailcatServeStatus());+}));++// POST /api/instances/peers/tailcat/serve — ensure serve is running for PORTS.API.+router.post('/peers/tailcat/serve', asyncHandler(async (req, res) => {+ const body = req.body && typeof req.body === 'object' ? req.body : {};+ const status = await tailcatServe.ensureTailcatServe({+ localPort: Number.isInteger(body.localPort) ? body.localPort : undefined,+ keyName: typeof body.keyName === 'string' ? body.keyName : undefined,+ });+ res.status(200).json(status);+}));++// POST /api/instances/peers/tailcat/serve/retry — restart from saved config.+router.post('/peers/tailcat/serve/retry', asyncHandler(async (_req, res) => {+ res.json(await tailcatServe.retryTailcatServe());+}));++// DELETE /api/instances/peers/tailcat/serve — stop serve and disable restore-on-boot.+router.delete('/peers/tailcat/serve', asyncHandler(async (_req, res) => {+ res.json(await tailcatServe.stopTailcatServe({ disable: true }));+}));++// POST /api/instances/peers — add a peerrouter.post('/peers', asyncHandler(async (req, res) => {const data = validateRequest(addPeerSchema, req.body);diff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex de23ed9c89..cf4932652c 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -35,12 +35,25 @@ vi.mock('../services/tailcatPeer.js', async (original) => ({retryTailcatForward: vi.fn(),forgetTailcatForward: vi.fn(),}));+vi.mock('../services/tailcatServe.js', async (original) => ({+ ...(await original()),+ getTailcatServeStatus: vi.fn(),+ ensureTailcatServe: vi.fn(),+ retryTailcatServe: vi.fn(),+ stopTailcatServe: vi.fn(),+}));import {addPeerViaTailcat,listTailcatForwards,retryTailcatForward,forgetTailcatForward,} from '../services/tailcatPeer.js';+import {+ getTailcatServeStatus,+ ensureTailcatServe,+ retryTailcatServe,+ stopTailcatServe,+} from '../services/tailcatServe.js';import instancesRoutes from './instances.js';const buildApp = () => {@@ -268,3 +281,47 @@ describe('saved tailcat forward routes', () => {expect(res.body).toEqual({ id: 'fwd_1', peerId: 'peer-example' });});});+++describe('tailcat serve routes', () => {+ beforeEach(() => vi.clearAllMocks());++ it('returns serve status including a copyable address shape', async () => {+ const status = {+ enabled: true,+ status: 'active',+ live: true,+ localPort: 5555,+ keyName: 'portos-api',+ tcAddress: 'tcEXAMPLE' + 'A'.repeat(40),+ tcAddressRedacted: 'tcEX…AAAA',+ hasAddress: true,+ lastError: null,+ lastErrorAt: null,+ };+ getTailcatServeStatus.mockResolvedValue(status);+ const res = await request(buildApp()).get('/api/instances/peers/tailcat/serve');+ expect(res.status).toBe(200);+ expect(res.body).toEqual(status);+ });++ it('starts serve via POST', async () => {+ const status = { enabled: true, live: true, status: 'active', localPort: 5555, keyName: 'portos-api', hasAddress: true };+ ensureTailcatServe.mockResolvedValue(status);+ const res = await request(buildApp()).post('/api/instances/peers/tailcat/serve').send({});+ expect(res.status).toBe(200);+ expect(ensureTailcatServe).toHaveBeenCalled();+ expect(res.body).toEqual(status);+ });++ it('retries and stops serve', async () => {+ retryTailcatServe.mockResolvedValue({ enabled: true, live: true, status: 'active' });+ stopTailcatServe.mockResolvedValue({ enabled: false, live: false, status: 'stopped' });+ const retry = await request(buildApp()).post('/api/instances/peers/tailcat/serve/retry');+ expect(retry.status).toBe(200);+ expect(retryTailcatServe).toHaveBeenCalled();+ const stop = await request(buildApp()).delete('/api/instances/peers/tailcat/serve');+ expect(stop.status).toBe(200);+ expect(stopTailcatServe).toHaveBeenCalledWith({ disable: true });+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex cd06e871fd..6e9c8facca 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -843,6 +843,9 @@ export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled,void import('./tailcatPeer.js').then(({ restoreForwards }) => restoreForwards()).catch((err) => console.log(`⚠️ tailcat forward restore failed: ${err.message}`));+ void import('./tailcatServe.js')+ .then(({ restoreServe }) => restoreServe())+ .catch((err) => console.log(`⚠️ tailcat serve restore failed: ${err.message}`));},initSyncOrchestrator}))@@ -904,6 +907,8 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>markHostShuttingDown();await import('./tailcatPeer.js').then(({ stopAllForwards }) => stopAllForwards()).catch(() => console.error('❌ Tailcat forward shutdown failed'));+ await import('./tailcatServe.js').then(({ stopServeProcess }) => stopServeProcess())+ .catch(() => console.error('❌ Tailcat serve shutdown failed'));// Disarm the idle reaper before anything awaits: a sweep that fires mid// -shutdown would `pm2 stop` a model server the user never asked to lose,// and PortOS is about to stop being the thing that could restart it.diff --git a/server/services/tailcatServe.js b/server/services/tailcatServe.jsnew file mode 100644index 0000000000..ba382327d9--- /dev/null+++ b/server/services/tailcatServe.js@@ -0,0 +1,524 @@+/**+ * Machine-local `tailcat serve` for the PortOS API port — the reverse polarity+ * of `tailcatPeer.js` forwards.+ *+ * When this node is a better *outbound initiator* than the peer that should+ * dial it (firewall / Little Snitch / path asymmetry), the operator starts+ * serve here, copies the printed `tc…` address out of band, and pastes it into+ * the *other* PortOS as Dial-them (forward). No Tailscale account, no+ * `serve all`, no exit-node.+ *+ * The serve address is this machine's own capability: it is persisted+ * machine-locally, returned by the status API so the Instances UI can offer a+ * Copy control, and always redacted in logs. It is never placed on a peer+ * record, never federated, and never committed.+ */++import { mkdir, readFile, unlink } from 'node:fs/promises';+import { dirname } from 'node:path';+import { spawn } from '../lib/childProcess.js';+import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';+import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';+import { PORTS } from '../lib/ports.js';+import { ServerError } from '../lib/errorHandler.js';+import { safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';+import {+ ensureTailcatInstalled,+ primeDerpMapCache,+ isValidTcAddress,+ redactTcAddress,+ redactTailcatDiagnostics,+} from './tailcatPeer.js';++const SERVE_FILE = dataPath('tailcat-serve.json');+const ADDR_FILE = dataPath('tailcat-serve.addr');+const DEFAULT_KEY_NAME = 'portos-api';+const DEFAULT_LOCAL_PORT = PORTS.API;+const SERVE_READY_MS = 20_000;+const DIAGNOSTIC_TAIL_CHARS = 4096;+const GENKEY_TIMEOUT_MS = 60_000;+const DEFAULT_DATA = { version: 1, serve: null };++const withLock = createMutex();+const withLifecycle = createMutex();++/** @type {{ child: import('node:child_process').ChildProcess, localPort: number, keyName: string } | null} */+let liveServe = null;+let shuttingDown = false;++/**+ * Normalize a stored serve record. Drop anything that cannot drive a restore+ * (missing key name / bad port). The tc address is optional until the first+ * successful start prints one.+ */+function normalizeServeEntry(entry) {+ if (!entry || typeof entry !== 'object') return null;+ const keyName = typeof entry.keyName === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(entry.keyName)+ ? entry.keyName+ : DEFAULT_KEY_NAME;+ const localPort = Number.isInteger(entry.localPort) && entry.localPort >= 1 && entry.localPort <= 65535+ ? entry.localPort+ : DEFAULT_LOCAL_PORT;+ const status = ['active', 'failed', 'stopped', 'pending'].includes(entry.status)+ ? entry.status+ : 'stopped';+ const tcAddress = isValidTcAddress(entry.tcAddress) ? entry.tcAddress.trim() : null;+ return {+ enabled: entry.enabled === true,+ status,+ localPort,+ keyName,+ tcAddress,+ lastError: typeof entry.lastError === 'string' ? entry.lastError : null,+ lastErrorAt: typeof entry.lastErrorAt === 'string' ? entry.lastErrorAt : null,+ createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date().toISOString(),+ updatedAt: typeof entry.updatedAt === 'string' ? entry.updatedAt : null,+ };+}++async function loadServeData() {+ const data = await readJSONFile(SERVE_FILE, DEFAULT_DATA, { strict: true, logError: false })+ .catch(() => { throw new ServerError('Could not read tailcat serve storage', { status: 503 }); });+ if (data?.version !== 1) {+ throw new ServerError('Invalid tailcat serve storage', { status: 503 });+ }+ return { version: 1, serve: normalizeServeEntry(data.serve) };+}++async function saveServeEntry(entry) {+ await ensureDir(PATHS.data);+ await atomicWrite(SERVE_FILE, { version: 1, serve: entry });+}++async function readServeEntry() {+ const data = await loadServeData();+ return data.serve;+}++async function patchServeEntry(patch) {+ return withLock(async () => {+ const current = await readServeEntry() || {+ enabled: false,+ status: 'stopped',+ localPort: DEFAULT_LOCAL_PORT,+ keyName: DEFAULT_KEY_NAME,+ tcAddress: null,+ lastError: null,+ lastErrorAt: null,+ createdAt: new Date().toISOString(),+ updatedAt: null,+ };+ const next = normalizeServeEntry({+ ...current,+ ...patch,+ updatedAt: new Date().toISOString(),+ });+ await saveServeEntry(next);+ return next;+ });+}++async function markServeFailed(error) {+ const detail = redactTailcatDiagnostics(error?.message || String(error || 'unknown error'));+ await patchServeEntry({+ status: 'failed',+ lastError: detail || 'unknown error',+ lastErrorAt: new Date().toISOString(),+ }).catch(() => null);+}++/**+ * Operator-facing serve status. Returns the full `tcAddress` when known so the+ * Instances UI can offer Copy — this is *our* serve address, not a peer's+ * pasted capability. Logs elsewhere still use the redacted form only.+ */+export async function getTailcatServeStatus() {+ const entry = await readServeEntry();+ const live = !!(liveServe?.child && !liveServe.child.killed);+ if (!entry) {+ return {+ enabled: false,+ status: 'stopped',+ live: false,+ localPort: DEFAULT_LOCAL_PORT,+ keyName: DEFAULT_KEY_NAME,+ tcAddress: null,+ tcAddressRedacted: null,+ hasAddress: false,+ lastError: null,+ lastErrorAt: null,+ createdAt: null,+ updatedAt: null,+ };+ }+ return {+ enabled: entry.enabled,+ status: live ? 'active' : entry.status,+ live,+ localPort: entry.localPort,+ keyName: entry.keyName,+ tcAddress: entry.tcAddress,+ tcAddressRedacted: entry.tcAddress ? redactTcAddress(entry.tcAddress) : null,+ hasAddress: !!entry.tcAddress,+ lastError: entry.lastError,+ lastErrorAt: entry.lastErrorAt,+ createdAt: entry.createdAt,+ updatedAt: entry.updatedAt,+ };+}++/**+ * Ensure a named server key exists under tailcat's config dir. `genkey` without+ * `--force` refuses to overwrite; that refusal is success for us — we want a+ * stable address across PortOS restarts.+ */+export async function ensureServeKey({+ bin,+ keyName = DEFAULT_KEY_NAME,+ runGenkey = (b, args) => bufferedSpawn(b, args, {+ env: safeChildProcessEnv(),+ timeoutMs: GENKEY_TIMEOUT_MS,+ }),+} = {}) {+ if (!bin) throw new ServerError('tailcat binary required to create a serve key', { status: 503 });+ const result = await runGenkey(bin, ['genkey', `--key=${keyName}`]);+ if (result.success) return { created: true, keyName };+ const detail = spawnFailureDetail(result, `exit ${result.code}`);+ // Existing key is the common case after the first start.+ if (/already|exist|overwrite/i.test(detail)) {+ return { created: false, keyName };+ }+ // Proceed anyway: serve will fail with a clearer message if the key is gone.+ // A DERP-map blip during genkey should not block a retry that already has a key.+ return { created: false, keyName, warning: redactTailcatDiagnostics(detail) };+}++/**+ * Parse `{"listenAddr":"tc…"}` JSON that `tailcat serve --json` writes to stdout.+ */+export function parseServeListenAddr(text) {+ const raw = String(text || '');+ // The encoder writes one JSON object; tolerate leading chatter / multiple lines.+ for (const line of raw.split(/\r?\n/)) {+ const trimmed = line.trim();+ if (!trimmed.startsWith('{')) continue;+ try {+ const parsed = JSON.parse(trimmed);+ const addr = typeof parsed?.listenAddr === 'string' ? parsed.listenAddr.trim() : '';+ if (isValidTcAddress(addr)) return addr;+ } catch {+ // not the listenAddr frame+ }+ }+ // Fallback: a bare tc… token (e.g. TAILCAT_ADDR_FILE contents).+ const match = raw.match(/tc[A-Za-z0-9_+\/=-]{24,}/);+ return match && isValidTcAddress(match[0]) ? match[0] : null;+}++/**+ * Start `tailcat serve --full-address --json --key=<name> <port>`. Resolves once+ * the listen address is known (stdout JSON and/or TAILCAT_ADDR_FILE).+ */+export async function startServeProcess({+ bin,+ localPort = DEFAULT_LOCAL_PORT,+ keyName = DEFAULT_KEY_NAME,+ addrFile = ADDR_FILE,+ spawnFn = spawn,+ readyMs = SERVE_READY_MS,+ readFileFn = readFile,+ mkdirFn = mkdir,+} = {}) {+ if (shuttingDown) throw new Error('PortOS is shutting down');+ if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) {+ throw new ServerError('Invalid local port for tailcat serve', { status: 400, code: 'TAILCAT_SERVE_BAD_PORT' });+ }++ await mkdirFn(dirname(addrFile), { recursive: true }).catch(() => null);+ await unlink(addrFile).catch(() => null);++ const child = spawnFn(+ bin,+ ['serve', '--verbose', '--full-address', '--json', `--key=${keyName}`, String(localPort)],+ safeChildProcessOptions({+ env: safeChildProcessEnv({ TAILCAT_ADDR_FILE: addrFile }),+ stdio: ['ignore', 'pipe', 'pipe'],+ }),+ );++ let stdoutTail = '';+ let stderrTail = '';+ let settled = false;+ let resolvedAddr = null;+ let resolveReady;+ let rejectReady;+ let timer;+ let poller;++ const ready = new Promise((resolve, reject) => {+ resolveReady = resolve;+ rejectReady = reject;+ });++ const finish = (error) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ clearInterval(poller);+ const diagnostics = error ? redactTailcatDiagnostics(stderrTail || stdoutTail) : '';+ if (error) {+ if (diagnostics) error.message = `${error.message} — tailcat said: ${diagnostics}`;+ try { child.kill('SIGTERM'); } catch { /* process event boundary */ }+ rejectReady(error);+ } else {+ resolveReady();+ }+ };++ const tryResolve = async () => {+ if (settled) return;+ const fromStdout = parseServeListenAddr(stdoutTail);+ if (fromStdout) {+ resolvedAddr = fromStdout;+ finish();+ return;+ }+ const fromFile = await readFileFn(addrFile, 'utf8').then(+ (text) => parseServeListenAddr(text),+ () => null,+ );+ if (fromFile) {+ resolvedAddr = fromFile;+ finish();+ }+ };++ timer = setTimeout(() => finish(new Error('tailcat serve startup timed out')), readyMs);+ poller = setInterval(() => { tryResolve().catch(() => {}); }, 150);++ child.stdout?.on('data', (chunk) => {+ stdoutTail = (stdoutTail + String(chunk)).slice(-DIAGNOSTIC_TAIL_CHARS);+ tryResolve().catch(() => {});+ });+ child.stderr?.on('data', (chunk) => {+ stderrTail = (stderrTail + String(chunk)).slice(-DIAGNOSTIC_TAIL_CHARS);+ // Human line often includes the address before --json flushes; harvest it.+ const fromErr = parseServeListenAddr(stderrTail);+ if (fromErr) {+ resolvedAddr = fromErr;+ finish();+ return;+ }+ tryResolve().catch(() => {});+ });+ child.on('error', () => finish(new Error('tailcat serve process failed')));+ child.once('exit', (code, signal) => {+ if (!settled) {+ finish(new Error(`tailcat serve exited early (code=${code}, signal=${signal})`));+ }+ });++ await ready;++ console.log(+ `🐈 tailcat serve listening for PortOS :${localPort} (${redactTcAddress(resolvedAddr)}, key=${keyName})`,+ );+ return { child, tcAddress: resolvedAddr, localPort, keyName };+}++function killLiveServe() {+ if (liveServe?.child && !liveServe.child.killed) {+ try { liveServe.child.kill('SIGTERM'); } catch { /* best-effort */ }+ }+ liveServe = null;+}++function trackServe(child, localPort, keyName) {+ liveServe = { child, localPort, keyName };+ child.on('exit', () => {+ if (liveServe?.child === child) liveServe = null;+ });+}++/**+ * Ensure serve is running for the PortOS API port. Idempotent when already live+ * with the same port/key; otherwise stops and restarts.+ */+export function ensureTailcatServe(options = {}) {+ return withLifecycle(() => ensureServe(options));+}++async function ensureServe({+ localPort = DEFAULT_LOCAL_PORT,+ keyName = DEFAULT_KEY_NAME,+ ensureInstalled = ensureTailcatInstalled,+ primeDerpMap = primeDerpMapCache,+ ensureKey = ensureServeKey,+ startServe = startServeProcess,+ persist = patchServeEntry,+} = {}) {+ if (shuttingDown) throw new Error('PortOS is shutting down');++ const port = Number.isInteger(localPort) ? localPort : DEFAULT_LOCAL_PORT;+ const key = typeof keyName === 'string' && keyName ? keyName : DEFAULT_KEY_NAME;++ // Persist intent before spawn so a failed start stays retryable / restorable.+ await persist({+ enabled: true,+ status: 'pending',+ localPort: port,+ keyName: key,+ lastError: null,+ lastErrorAt: null,+ }).catch(() => {+ throw new ServerError('Could not save tailcat serve config; nothing was started', {+ status: 503, code: 'TAILCAT_SERVE_PERSIST_FAILED',+ });+ });++ if (liveServe?.child && !liveServe.child.killed+ && liveServe.localPort === port && liveServe.keyName === key) {+ const entry = await readServeEntry();+ await persist({+ enabled: true,+ status: 'active',+ localPort: port,+ keyName: key,+ tcAddress: entry?.tcAddress || null,+ lastError: null,+ lastErrorAt: null,+ });+ return getTailcatServeStatus();+ }++ killLiveServe();++ try {+ const { bin } = await ensureInstalled();+ await Promise.resolve().then(primeDerpMap).catch(() => null);+ await ensureKey({ bin, keyName: key });+ const started = await startServe({ bin, localPort: port, keyName: key });+ trackServe(started.child, started.localPort, started.keyName);+ await persist({+ enabled: true,+ status: 'active',+ localPort: started.localPort,+ keyName: started.keyName,+ tcAddress: started.tcAddress,+ lastError: null,+ lastErrorAt: null,+ });+ started.child.on('exit', () => {+ console.log(`🐈 tailcat serve stopped (${redactTcAddress(started.tcAddress)})`);+ });+ return getTailcatServeStatus();+ } catch (err) {+ await markServeFailed(err);+ throw err instanceof ServerError+ ? err+ : new ServerError(`Could not start tailcat serve: ${err.message}`, {+ status: 502, code: 'TAILCAT_SERVE_FAILED',+ });+ }+}++/** Restart serve from the saved config (or defaults). */+export function retryTailcatServe(options = {}) {+ return withLifecycle(async () => {+ const entry = await readServeEntry();+ killLiveServe();+ return ensureServe({+ localPort: entry?.localPort || DEFAULT_LOCAL_PORT,+ keyName: entry?.keyName || DEFAULT_KEY_NAME,+ ...options,+ });+ });+}++/**+ * Stop the live serve process. When `disable` is true (default), clear the+ * restore-on-boot flag so the next PortOS start leaves serve off.+ */+export function stopTailcatServe({ disable = true } = {}) {+ return withLifecycle(async () => {+ killLiveServe();+ const entry = await readServeEntry();+ if (!entry && !disable) {+ return getTailcatServeStatus();+ }+ await patchServeEntry({+ enabled: disable ? false : (entry?.enabled === true),+ status: 'stopped',+ localPort: entry?.localPort || DEFAULT_LOCAL_PORT,+ keyName: entry?.keyName || DEFAULT_KEY_NAME,+ tcAddress: entry?.tcAddress || null,+ lastError: null,+ lastErrorAt: null,+ });+ return getTailcatServeStatus();+ });+}++/** Restore serve after PortOS boot when the operator left it enabled. */+export function restoreServe(options = {}) {+ return withLifecycle(() => restoreTailcatServe(options));+}++async function restoreTailcatServe({+ ensureInstalled = ensureTailcatInstalled,+ primeDerpMap = primeDerpMapCache,+ ensureKey = ensureServeKey,+ startServe = startServeProcess,+} = {}) {+ if (shuttingDown) return { restored: false };+ const entry = await readServeEntry();+ if (!entry?.enabled) return { restored: false, reason: 'disabled' };+ if (liveServe) return { restored: false, reason: 'already-live' };++ try {+ const { bin } = await ensureInstalled();+ await Promise.resolve().then(primeDerpMap).catch(() => null);+ await ensureKey({ bin, keyName: entry.keyName });+ const started = await startServe({+ bin,+ localPort: entry.localPort,+ keyName: entry.keyName,+ });+ trackServe(started.child, started.localPort, started.keyName);+ await patchServeEntry({+ enabled: true,+ status: 'active',+ localPort: started.localPort,+ keyName: started.keyName,+ tcAddress: started.tcAddress || entry.tcAddress,+ lastError: null,+ lastErrorAt: null,+ });+ console.log(`🐈 Restored tailcat serve on :${started.localPort}`);+ return { restored: true };+ } catch (err) {+ console.log(`⚠️ tailcat serve restore failed — ${redactTailcatDiagnostics(err.message)}`);+ await markServeFailed(err);+ return { restored: false, error: redactTailcatDiagnostics(err.message) };+ }+}++/** Stop the serve child on PortOS shutdown; keep enabled metadata for next boot. */+export function stopServeProcess() {+ shuttingDown = true;+ killLiveServe();+}++// Test-only helpers+export function _resetLiveServeForTests() {+ stopServeProcess();+ shuttingDown = false;+ liveServe = null;+}++export function _liveServeForTests() {+ return liveServe;+}++export { DEFAULT_KEY_NAME, DEFAULT_LOCAL_PORT as DEFAULT_SERVE_PORT };diff --git a/server/services/tailcatServe.test.js b/server/services/tailcatServe.test.jsnew file mode 100644index 0000000000..a696cbb1b3--- /dev/null+++ b/server/services/tailcatServe.test.js@@ -0,0 +1,248 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'node:events';+import {+ parseServeListenAddr,+ ensureServeKey,+ startServeProcess,+ ensureTailcatServe,+ getTailcatServeStatus,+ stopTailcatServe,+ retryTailcatServe,+ restoreServe,+ _resetLiveServeForTests,+ _liveServeForTests,+ DEFAULT_KEY_NAME,+ DEFAULT_SERVE_PORT,+} from './tailcatServe.js';++vi.mock('../lib/fileUtils.js', async (original) => ({+ ...(await original()),+ readJSONFile: vi.fn(),+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+}));+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';++vi.mock('../lib/bufferedSpawn.js', async (original) => ({+ ...(await original()),+ bufferedSpawn: vi.fn(),+}));+import { bufferedSpawn } from '../lib/bufferedSpawn.js';++const EXAMPLE_TC = 'tcEXAMPLE' + 'C'.repeat(40);++function fakeChild() {+ const child = new EventEmitter();+ child.killed = false;+ child.stderr = new EventEmitter();+ child.stdout = new EventEmitter();+ child.kill = vi.fn(() => {+ child.killed = true;+ child.emit('exit', 0, null);+ });+ return child;+}++describe('tailcatServe helpers', () => {+ beforeEach(() => {+ _resetLiveServeForTests();+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ version: 1, serve: null });+ });++ afterEach(() => {+ _resetLiveServeForTests();+ });++ it('parses --json listenAddr and rejects placeholders', () => {+ expect(parseServeListenAddr(JSON.stringify({ listenAddr: EXAMPLE_TC }))).toBe(EXAMPLE_TC);+ expect(parseServeListenAddr(`noise\n{"listenAddr":"${EXAMPLE_TC}"}\n`)).toBe(EXAMPLE_TC);+ expect(parseServeListenAddr(EXAMPLE_TC)).toBe(EXAMPLE_TC);+ expect(parseServeListenAddr('tcEXAMPLE…')).toBe(null);+ expect(parseServeListenAddr('')).toBe(null);+ });++ it('ensureServeKey treats an existing key as success', async () => {+ bufferedSpawn.mockResolvedValue({+ success: false,+ code: 1,+ timedOut: false,+ stderr: 'key already exists; use --force to overwrite\n',+ stdout: '',+ });+ const result = await ensureServeKey({ bin: '/usr/bin/tailcat', keyName: 'portos-api' });+ expect(result).toMatchObject({ created: false, keyName: 'portos-api' });+ expect(bufferedSpawn).toHaveBeenCalledWith(+ '/usr/bin/tailcat',+ ['genkey', '--key=portos-api'],+ expect.any(Object),+ );+ });++ it('startServeProcess resolves when stdout prints listenAddr JSON', async () => {+ const child = fakeChild();+ const spawnFn = vi.fn(() => {+ queueMicrotask(() => child.stdout.emit('data', `${JSON.stringify({ listenAddr: EXAMPLE_TC })}\n`));+ return child;+ });+ const started = await startServeProcess({+ bin: '/usr/bin/tailcat',+ localPort: 5555,+ keyName: 'portos-api',+ spawnFn,+ readyMs: 2_000,+ readFileFn: async () => { throw new Error('no file'); },+ mkdirFn: async () => {},+ });+ expect(started.tcAddress).toBe(EXAMPLE_TC);+ expect(started.localPort).toBe(5555);+ expect(spawnFn).toHaveBeenCalledWith(+ '/usr/bin/tailcat',+ ['serve', '--verbose', '--full-address', '--json', '--key=portos-api', '5555'],+ expect.any(Object),+ );+ });++ it('ensureTailcatServe persists enabled config and returns copyable address', async () => {+ const child = fakeChild();+ let saved = null;+ atomicWrite.mockImplementation(async (_path, data) => { saved = data; });+ readJSONFile.mockImplementation(async () => saved || { version: 1, serve: null });++ const status = await ensureTailcatServe({+ ensureInstalled: async () => ({ bin: '/usr/bin/tailcat', installed: false }),+ primeDerpMap: async () => ({ primed: false }),+ ensureKey: async () => ({ created: true, keyName: DEFAULT_KEY_NAME }),+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }),+ });++ expect(status.live).toBe(true);+ expect(status.enabled).toBe(true);+ expect(status.tcAddress).toBe(EXAMPLE_TC);+ expect(status.hasAddress).toBe(true);+ expect(status.tcAddressRedacted).not.toBe(EXAMPLE_TC);+ expect(status.tcAddressRedacted).toContain('…');+ expect(_liveServeForTests()?.child).toBe(child);+ expect(saved?.serve?.enabled).toBe(true);+ expect(saved?.serve?.tcAddress).toBe(EXAMPLE_TC);+ });++ it('stopTailcatServe disables restore-on-boot', async () => {+ const child = fakeChild();+ let saved = {+ version: 1,+ serve: {+ enabled: true,+ status: 'active',+ localPort: 5555,+ keyName: 'portos-api',+ tcAddress: EXAMPLE_TC,+ lastError: null,+ lastErrorAt: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ };+ readJSONFile.mockImplementation(async () => saved);+ atomicWrite.mockImplementation(async (_path, data) => { saved = data; });++ await ensureTailcatServe({+ ensureInstalled: async () => ({ bin: '/x', installed: false }),+ primeDerpMap: async () => ({}),+ ensureKey: async () => ({ created: false, keyName: 'portos-api' }),+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),+ });+ expect(_liveServeForTests()).not.toBe(null);++ const stopped = await stopTailcatServe({ disable: true });+ expect(stopped.live).toBe(false);+ expect(stopped.enabled).toBe(false);+ expect(stopped.status).toBe('stopped');+ expect(child.kill).toHaveBeenCalled();+ expect(_liveServeForTests()).toBe(null);+ });++ it('restoreServe starts when enabled and skips when disabled', async () => {+ const child = fakeChild();+ readJSONFile.mockResolvedValue({+ version: 1,+ serve: {+ enabled: true,+ status: 'active',+ localPort: 5555,+ keyName: 'portos-api',+ tcAddress: EXAMPLE_TC,+ lastError: null,+ lastErrorAt: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ });+ atomicWrite.mockResolvedValue(undefined);++ const ok = await restoreServe({+ ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),+ primeDerpMap: async () => ({}),+ ensureKey: async () => ({ created: false, keyName: 'portos-api' }),+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),+ });+ expect(ok).toEqual({ restored: true });+ expect(_liveServeForTests()?.child).toBe(child);++ _resetLiveServeForTests();+ readJSONFile.mockResolvedValue({ version: 1, serve: { enabled: false, status: 'stopped', localPort: 5555, keyName: 'portos-api', tcAddress: null } });+ const skipped = await restoreServe({+ ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),+ startServe: async () => { throw new Error('should not run'); },+ });+ expect(skipped).toMatchObject({ restored: false, reason: 'disabled' });+ });++ it('retryTailcatServe kills a live child then restarts', async () => {+ const first = fakeChild();+ const second = fakeChild();+ let saved = {+ version: 1,+ serve: {+ enabled: true,+ status: 'failed',+ localPort: 5555,+ keyName: 'portos-api',+ tcAddress: EXAMPLE_TC,+ lastError: 'boom',+ lastErrorAt: '2026-01-01T00:00:00.000Z',+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ };+ readJSONFile.mockImplementation(async () => saved);+ atomicWrite.mockImplementation(async (_path, data) => { saved = data; });++ // Seed a live child by ensuring once.+ await ensureTailcatServe({+ ensureInstalled: async () => ({ bin: '/x' }),+ primeDerpMap: async () => ({}),+ ensureKey: async () => ({ created: false, keyName: 'portos-api' }),+ startServe: async () => ({ child: first, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),+ });++ const status = await retryTailcatServe({+ ensureInstalled: async () => ({ bin: '/x' }),+ primeDerpMap: async () => ({}),+ ensureKey: async () => ({ created: false, keyName: 'portos-api' }),+ startServe: async () => ({ child: second, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),+ });+ expect(first.kill).toHaveBeenCalled();+ expect(status.live).toBe(true);+ expect(_liveServeForTests()?.child).toBe(second);+ });++ it('getTailcatServeStatus never invents a live process', async () => {+ const status = await getTailcatServeStatus();+ expect(status).toMatchObject({+ enabled: false,+ live: false,+ localPort: DEFAULT_SERVE_PORT,+ keyName: DEFAULT_KEY_NAME,+ hasAddress: false,+ tcAddress: null,+ });+ });+});