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
fix: show degraded Tailcat relay health (#8822)
[._.]/36d545cb4221
diff --git a/client/src/components/instances/TailcatServePanel.jsx b/client/src/components/instances/TailcatServePanel.jsxindex cd8eee608c..cab884fbab 100644--- a/client/src/components/instances/TailcatServePanel.jsx+++ b/client/src/components/instances/TailcatServePanel.jsx@@ -23,14 +23,15 @@ export default function TailcatServePanel({ onChange, compact = false }) {if (await runServe(fn, message)) onChange?.();};+ const degraded = status?.live && status?.relayStatus === 'degraded';const label = status?.live- ? 'serving'+ ? (degraded ? 'relay degraded' : 'process running'): (status?.status || 'stopped');const tone = status?.live- ? 'success'+ ? (degraded ? 'warning' : 'muted'): (STATUS_TONE[status?.status] || 'muted');const StatusIcon = status?.live- ? CheckCircle2+ ? (degraded ? AlertCircle : Clock): (STATUS_ICON[status?.status] || Clock);return (@@ -104,6 +105,17 @@ export default function TailcatServePanel({ onChange, compact = false }) {</div></div>+ {status?.live && (+ <p role="status" className={`text-[11px] mt-2 leading-snug ${degraded ? 'text-port-warning' : 'text-gray-500'}`}>+ {degraded+ ? (status.relayError || 'Tailcat reported a relay connection failure.')+ : (status.relayStatus === 'connected'+ ? 'Relay connected. End-to-end peer health is not verified here.'+ : 'Relay reachability is unknown. A running process does not confirm a working tunnel.')}+ {status.relayObservedAt && <span> · {timeAgo(status.relayObservedAt)}</span>}+ </p>+ )}+<TailcatAddress address={status?.tcAddress} preview={status?.tcAddressRedacted} disabled={busy} />{status?.lastError && status?.status !== 'active' && (diff --git a/client/src/components/instances/TailcatServePanel.test.jsx b/client/src/components/instances/TailcatServePanel.test.jsxindex 62dd14fd46..92dabf76a7 100644--- a/client/src/components/instances/TailcatServePanel.test.jsx+++ b/client/src/components/instances/TailcatServePanel.test.jsx@@ -183,3 +183,21 @@ it.each([false, true])('reconciles changes received during a mutation (failed=%sexpect(getTailcatServe).toHaveBeenCalledTimes(2);expect(screen.getByText('Example process exited')).toBeInTheDocument();});+++it('shows relay degradation and socket-driven recovery without claiming peer health', async () => {+ getTailcatServe.mockReset().mockResolvedValue({ ...serving, relayStatus: 'degraded',+ relayError: 'Tailcat relay connection timed out.', relayObservedAt: '2026-01-01T00:00:00Z' });+ render(<TailcatServePanel />);+ expect(await screen.findByText('relay degraded')).toBeInTheDocument();+ expect(screen.getByText(/Tailcat relay connection timed out/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Stop' })).toBeEnabled();+ getTailcatServe.mockResolvedValue({ ...serving, relayStatus: 'connected', relayError: null });+ await act(async () => socket.emit('tailcat:serve:changed', {}));+ expect(screen.queryByText('relay degraded')).not.toBeInTheDocument();+ expect(screen.getByText('process running')).toBeInTheDocument();+ expect(screen.getByText(/End-to-end peer health is not verified/)).toBeInTheDocument();+ getTailcatServe.mockResolvedValue({ ...serving, relayStatus: 'unknown' });+ await act(async () => socket.emit('tailcat:serve:changed', {}));+ expect(screen.getByText(/Relay reachability is unknown/)).toBeInTheDocument();+});diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.mdindex 1aaf57129d..542282a802 100644--- a/docs/features/tailcat-peers.md+++ b/docs/features/tailcat-peers.md@@ -153,6 +153,26 @@ placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.| `POST …/serve/retry` | Restart from the saved config. || `DELETE …/serve` | Stop serve and disable restore-on-boot. |+### Serve process and relay health are separate++A live managed serve is displayed as **process running**, not proof that a peer+can reach PortOS. Its status includes `relayStatus` (`unknown`, `connected`, or+`degraded`), `relayError`, and `relayObservedAt`. A reported connection failure or+loss shows **relay degraded** while keeping the process and saved key intact.++Relay evidence comes from complete, bounded Tailcat stderr lines. Only fixed+failure summaries leave the process observer; raw endpoints, capabilities and+credentials are not returned or logged. Overlong lines are discarded entirely.+An explicit connection message for the affected relay clears the failure; an+unrelated relay connecting does not. Evidence expires after five minutes to+**unknown**, never presumed healthy. A replacement process starts with unknown+relay health, and stopped/replaced children cannot update its status.++These observations remain in memory and update the UI through the existing+serve-change event. They do not trigger restarts or change encryption, ingress,+or pairing settings. Even **Relay connected** only confirms a relay connection;+the peer health check still establishes end-to-end API reachability.+### The saved address is what makes a failed add recoverableThe row is written **before** the forward is attempted. That ordering is thediff --git a/server/services/tailcatServe.js b/server/services/tailcatServe.jsindex ac71d6fadd..90793c11a7 100644--- a/server/services/tailcatServe.js+++ b/server/services/tailcatServe.js@@ -39,6 +39,7 @@ const DEFAULT_LOCAL_PORT = PORTS.TAILCAT_INGRESS;const SERVE_READY_MS = 20_000;const DIAGNOSTIC_TAIL_CHARS = 4096;const GENKEY_TIMEOUT_MS = 60_000;+const RELAY_OBSERVATION_MS = 5 * 60 * 1000;const DEFAULT_DATA = { version: 1, serve: null };const withLock = createMutex();@@ -48,6 +49,71 @@ const withLifecycle = createMutex();let liveServe = null;let shuttingDown = false;+/** Observe complete stderr lines without exposing their private endpoints or tokens. */+function observeServeRelay(child) {+ let partial = '';+ let droppingLine = false;+ let expiry;+ let closed = false;+ // Relay evidence belongs to this process, never the persisted serve config.+ child.tailcatRelay = { status: 'unknown', error: null, at: null };+ let failedRegion = null;+ const publish = (status, error, at = new Date().toISOString()) => {+ clearTimeout(expiry);+ if (status === 'unknown') failedRegion = null;+ child.tailcatRelay = { status, error, at };+ child.emit('tailcat:relay');+ if (status !== 'unknown') {+ expiry = setTimeout(() => {+ if (!closed) publish('unknown', null, null);+ }, RELAY_OBSERVATION_MS);+ expiry.unref?.();+ }+ };+ const lineReceived = (line) => {+ if (!/\bderp(?:http|[-.( :])/i.test(line)) return;+ const region = line.match(/\bderp-(\d+)\b/)?.[1] || null;+ if (/\bmagicsock: derp-\d+ connected\b/.test(line)) {+ // A different relay connecting does not disprove the observed failure.+ if (failedRegion && region !== failedRegion) return;+ failedRegion = null;+ publish('connected', null);+ } else if (/\b(?:error|failed|timeout|timed out|deadline exceeded|refused|no such host|socket is not connected)\b/i.test(line)+ || /\bclosing connection to derp-\d+.*\(conn-close\)/.test(line)) {+ failedRegion = region;+ // Fixed messages intentionally avoid replaying arbitrary CLI text. Even a+ // truncated capability, password or endpoint cannot cross this boundary.+ const error = /timeout|timed out|deadline exceeded/i.test(line)+ ? 'Tailcat relay connection timed out.'+ : 'Tailcat reported a relay connection failure or loss.';+ publish('degraded', error);+ }+ };+ child.stderr?.on('data', (chunk) => {+ if (closed) return;+ try {+ for (const part of String(chunk).split(/(\n)/)) {+ if (part === '\n') {+ if (!droppingLine) lineReceived(partial);+ partial = '';+ droppingLine = false;+ } else if (!droppingLine) {+ if (partial.length + part.length > DIAGNOSTIC_TAIL_CHARS) {+ partial = '';+ droppingLine = true;+ } else partial += part;+ }+ }+ } catch { /* process stream boundary: diagnostics must not stop PortOS */ }+ });+ child.disposeTailcatRelay = () => {+ closed = true;+ partial = '';+ clearTimeout(expiry);+ };+ child.once('exit', child.disposeTailcatRelay);+}+/*** 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@@ -145,6 +211,9 @@ export async function getTailcatServeStatus() {enabled: false,status: 'stopped',live: false,+ relayStatus: 'unknown',+ relayError: null,+ relayObservedAt: null,localPort: DEFAULT_LOCAL_PORT,keyName: DEFAULT_KEY_NAME,tcAddress: null,@@ -160,6 +229,9 @@ export async function getTailcatServeStatus() {enabled: entry.enabled,status: live ? 'active' : (entry.status === 'active' ? 'stopped' : entry.status),live,+ relayStatus: live ? (liveServe.child.tailcatRelay?.status || 'unknown') : 'unknown',+ relayError: live ? (liveServe.child.tailcatRelay?.error || null) : null,+ relayObservedAt: live ? (liveServe.child.tailcatRelay?.at || null) : null,localPort: entry.localPort,keyName: entry.keyName,tcAddress: entry.tcAddress,@@ -251,6 +323,8 @@ export async function startServeProcess({}),);+ observeServeRelay(child);+let stdoutTail = '';let stderrTail = '';let settled = false;@@ -271,7 +345,10 @@ export async function startServeProcess({clearTimeout(timer);clearInterval(poller);const diagnostics = error ? redactTailcatDiagnostics(stderrTail || stdoutTail) : '';+ stdoutTail = '';+ stderrTail = '';if (error) {+ child.disposeTailcatRelay?.();if (diagnostics) error.message = `${error.message} — tailcat said: ${diagnostics}`;try { child.kill('SIGTERM'); } catch { /* process event boundary */ }rejectReady(error);@@ -302,10 +379,12 @@ export async function startServeProcess({poller = setInterval(() => { tryResolve().catch(() => {}); }, 150);child.stdout?.on('data', (chunk) => {+ if (settled) return;stdoutTail = (stdoutTail + String(chunk)).slice(-DIAGNOSTIC_TAIL_CHARS);tryResolve().catch(() => {});});child.stderr?.on('data', (chunk) => {+ if (settled) return;stderrTail = (stderrTail + String(chunk)).slice(-DIAGNOSTIC_TAIL_CHARS);// Human line often includes the address before --json flushes; harvest it.const fromErr = parseServeListenAddr(stderrTail);@@ -335,6 +414,7 @@ function killLiveServe() {const child = liveServe?.child;// Relinquish ownership before signalling: a synchronous exit is intentional.liveServe = null;+ child?.disposeTailcatRelay?.();if (child) instanceEvents.emit('tailcat:serve:changed');if (child && !child.killed) {try { child.kill('SIGTERM'); } catch { /* best-effort */ }@@ -344,6 +424,9 @@ function killLiveServe() {function trackServe(child, localPort, keyName) {liveServe = { child, localPort, keyName };const owned = liveServe;+ child.on('tailcat:relay', () => {+ if (liveServe === owned && !child.killed) instanceEvents.emit('tailcat:serve:changed');+ });child.on('exit', (code, signal) => {if (liveServe !== owned) return;// Serialize the terminal write behind startup persistence. Retry/stop maydiff --git a/server/services/tailcatServe.test.js b/server/services/tailcatServe.test.jsindex 09b7b591c2..5a3f90de7b 100644--- a/server/services/tailcatServe.test.js+++ b/server/services/tailcatServe.test.js@@ -63,6 +63,7 @@ describe('tailcatServe helpers', () => {afterEach(() => {_resetLiveServeForTests();+ vi.useRealTimers();});it('surfaces shared installation failure without starting a tunnel', async () => {@@ -302,6 +303,77 @@ describe('tailcatServe helpers', () => {expect(_liveServeForTests()?.child).toBe(second);});+ it('reports fragmented relay failures, recovery, expiry and replacement isolation through serve status', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ let saved = { version: 1, serve: null };+ readJSONFile.mockImplementation(async () => saved);+ atomicWrite.mockImplementation(async (_path, data) => { saved = data; });+ const children = [];+ const deps = {+ ensureInstalled: async () => ({ bin: '/example/tailcat' }),+ primeDerpMap: async () => ({}),+ ensureKey: async () => ({}),+ startServe: (options) => startServeProcess({+ ...options,+ mkdirFn: async () => {},+ readFileFn: async () => '',+ spawnFn: () => {+ const child = fakeChild();+ children.push(child);+ Promise.resolve().then(() => child.stdout.emit('data', `${JSON.stringify({ listenAddr: EXAMPLE_TC })}\n`));+ return child;+ },+ }),+ };+ expect(await ensureTailcatServe(deps)).toMatchObject({ live: true, relayStatus: 'unknown' });+ const child = children[0];+ instanceEvents.emit.mockClear();+ const writes = atomicWrite.mock.calls.length;+ const raw = `magicsock: derp.Recv(derp-301): ${EXAMPLE_TC} https://user:[email protected]:443 context deadline exceeded`;+ child.stderr.emit('data', raw.slice(0, 45));+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });+ child.stderr.emit('data', raw.slice(45) + '\n');+ const failed = await getTailcatServeStatus();+ expect(failed).toMatchObject({ live: true, status: 'active', relayStatus: 'degraded',+ relayError: 'Tailcat relay connection timed out.', relayObservedAt: '2026-01-01T00:00:00.000Z' });+ expect(failed.relayError).not.toMatch(/example-secret|relay.example|tcEX/);+ expect(instanceEvents.emit).toHaveBeenCalledWith('tailcat:serve:changed');+ expect(atomicWrite).toHaveBeenCalledTimes(writes);++ child.stderr.emit('data', 'derphttp.Client.Connect: connecting to derp-301 (example)\n');+ child.stderr.emit('data', 'magicsock: derp-302 connected; connGen=1\n');+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'degraded' });+ child.stderr.emit('data', 'magicsock: derp-301 connected; connGen=2\n');+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'connected', relayError: null });+ child.stderr.emit('data', 'magicsock: closing connection to derp-301 (conn-close), age 10s\n');+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'degraded' });+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown', relayError: null, relayObservedAt: null });++ child.stderr.emit('data', 'magicsock: derp-302 connected; connGen=3\n');+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'connected' });+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });++ // Oversized lines are dropped as a whole, not classified from a private suffix.+ child.stderr.emit('data', 'x'.repeat(5000));+ child.stderr.emit('data', raw + '\n');+ expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });+ child.stderr.emit('data', raw + '\n');+ await retryTailcatServe(deps);+ instanceEvents.emit.mockClear();+ child.stderr.emit('data', raw + '\n');+ expect(await getTailcatServeStatus()).toMatchObject({ live: true, relayStatus: 'unknown', relayError: null });+ expect(instanceEvents.emit).not.toHaveBeenCalled();+ children[1].stderr.emit('data', raw + '\n');+ await stopTailcatServe();+ instanceEvents.emit.mockClear();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(await getTailcatServeStatus()).toMatchObject({ live: false, relayStatus: 'unknown', relayError: null });+ expect(instanceEvents.emit).not.toHaveBeenCalled();+ });+it('getTailcatServeStatus never invents a live process', async () => {const status = await getTailcatServeStatus();expect(status).toMatchObject({