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 peer card forward status + probe diagnostics (#6478)
atomanticagent9806d3d48e87
diff --git a/client/src/components/instances/TailcatForwardStatus.jsx b/client/src/components/instances/TailcatForwardStatus.jsxnew file mode 100644index 0000000000..db3a66f21e--- /dev/null+++ b/client/src/components/instances/TailcatForwardStatus.jsx@@ -0,0 +1,100 @@+/**+ * Shared Tailcat forward status row — used on the federated peer card (primary)+ * and on the orphan/pre-peer TailcatForwardsPanel (secondary).+ *+ * Distinguishes listener-bound ("running") from tunnel-broken ("no route").+ * Never receives a full tc… capability — only the redacted listing fields.+ */++import { RefreshCw, Trash2, CheckCircle2, AlertCircle, Clock } from 'lucide-react';+import Pill from '../ui/Pill';+import { timeAgo } from '../../utils/formatters';++const STATUS_TONE = { active: 'success', pending: 'muted', failed: 'warning' };+const STATUS_ICON = { active: CheckCircle2, pending: Clock, failed: AlertCircle };++export function forwardDisplayState(forward) {+ if (!forward) return { label: 'no forward', tone: 'muted', broken: false };+ const broken = forward.live && !!forward.tunnelError;+ if (broken) return { label: 'no route', tone: 'warning', broken: true };+ if (forward.live) return { label: 'running', tone: STATUS_TONE[forward.status] || 'success', broken: false };+ return {+ label: forward.status || 'unknown',+ tone: STATUS_TONE[forward.status] || 'bare',+ broken: false,+ };+}++export function TailcatForwardStatus({+ forward,+ busy = false,+ onRetry,+ onForget,+ compact = false,+ showForget = true,+}) {+ if (!forward) {+ return (+ <div className="mt-2 text-[11px] text-gray-500 leading-snug">+ No saved Tailcat forward for this peer.+ </div>+ );+ }++ const { label, tone, broken } = forwardDisplayState(forward);+ const StatusIcon = broken ? AlertCircle : (STATUS_ICON[forward.status] || Clock);+ const failure = broken+ ? { message: forward.tunnelError, at: forward.tunnelErrorAt }+ : (forward.status !== 'active' && forward.lastError+ ? { message: forward.lastError, at: forward.lastErrorAt }+ : null);++ return (+ <div className={compact ? 'mt-2' : '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">+ {forward.localPort ? `127.0.0.1:${forward.localPort}` : 'no port yet'}+ {' → '}:{forward.remotePort}+ </span>+ {(onRetry || onForget) && (+ <div className="ml-auto flex items-center gap-1">+ {onRetry && (+ <button+ type="button"+ onClick={onRetry}+ disabled={busy}+ title="Restart this forward using the saved tc address"+ 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"+ >+ <RefreshCw size={11} className={busy ? 'animate-spin' : ''} />+ {busy ? 'Working...' : 'Retry'}+ </button>+ )}+ {showForget && onForget && (+ <button+ type="button"+ onClick={onForget}+ disabled={busy}+ title="Stop the forward, delete its saved address, and remove its peer"+ 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"+ >+ <Trash2 size={11} /> Forget+ </button>+ )}+ </div>+ )}+ </div>+ {failure && (+ <p className="text-[11px] text-port-error mt-2 leading-snug break-words">+ {failure.message}+ {failure.at && <span className="text-gray-500"> · {timeAgo(failure.at)}</span>}+ </p>+ )}+ </div>+ );+}++export default TailcatForwardStatus;diff --git a/client/src/components/instances/TailcatForwardsPanel.jsx b/client/src/components/instances/TailcatForwardsPanel.jsxindex 02d8ad4ce3..ad390ebbf8 100644--- a/client/src/components/instances/TailcatForwardsPanel.jsx+++ b/client/src/components/instances/TailcatForwardsPanel.jsx@@ -1,40 +1,31 @@/**- * Saved tailcat forwards.+ * Orphan / pre-peer Tailcat forwards only.*- * A tc address is a bearer capability the operator receives out of band, and it- * only ever existed in the Add Peer field. When the forward failed to start,- * that pasted value was gone — so recovering meant going back to the remote for- * a fresh address before anyone could even retry. PortOS now saves the- * capability (machine-local) the moment an add begins, and this panel is what- * makes that recoverable: it names which forward is down, what tailcat actually- * said, and offers Retry without the address ever coming back to the browser.- *- * It also separates "the listener is bound" from "the tunnel can carry a- * request". tailcat binds its loopback port eagerly and only dials the remote- * once traffic arrives, so a forward whose relay is blocked stays `active` and- * `running` while every request through it is reset — which reads as a working- * loopback that simply refuses to answer.+ * When a forward is linked to a federated peer (`peerId`), its status lives on+ * that peer card — the primary source of truth. This panel keeps the salvage+ * surface for a forward that failed before peer registration (or whose peer+ * was removed), so a saved tc… capability can still be retried without pasting+ * the address again.** Rows carry only the redacted address. Nothing here can reveal the capability.*/-import { useCallback, useEffect, useState } from 'react';-import { RefreshCw, Trash2, CheckCircle2, AlertCircle, Clock } from 'lucide-react';+import { useCallback, useEffect, useMemo, useState } from 'react';import toast from '../ui/Toast';-import Pill from '../ui/Pill';import { getTailcatForwards, retryTailcatForward, forgetTailcatForward } from '../../services/api';-import { timeAgo } from '../../utils/formatters';--// Pill has no `error` tone; the red lastError line below carries the severity.-const STATUS_TONE = { active: 'success', pending: 'muted', failed: 'warning' };-const STATUS_ICON = { active: CheckCircle2, pending: Clock, failed: AlertCircle };+import TailcatForwardStatus from './TailcatForwardStatus';-export default function TailcatForwardsPanel({ onChange }) {+export default function TailcatForwardsPanel({ onChange, peerIds }) {// `null` = not loaded yet, `[]` = loaded and genuinely empty. Distinct so a// pending fetch never renders as "no forwards".const [forwards, setForwards] = useState(null);const [busyId, setBusyId] = useState(null);+ const peerIdSet = useMemo(() => {+ if (!peerIds) return null;+ return peerIds instanceof Set ? peerIds : new Set(peerIds);+ }, [peerIds]);+const load = useCallback(async () => {// An install that has never added a tailcat peer is the common case — not// something to toast about on every Instances load.@@ -44,6 +35,15 @@ export default function TailcatForwardsPanel({ onChange }) {useEffect(() => { load(); }, [load]);+ const orphans = useMemo(() => {+ if (!forwards) return null;+ return forwards.filter((f) => {+ if (!f.peerId) return true;+ if (!peerIdSet) return false; // linked forward; peer card owns it+ return !peerIdSet.has(f.peerId);+ });+ }, [forwards, peerIdSet]);+const retry = async (id) => {setBusyId(id);const peer = await retryTailcatForward(id).catch(() => null);@@ -67,80 +67,32 @@ export default function TailcatForwardsPanel({ onChange }) {toast.success('Tailcat forward and its saved address removed');};- if (!forwards || forwards.length === 0) return null;+ if (!orphans || orphans.length === 0) return null;return (<div className="bg-port-card border border-port-border rounded-xl p-5"><h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-1">- Tailcat forwards ({forwards.length})+ Tailcat forwards — needs attention ({orphans.length})</h2><p className="text-[11px] text-gray-500 mb-3 leading-snug">- Saved on this machine only, so a forward that fails to start can be retried- without pasting its <span className="font-mono">tc…</span> address again.+ Orphaned or pre-peer forwards only. Linked Tailcat peers show forward+ status on their card. Saved on this machine so a failed start can be+ retried without pasting its <span className="font-mono">tc…</span> address again.</p><ul className="space-y-2">- {forwards.map(forward => {- // A bound listener is not a working tunnel: tailcat binds eagerly and- // only dials the remote when a request arrives, so a forward whose- // relay is blocked reports `active`/`running` while every request- // through it is reset. Show that as its own state instead of green.- const broken = forward.live && !!forward.tunnelError;- const StatusIcon = broken ? AlertCircle : (STATUS_ICON[forward.status] || Clock);- const busy = busyId === forward.id;- const failure = broken- ? { message: forward.tunnelError, at: forward.tunnelErrorAt }- : (forward.status !== 'active' && forward.lastError- ? { message: forward.lastError, at: forward.lastErrorAt }- : null);- return (- <li key={forward.id} className="bg-port-bg border border-port-border rounded-lg p-3">- <div className="flex flex-wrap items-center gap-2">- <Pill- tone={broken ? 'warning' : (STATUS_TONE[forward.status] || 'bare')}- size="xs"- bordered={false}- icon={StatusIcon}- >- {broken ? 'no route' : (forward.live ? 'running' : forward.status)}- </Pill>- <span className="text-sm text-white truncate">- {forward.name || forward.tcAddress}- </span>- <span className="text-[11px] font-mono text-gray-500">- {forward.localPort ? `127.0.0.1:${forward.localPort}` : 'no port yet'}- {' → '}:{forward.remotePort}- </span>- <div className="ml-auto flex items-center gap-1">- <button- type="button"- onClick={() => retry(forward.id)}- disabled={busy}- title="Restart this forward using the saved tc address"- 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"- >- <RefreshCw size={11} className={busy ? 'animate-spin' : ''} />- {busy ? 'Working...' : 'Retry'}- </button>- <button- type="button"- onClick={() => forget(forward.id)}- disabled={busy}- title="Stop the forward, delete its saved address, and remove its peer"- 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"- >- <Trash2 size={11} /> Forget- </button>- </div>- </div>- {failure && (- <p className="text-[11px] text-port-error mt-2 leading-snug break-words">- {failure.message}- {failure.at && <span className="text-gray-500"> · {timeAgo(failure.at)}</span>}- </p>- )}- </li>- );- })}+ {orphans.map(forward => (+ <li key={forward.id}>+ <div className="mb-1 text-sm text-white truncate">+ {forward.name || forward.tcAddress}+ </div>+ <TailcatForwardStatus+ forward={forward}+ busy={busyId === forward.id}+ onRetry={() => retry(forward.id)}+ onForget={() => forget(forward.id)}+ />+ </li>+ ))}</ul></div>);diff --git a/client/src/components/instances/TailcatForwardsPanel.test.jsx b/client/src/components/instances/TailcatForwardsPanel.test.jsxindex ad94c99221..dd53782f7a 100644--- a/client/src/components/instances/TailcatForwardsPanel.test.jsx+++ b/client/src/components/instances/TailcatForwardsPanel.test.jsx@@ -32,6 +32,18 @@ const failedForward = {live: false,};+const linkedForward = {+ ...failedForward,+ id: 'fwd_linked',+ peerId: 'peer-grokbot',+ name: 'grokbot',+ status: 'active',+ localPort: 15555,+ live: true,+ lastError: null,+ lastErrorAt: null,+};+describe('TailcatForwardsPanel', () => {beforeEach(() => {vi.clearAllMocks();@@ -45,6 +57,14 @@ describe('TailcatForwardsPanel', () => {expect(container).toBeEmptyDOMElement();});+ it('hides forwards that already belong to a peer card', async () => {+ getTailcatForwards.mockResolvedValue({ forwards: [linkedForward, failedForward] });+ render(<TailcatForwardsPanel peerIds={['peer-grokbot']} />);+ expect(await screen.findByText('sandbox')).toBeInTheDocument();+ expect(screen.queryByText('grokbot')).not.toBeInTheDocument();+ expect(screen.getByText(/needs attention/)).toBeInTheDocument();+ });+it('surfaces what tailcat actually said, which is the whole point of saving the forward', async () => {render(<TailcatForwardsPanel />);expect(await screen.findByText(/context deadline exceeded/)).toBeInTheDocument();diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 0f01ce790b..a6d8be8fcc 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -20,6 +20,7 @@ import {listPeerSubscriptions,getPeerFullSyncCoverage,getBrainParityReports,+ retryTailcatForward, forgetTailcatForward,} from '../services/api';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';@@ -31,6 +32,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 TailcatForwardStatus from '../components/instances/TailcatForwardStatus';import { timeAgo, timeUntil } from '../utils/formatters';import { directionalCounts, describeDirectional } from '../lib/syncCounts';import PageSkeleton from '../components/ui/PageSkeleton';@@ -1052,10 +1054,50 @@ function PeerAuthEditor({ peer, onRefresh }) {);}+function ProbeDiagnostics({ peer, probing, onProbe }) {+ const last = peer.lastProbe;+ return (+ <div className="mt-2 rounded-lg border border-port-border bg-port-bg/60 p-2.5">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Health check</span>+ <button+ type="button"+ onClick={onProbe}+ disabled={probing}+ className="inline-flex items-center gap-1 text-[11px] text-port-accent hover:text-white disabled:opacity-50 border border-port-accent/40 rounded px-2 py-1 transition-colors"+ title="Force an immediate health/details probe"+ >+ <RefreshCw size={11} className={probing ? 'animate-spin' : ''} />+ {probing ? 'Checking…' : 'Check now'}+ </button>+ </div>+ {last ? (+ <p className={`mt-1.5 text-[11px] leading-snug break-words ${last.ok ? 'text-port-success' : 'text-port-warning'}`}>+ {last.ok ? 'ok' : (last.class || 'failed')}+ {last.httpStatus != null && ` · HTTP ${last.httpStatus}`}+ {last.latencyMs != null && ` · ${last.latencyMs}ms`}+ {last.at && ` · ${timeAgo(last.at)}`}+ {!last.ok && last.message && (+ <span className="block text-gray-400 mt-0.5">{last.message}</span>+ )}+ {peer.consecutiveFailures > 0 && peer.nextProbeAt && (+ <span className="block text-gray-500 mt-0.5">+ next probe {timeUntil(peer.nextProbeAt) ?? '—'}+ </span>+ )}+ </p>+ ) : (+ <p className="mt-1.5 text-[11px] text-gray-500">No probe result yet — run a health check.</p>+ )}+ </div>+ );+}+function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {const [editingName, setEditingName] = useState(false);const [name, setName] = useState('');const [probing, setProbing] = useState(false);+ const [forwardBusy, setForwardBusy] = useState(false);const [connecting, setConnecting] = useState(false);const [confirmRemove, setConfirmRemove] = useState(false);// Peer subs are loaded once at this level and shared with SchemaGapBadge and@@ -1166,9 +1208,42 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {const handleProbe = async () => {setProbing(true);- await probePeer(peer.id).catch(() => null);+ const result = await probePeer(peer.id).catch(() => null);onRefresh();setProbing(false);+ if (!result) {+ toast.error(`Health check failed for ${peer.name}`);+ return;+ }+ if (result.status === 'online') {+ const ms = result.lastProbe?.latencyMs;+ toast.success(`Health check ok${ms != null ? ` (${ms}ms)` : ''}`);+ } else {+ const detail = result.lastProbe?.message || result.lastProbe?.class || 'offline';+ toast.error(`Health check: ${detail}`);+ }+ };++ const handleForwardRetry = async () => {+ const forwardId = peer.tailcatForward?.id;+ if (!forwardId) return;+ setForwardBusy(true);+ const updated = await retryTailcatForward(forwardId).catch(() => null);+ setForwardBusy(false);+ onRefresh();+ if (!updated) return;+ toast.success(`Tailcat forward restarted on 127.0.0.1:${updated.port}`);+ };++ const handleForwardForget = async () => {+ const forwardId = peer.tailcatForward?.id;+ if (!forwardId) return;+ setForwardBusy(true);+ const removed = await forgetTailcatForward(forwardId).catch(() => null);+ setForwardBusy(false);+ if (!removed) return;+ onRefresh();+ toast.success('Tailcat forward and peer removed');};const handleSync = async () => {@@ -1305,8 +1380,23 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {<PeerAuthEditor peer={peer} onRefresh={onRefresh} /></div>+ {peer.transport === 'tailcat' && (+ <div className="mb-2">+ <div className="text-[11px] uppercase tracking-wider text-gray-500 mb-1">Tailcat forward</div>+ <TailcatForwardStatus+ forward={peer.tailcatForward}+ busy={forwardBusy}+ onRetry={peer.tailcatForward?.id ? handleForwardRetry : undefined}+ onForget={peer.tailcatForward?.id ? handleForwardForget : undefined}+ compact+ />+ </div>+ )}+<HealthSummary health={peer.lastHealth} version={peer.version} />+ <ProbeDiagnostics peer={peer} probing={probing} onProbe={handleProbe} />+<div className="mt-2 text-xs text-gray-600">Last seen: {timeAgo(peer.lastSeen)}</div>@@ -1433,7 +1523,7 @@ 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. */}- <TailcatForwardsPanel onChange={fetchData} />+ <TailcatForwardsPanel onChange={fetchData} peerIds={peers.map((p) => p.id)} />{peers.length > 0 && (<div>diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsxindex b1e2ca8df9..ea9acfec59 100644--- a/client/src/pages/Instances.test.jsx+++ b/client/src/pages/Instances.test.jsx@@ -20,6 +20,9 @@ vi.mock('../services/api', () => ({listPeerSubscriptions: vi.fn(),getPeerFullSyncCoverage: vi.fn(),getBrainParityReports: vi.fn(),+ getTailcatForwards: vi.fn().mockResolvedValue({ forwards: [] }),+ retryTailcatForward: vi.fn(),+ forgetTailcatForward: vi.fn(),}));vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.mdindex b14b6e3590..d585228744 100644--- a/docs/features/tailcat-peers.md+++ b/docs/features/tailcat-peers.md@@ -77,9 +77,28 @@ even retry.| `POST …/forwards/:id/retry` | Restarts from the stored capability, registering the peer if the original add never got that far, and repointing an existing peer when a retry has to bind a different local port. || `DELETE …/forwards/:id` | Stops the forward, deletes the stored capability, and removes its peer. |-The Instances page renders these as **Tailcat forwards**, with Retry and Forget-per row. A boot-time restore failure lands on the same row, so the one case-nobody is watching still surfaces somewhere actionable.+Linked forwards (`peerId` set) render on the **federated peer card** — mapping,+live/running/no-route/failed, `tunnelError`, Retry, and Forget — so the card is+the primary source of truth. The standalone **Tailcat forwards** panel only+lists **orphans / pre-peer failures** (no peer yet, or peer gone), still with+Retry and Forget. A boot-time restore failure lands there when it never+registered a peer, so the one case nobody is watching still surfaces somewhere+actionable.++Each peer card also exposes a **Health check** control that forces+`POST /api/instances/peers/:id/probe` and shows the last probe result+(`lastProbe`: class, message, HTTP status, latency, timestamp) plus+`nextProbeAt`. Probe classification distinguishes:++| Class | Meaning |+| --- | --- |+| `local_refused` | Loopback connection refused — the forward is not listening |+| `tunnel_dial` | Listener up but tunnel cannot dial (uses `tunnelError` when present) |+| `probe_http` / `probe_timeout` / `auth_required` | Tunnel carried bytes (or timed out) but `/api/system/health/details` failed |++`GET /api/instances` attaches `tailcatForward` onto `transport: 'tailcat'` peers+(redacted listing fields only). Server logs include the structured class, e.g.+`[local_refused] …`.### Startup readiness has two independent signalsdiff --git a/server/lib/README.md b/server/lib/README.mdindex 2a95dad820..6433abdfa8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -364,6 +364,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). || `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. || `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |+| `peerProbeDiagnostics.js` | Classify federated peer probe failures (`local_refused` / `tunnel_dial` / `probe_http` / timeout / auth / DNS) so Instances UI and logs can tell a dead local forward from a tunnel dial miss from a PortOS health-details failure; messages stay redacted (no full `tc…` capabilities). || `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. || `peerUrl.js` | Build the base URL for a peer. || `sharingOrigin.js` | Origin metadata for records imported from share buckets. |diff --git a/server/lib/index.js b/server/lib/index.jsindex be77a02957..01e258eda3 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -342,6 +342,7 @@ export * from './httpsState.js';export * from './isSafeHref.js';export * from './networkExposure.js';export * from './peerHttpClient.js';+export * from './peerProbeDiagnostics.js';export * from './peerSelfHost.js';export * from './peerUrl.js';export * from './pinterestFeed.js';diff --git a/server/lib/peerProbeDiagnostics.js b/server/lib/peerProbeDiagnostics.jsnew file mode 100644index 0000000000..18e7c99c19--- /dev/null+++ b/server/lib/peerProbeDiagnostics.js@@ -0,0 +1,160 @@+/**+ * Classify why a federated peer probe failed so operators (and logs) can tell+ * "local forward not listening" apart from "tunnel cannot dial" apart from+ * "tunnel carried bytes but /api/system/health/details failed".+ *+ * Messages must never include a full tc… capability — callers pass already-+ * redacted tunnelError text from listTailcatForwards / redactTailcatDiagnostics.+ */++export const PROBE_CLASS = Object.freeze({+ OK: 'ok',+ LOCAL_REFUSED: 'local_refused',+ TUNNEL_DIAL: 'tunnel_dial',+ PROBE_HTTP: 'probe_http',+ PROBE_TIMEOUT: 'probe_timeout',+ AUTH_REQUIRED: 'auth_required',+ DNS: 'dns',+ HOST_UNREACHABLE: 'host_unreachable',+ UNKNOWN: 'unknown',+});++const TUNNEL_DIAL_HINT = /dial remote|context deadline exceeded|connection reset|socket hang up|ECONNRESET|recv failure/i;++/**+ * @param {Error|object|null} err+ * @param {{ peer?: object, tunnelError?: string|null, probeTimeoutMs?: number }} [ctx]+ * @returns {{ class: string, message: string, httpStatus: number|null }}+ */+export function classifyPeerProbeFailure(err, { peer = null, tunnelError = null, probeTimeoutMs = 10_000 } = {}) {+ const httpStatus = Number.isFinite(err?.httpStatus) ? err.httpStatus : null;+ const code = err?.code;+ const rawMessage = err?.message || String(err || 'unknown error');+ const isTailcat = peer?.transport === 'tailcat';++ if (httpStatus === 401 || httpStatus === 403) {+ return {+ class: PROBE_CLASS.AUTH_REQUIRED,+ message: `Authentication required (HTTP ${httpStatus}) — set a username/password for this peer in the Instances UI`,+ httpStatus,+ };+ }++ // Fresh tunnel dial failure from the live tailcat child — prefer that over a+ // generic timeout/reset, which is how the same failure usually surfaces to fetch.+ if (isTailcat && tunnelError) {+ return {+ class: PROBE_CLASS.TUNNEL_DIAL,+ message: `Tunnel dial failure — ${tunnelError}`,+ httpStatus,+ };+ }++ if (code === 'ENOTFOUND') {+ return {+ class: PROBE_CLASS.DNS,+ message: `DNS lookup failed for ${peer?.host || peer?.address || 'peer'} — is Tailscale MagicDNS up?`,+ httpStatus,+ };+ }++ if (code === 'ECONNREFUSED') {+ if (isTailcat) {+ return {+ class: PROBE_CLASS.LOCAL_REFUSED,+ message: 'Local connection refused — tailcat forward is not listening on this loopback port',+ httpStatus,+ };+ }+ return {+ class: PROBE_CLASS.LOCAL_REFUSED,+ message: 'Connection refused — peer not running on this port',+ httpStatus,+ };+ }++ if (code === 'EHOSTUNREACH') {+ return {+ class: PROBE_CLASS.HOST_UNREACHABLE,+ message: 'Host unreachable — Tailscale tunnel down or peer offline',+ httpStatus,+ };+ }++ const timedOut = code === 'ETIMEDOUT'+ || err?.name === 'AbortError'+ || err?.message === 'Request aborted';+ if (timedOut) {+ if (isTailcat && TUNNEL_DIAL_HINT.test(rawMessage)) {+ return {+ class: PROBE_CLASS.TUNNEL_DIAL,+ message: `Tunnel dial failure — probe timed out (${probeTimeoutMs}ms); remote may be unreachable through the forward`,+ httpStatus,+ };+ }+ return {+ class: PROBE_CLASS.PROBE_TIMEOUT,+ message: `Probe timeout (${probeTimeoutMs}ms)`,+ httpStatus,+ };+ }++ if (isTailcat && (code === 'ECONNRESET' || TUNNEL_DIAL_HINT.test(rawMessage))) {+ return {+ class: PROBE_CLASS.TUNNEL_DIAL,+ message: `Tunnel dial failure — ${rawMessage}`,+ httpStatus,+ };+ }++ if (httpStatus != null) {+ return {+ class: PROBE_CLASS.PROBE_HTTP,+ message: isTailcat+ ? `Tunnel reachable but health/details probe failed (HTTP ${httpStatus})`+ : `HTTP ${httpStatus}`,+ httpStatus,+ };+ }++ return {+ class: PROBE_CLASS.UNKNOWN,+ message: rawMessage,+ httpStatus,+ };+}++/**+ * Operator-facing lastProbe payload persisted on the peer record.+ * @returns {{ ok: boolean, class: string, message: string|null, httpStatus: number|null, latencyMs: number|null, at: string }}+ */+export function buildLastProbeRecord({ ok, classification = null, latencyMs = null, at = new Date().toISOString() } = {}) {+ if (ok) {+ return {+ ok: true,+ class: PROBE_CLASS.OK,+ message: null,+ httpStatus: classification?.httpStatus ?? 200,+ latencyMs: latencyMs == null ? null : Math.max(0, Math.round(latencyMs)),+ at,+ };+ }+ return {+ ok: false,+ class: classification?.class || PROBE_CLASS.UNKNOWN,+ message: classification?.message || 'Probe failed',+ httpStatus: classification?.httpStatus ?? null,+ latencyMs: latencyMs == null ? null : Math.max(0, Math.round(latencyMs)),+ at,+ };+}++/** One-line log fragment: `[local_refused] Local connection refused…` */+export function formatProbeDiagnosticLog(lastProbe) {+ if (!lastProbe) return 'unknown';+ if (lastProbe.ok) {+ const ms = lastProbe.latencyMs != null ? ` ${lastProbe.latencyMs}ms` : '';+ return `[ok]${ms}`;+ }+ return `[${lastProbe.class || 'unknown'}] ${lastProbe.message || 'Probe failed'}`;+}diff --git a/server/lib/peerProbeDiagnostics.test.js b/server/lib/peerProbeDiagnostics.test.jsnew file mode 100644index 0000000000..f52c0c8486--- /dev/null+++ b/server/lib/peerProbeDiagnostics.test.js@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import {+ PROBE_CLASS,+ classifyPeerProbeFailure,+ buildLastProbeRecord,+ formatProbeDiagnosticLog,+} from './peerProbeDiagnostics.js';++describe('classifyPeerProbeFailure', () => {+ const tailcatPeer = { transport: 'tailcat', address: '127.0.0.1', port: 15555 };++ it('marks loopback ECONNREFUSED on a tailcat peer as local_refused', () => {+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' });+ const result = classifyPeerProbeFailure(err, { peer: tailcatPeer });+ expect(result.class).toBe(PROBE_CLASS.LOCAL_REFUSED);+ expect(result.message).toMatch(/forward is not listening/i);+ });++ it('prefers a live tunnelError over a generic timeout', () => {+ const err = Object.assign(new Error('Request aborted'), { name: 'AbortError' });+ const result = classifyPeerProbeFailure(err, {+ peer: tailcatPeer,+ tunnelError: 'dial remote port 5555: context deadline exceeded',+ });+ expect(result.class).toBe(PROBE_CLASS.TUNNEL_DIAL);+ expect(result.message).toMatch(/Tunnel dial failure/);+ expect(result.message).toMatch(/dial remote port 5555/);+ });++ it('classifies HTTP health/details failures as probe_http when the tunnel carried bytes', () => {+ const err = Object.assign(new Error('HTTP 502'), { httpStatus: 502 });+ const result = classifyPeerProbeFailure(err, { peer: tailcatPeer });+ expect(result.class).toBe(PROBE_CLASS.PROBE_HTTP);+ expect(result.message).toMatch(/health\/details/);+ expect(result.httpStatus).toBe(502);+ });++ it('does not invent tunnel_dial for classic peers', () => {+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' });+ const result = classifyPeerProbeFailure(err, {+ peer: { address: '10.0.0.1', port: 5555 },+ });+ expect(result.class).toBe(PROBE_CLASS.LOCAL_REFUSED);+ expect(result.message).toMatch(/peer not running/);+ });+});++describe('buildLastProbeRecord / formatProbeDiagnosticLog', () => {+ it('records latency and class for a failed probe', () => {+ const last = buildLastProbeRecord({+ ok: false,+ classification: { class: PROBE_CLASS.TUNNEL_DIAL, message: 'Tunnel dial failure — dial remote', httpStatus: null },+ latencyMs: 12.6,+ at: '2026-01-01T00:00:00.000Z',+ });+ expect(last).toMatchObject({+ ok: false,+ class: 'tunnel_dial',+ latencyMs: 13,+ at: '2026-01-01T00:00:00.000Z',+ });+ expect(formatProbeDiagnosticLog(last)).toMatch(/\[tunnel_dial\]/);+ });++ it('records ok probes without a failure message', () => {+ const last = buildLastProbeRecord({ ok: true, latencyMs: 40 });+ expect(last).toMatchObject({ ok: true, class: 'ok', message: null, httpStatus: 200 });+ expect(formatProbeDiagnosticLog(last)).toBe('[ok] 40ms');+ });+});diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 44076a3224..36f04f7149 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -128,7 +128,12 @@ router.get('/', asyncHandler(async (req, res) => {]);// Redact each peer's stored proxy password (keep username + hasPassword) —// the browser never needs the secret. Mirrors providers' hasApiKey pattern.- res.json({ self, peers: peers.map(instances.sanitizePeerForClient), syncStatus });+ // Tailcat peers also carry their live forward summary so the peer card is the+ // primary status surface (orphan forwards stay on the dedicated panel).+ const sanitized = await tailcatPeer.attachTailcatForwardsToPeers(+ peers.map(instances.sanitizePeerForClient),+ );+ res.json({ self, peers: sanitized, syncStatus });}));// GET /api/instances/assignable — id/name pairs a CoS task may be pinned to@@ -367,7 +372,8 @@ router.post('/peers/:id/probe', asyncHandler(async (req, res) => {const peer = peers.find(p => p.id === req.params.id);if (!peer) throw new ServerError('Peer not found', { status: 404 });const result = await instances.probePeer(peer);- res.json(instances.sanitizePeerForClient(result));+ const sanitized = instances.sanitizePeerForClient(result);+ res.json(await tailcatPeer.attachTailcatForwardToPeer(sanitized));}));// POST /api/instances/peers/:id/sync — force an immediate sync with this peer.diff --git a/server/services/instances.js b/server/services/instances.jsindex 4d5a92ff9e..a4fc512adc 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -26,6 +26,11 @@ import {normalizePeerMediaProviderConfig,probeFederatedMediaProvider,} from './federatedMediaConsumer.js';+import {+ classifyPeerProbeFailure,+ buildLastProbeRecord,+ formatProbeDiagnosticLog,+} from '../lib/peerProbeDiagnostics.js';const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;@@ -68,22 +73,33 @@ let pollingStartPending = false;// was requested.let pollingGeneration = 0;-function classifyProbeError(err, peer) {- const code = err?.code;- if (code === 'ENOTFOUND') return `🌐 ❌ DNS lookup failed for ${peer.host || peer.address} — is Tailscale MagicDNS up?`;- if (code === 'ECONNREFUSED') return `🌐 ❌ Connection refused — peer not running on this port`;- if (code === 'EHOSTUNREACH') return `🌐 ❌ Host unreachable — Tailscale tunnel down or peer offline`;- // Native fetch raises AbortError when the AbortSignal fires; insecureFetch- // (used for HTTPS peer hops via peerFetch) destroys the request with a- // plain `new Error('Request aborted')` instead — both are timeouts here.- if (code === 'ETIMEDOUT' || err?.name === 'AbortError' || err?.message === 'Request aborted') return `🌐 ⏱️ Probe timeout (${PROBE_TIMEOUT_MS}ms)`;- // The peer is reachable but gated by an auth proxy (Tailscale serve, Caddy,- // nginx Basic auth). Point the user at the per-peer credential field rather- // than letting it read like a generic failure.- if (err?.httpStatus === 401 || err?.httpStatus === 403) {- return `🔒 Authentication required (HTTP ${err.httpStatus}) — set a username/password for this peer in the Instances UI`;+function classifyProbeError(err, peer, tunnelError = null) {+ const classified = classifyPeerProbeFailure(err, {+ peer,+ tunnelError,+ probeTimeoutMs: PROBE_TIMEOUT_MS,+ });+ // Keep emoji prefixes for classic log grepping; structured class is on lastProbe.+ if (classified.class === 'dns') return `🌐 ❌ ${classified.message}`;+ if (classified.class === 'local_refused') return `🌐 ❌ ${classified.message}`;+ if (classified.class === 'host_unreachable') return `🌐 ❌ ${classified.message}`;+ if (classified.class === 'probe_timeout') return `🌐 ⏱️ ${classified.message}`;+ if (classified.class === 'tunnel_dial') return `🐈 ❌ ${classified.message}`;+ if (classified.class === 'auth_required') return `🔒 ${classified.message}`;+ if (classified.class === 'probe_http') return `🌐 ❌ ${classified.message}`;+ return classified.message;+}++/** Best-effort live forward hint for a tailcat peer (dynamic import avoids a cycle). */+async function lookupTailcatForwardHint(peer) {+ if (peer?.transport !== 'tailcat') return null;+ try {+ const { listTailcatForwards } = await import('./tailcatPeer.js');+ const forwards = await listTailcatForwards();+ return forwards.find((f) => f.peerId === peer.id) || null;+ } catch {+ return null;}- return err?.message || String(err);}// Normalize a credential object off a peer add/update payload. Returns:@@ -794,6 +810,13 @@ export async function probePeer(peer) {// opposed to an unreachable one. The Instances UI reads this to prompt for a// credential instead of showing a generic offline state.let authRequired = false;+ let probeFailure = null;+ const probeStartedAt = Date.now();+ // For tailcat peers, read the live forward's tunnelError up front so a probe+ // that times out / resets can be classified as tunnel dial vs local refuse vs+ // PortOS health/details failure — the three operator-visible cases.+ const forwardHint = await lookupTailcatForwardHint(peer);+ const tunnelError = forwardHint?.tunnelError || null;// One shared abort signal spans the instanceId read, all three parallel// fetches, AND their body reads, so a single PROBE_TIMEOUT_MS bounds the whole// probe (the instanceId read is inside the budget, as it was before).@@ -846,7 +869,7 @@ export async function probePeer(peer) {remoteSyncSeqs = await syncRes.json().catch(() => null);}}).catch((err) => {- console.log(`⚠️ Probe failed for ${baseUrl}: ${classifyProbeError(err, peer)}`);+ probeFailure = err;status = 'offline';authRequired = err?.httpStatus === 401 || err?.httpStatus === 403;lastHealth = peer.lastHealth; // preserve last known@@ -862,12 +885,32 @@ export async function probePeer(peer) {}});+ const latencyMs = Date.now() - probeStartedAt;+ const probedAt = new Date().toISOString();+ const classification = probeFailure+ ? classifyPeerProbeFailure(probeFailure, {+ peer,+ tunnelError,+ probeTimeoutMs: PROBE_TIMEOUT_MS,+ })+ : { class: 'ok', message: null, httpStatus: 200 };+ const lastProbe = buildLastProbeRecord({+ ok: status === 'online',+ classification,+ latencyMs,+ at: probedAt,+ });+ if (status !== 'online') {+ console.log(`⚠️ Probe failed for ${baseUrl}: ${classifyProbeError(probeFailure, peer, tunnelError)} ${formatProbeDiagnosticLog(lastProbe)}`);+ }+const stored = await withData(async (data) => {const entry = data.peers.find(p => p.id === peer.id);if (!entry) return null;entry.status = status;entry.lastSeen = lastSeen;entry.lastHealth = lastHealth;+ entry.lastProbe = lastProbe;// Surface "reachable but needs a credential" distinctly from plain offline.// Cleared on any successful probe (including after the user adds the password).entry.authRequired = authRequired;diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex b03a755b4e..7488a1f311 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -46,7 +46,10 @@ vi.mock('./peerSocketRelay.js', () => ({}));vi.mock('./tailcatPeer.js', () => ({- stopForwardForPeer: vi.fn().mockResolvedValue(undefined)+ stopForwardForPeer: vi.fn().mockResolvedValue(undefined),+ listTailcatForwards: vi.fn().mockResolvedValue([]),+ attachTailcatForwardsToPeers: async (peers) => peers,+ attachTailcatForwardToPeer: async (peer) => peer,}));vi.mock('../lib/ports.js', () => ({@@ -1344,9 +1347,46 @@ describe('instances.js', () => {expect(result.status).toBe('offline');expect(result.lastSeen).toBe('2024-01-01T00:00:00Z');expect(result.lastHealth).toEqual({ uptime: 100 });+ expect(result.lastProbe).toMatchObject({ ok: false, class: expect.any(String) });+ expect(result.lastProbe.message).toBeTruthy();expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');});+ it('classifies a tailcat loopback refuse as local_refused on lastProbe', async () => {+ const peer = makePeer({+ transport: 'tailcat',+ address: '127.0.0.1',+ port: 15555,+ });+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });+ const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:15555'), { code: 'ECONNREFUSED' });+ fetch.mockRejectedValue(refused);++ const result = await probePeer(peer);++ expect(result.status).toBe('offline');+ expect(result.lastProbe).toMatchObject({+ ok: false,+ class: 'local_refused',+ });+ expect(result.lastProbe.message).toMatch(/forward is not listening/i);+ });++ it('persists lastProbe ok + latency on a successful probe', async () => {+ const peer = makePeer();+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });+ fetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id' }) })+ .mockResolvedValueOnce({ ok: false })+ .mockResolvedValueOnce({ ok: false });++ const result = await probePeer(peer);++ expect(result.status).toBe('online');+ expect(result.lastProbe).toMatchObject({ ok: true, class: 'ok', httpStatus: 200 });+ expect(typeof result.lastProbe.latencyMs).toBe('number');+ });+it('should mark peer offline on non-ok health response', async () => {const peer = makePeer();const peers = [peer];diff --git a/server/services/socket.js b/server/services/socket.jsindex 1d1bfd6bb2..8920a2a02b 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -13,6 +13,7 @@ import { moltworldWsEvents } from './moltworldWs.js';import { queueEvents } from './moltworldQueue.js';import { instanceEvents } from './instanceEvents.js';import { sanitizePeerForClient } from './instances.js';+import { attachTailcatForwardsToPeers } from './tailcatPeer.js';import { reviewEvents } from './review.js';import { loopEvents } from './loops.js';import { imageGenEvents } from './imageGenEvents.js';@@ -484,7 +485,10 @@ function setupInstanceEventForwarding() {// route applies. `data` is the full peers array.instanceEvents.on('peers:updated', (data) => {const sanitized = Array.isArray(data) ? data.map(sanitizePeerForClient) : data;- broadcastToInstances('instances:peers:updated', sanitized);+ // Best-effort attach; never block the broadcast if forward metadata is busy.+ Promise.resolve(Array.isArray(sanitized) ? attachTailcatForwardsToPeers(sanitized) : sanitized)+ .then((enriched) => broadcastToInstances('instances:peers:updated', enriched))+ .catch(() => broadcastToInstances('instances:peers:updated', sanitized));});// Realtime sync lifecycle for the Instances cards: { phase, peerId, ... }.// No secrets — just a peer instanceId + counts — so forward as-is.diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.jsindex 349c0955ba..2eac188a4a 100644--- a/server/services/tailcatPeer.js+++ b/server/services/tailcatPeer.js@@ -256,6 +256,56 @@ export async function listTailcatForwards() {});}+/**+ * Client-safe forward summary attached onto a peer with transport === 'tailcat'.+ * Same fields as listTailcatForwards rows (already redacted) so the peer card+ * can be the primary surface without a second mental model.+ */+export function summarizeTailcatForwardForPeer(forward) {+ if (!forward) return null;+ return {+ id: forward.id,+ peerId: forward.peerId,+ tcAddress: forward.tcAddress,+ localPort: forward.localPort,+ remotePort: forward.remotePort,+ name: forward.name,+ protocol: forward.protocol,+ hasAuth: forward.hasAuth,+ status: forward.status,+ lastError: forward.lastError,+ lastErrorAt: forward.lastErrorAt,+ createdAt: forward.createdAt,+ live: forward.live,+ tunnelError: forward.tunnelError,+ tunnelErrorAt: forward.tunnelErrorAt,+ };+}++/**+ * Attach `tailcatForward` onto sanitized peer payloads. Peers that are not+ * tailcat transport are unchanged. A missing forward (e.g. metadata wiped)+ * still gets `tailcatForward: null` so the UI can say so explicitly.+ */+export async function attachTailcatForwardsToPeers(peers) {+ if (!Array.isArray(peers) || peers.length === 0) return peers;+ if (!peers.some((p) => p?.transport === 'tailcat')) return peers;+ const forwards = await listTailcatForwards();+ const byPeerId = new Map(+ forwards.filter((f) => f.peerId).map((f) => [f.peerId, summarizeTailcatForwardForPeer(f)]),+ );+ return peers.map((peer) => {+ if (peer?.transport !== 'tailcat') return peer;+ return { ...peer, tailcatForward: byPeerId.get(peer.id) || null };+ });+}++export async function attachTailcatForwardToPeer(peer) {+ if (!peer || peer.transport !== 'tailcat') return peer;+ const [enriched] = await attachTailcatForwardsToPeers([peer]);+ return enriched;+}+/*** Where a freshly installed `tailcat` can land. PATH is checked first, then the* install directories a package manager uses but a long-running server processdiff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.jsindex 5f9cd3d4ac..3608737739 100644--- a/server/services/tailcatPeer.test.js+++ b/server/services/tailcatPeer.test.js@@ -14,6 +14,7 @@ import {verifyTunnelReachable,addPeerViaTailcat,listTailcatForwards,+ attachTailcatForwardsToPeers,retryTailcatForward,forgetTailcatForward,redactTailcatDiagnostics,@@ -594,6 +595,24 @@ describe('saved tailcat forwards', () => {expect(JSON.stringify(row)).not.toContain('password');});+ it('attaches the redacted forward onto a tailcat peer payload for the peer card', async () => {+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,+ name: 'sandbox', protocol: 'http', auth: null,+ status: 'active', lastError: null, createdAt: '2026-01-01T00:00:00.000Z',+ }] });+ const peers = [+ { id: 'peer-1', name: 'sandbox', transport: 'tailcat', address: '127.0.0.1', port: 15555 },+ { id: 'peer-2', name: 'classic', address: '10.0.0.2', port: 5555 },+ ];+ const enriched = await attachTailcatForwardsToPeers(peers);+ expect(enriched[0].tailcatForward).toMatchObject({+ id: 'fwd_1', peerId: 'peer-1', localPort: 15555, status: 'active', live: false,+ });+ expect(JSON.stringify(enriched[0].tailcatForward)).not.toContain(EXAMPLE_TC);+ expect(enriched[1].tailcatForward).toBeUndefined();+ });+it('separates a bound listener from a tunnel that cannot carry a request', async () => {const child = fakeChild();const saved = [];