Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep Tailcat serve status current and support manual copying (#6529)

[._.]/fbe606ba6591
diff --git a/client/src/components/instances/TailcatAddress.jsx b/client/src/components/instances/TailcatAddress.jsx
new file mode 100644
index 0000000000..b0f551b897
--- /dev/null
+++ b/client/src/components/instances/TailcatAddress.jsx
@@ -0,0 +1,36 @@
+import { useId, useState } from 'react';
+import { Copy } from 'lucide-react';
+import { copyToClipboard } from '../../lib/clipboard';
+
+export default function TailcatAddress({ address, preview, disabled = false, label = 'Copy address' }) {
+ const [revealedAddress, setRevealedAddress] = useState(null);
+ const id = useId();
+ if (!address) return null;
+ const revealed = revealedAddress === address;
+ const copy = async () => {
+ if (!await copyToClipboard(address, 'Tailcat address copied')) setRevealedAddress(address);
+ };
+ return (
+ <div className="mt-2 space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[11px] font-mono text-gray-400 break-all">{preview || 'tc…'}</span>
+ <button type="button" onClick={copy} disabled={disabled}
+ className="inline-flex items-center gap-1 text-xs border border-port-border rounded px-2 py-1 disabled:opacity-50">
+ <Copy size={12} /> {label}
+ </button>
+ <button type="button" disabled={disabled} onClick={() => setRevealedAddress(revealed ? null : address)}
+ className="text-xs underline disabled:opacity-50">
+ {revealed ? 'Hide address' : 'Show address'}
+ </button>
+ </div>
+ {revealed && (
+ <div>
+ <label htmlFor={id} className="block text-xs text-gray-400 mb-1">Full Tailcat address — select and copy to the other node</label>
+ <input id={id} aria-label="Full Tailcat address" readOnly value={address}
+ onFocus={(event) => event.target.select()}
+ className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1 text-xs font-mono" />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/instances/TailcatServePanel.jsx b/client/src/components/instances/TailcatServePanel.jsx
index 4407fd246d..134b3bd94e 100644
--- a/client/src/components/instances/TailcatServePanel.jsx
+++ b/client/src/components/instances/TailcatServePanel.jsx
@@ -6,11 +6,11 @@
* 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 { RefreshCw, Square, Play, CheckCircle2, AlertCircle, Clock } from 'lucide-react';
import Pill from '../ui/Pill';
-import { getTailcatServe, startTailcatServe, retryTailcatServe, stopTailcatServe } from '../../services/api';
+import { startTailcatServe, retryTailcatServe, stopTailcatServe } from '../../services/api';
+import { useTailcatServe } from './TailcatServeProvider';
+import TailcatAddress from './TailcatAddress';
import { PORTS } from '../../lib/ports';
import { timeAgo } from '../../utils/formatters';
@@ -18,35 +18,9 @@ const STATUS_TONE = { active: 'success', pending: 'muted', failed: 'warning', st
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 { status, busy, run: runServe } = useTailcatServe();
+ const run = async (fn, message) => {
+ if (await runServe(fn, message)) onChange?.();
};
const label = status?.live
@@ -87,17 +61,6 @@ export default function TailcatServePanel({ onChange, compact = false }) {
{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"
@@ -129,12 +92,7 @@ export default function TailcatServePanel({ onChange, compact = false }) {
</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>
- )}
+ <TailcatAddress address={status?.tcAddress} preview={status?.tcAddressRedacted} disabled={busy} />
{status?.lastError && status?.status !== 'active' && (
<p className="text-[11px] text-port-error mt-2 leading-snug break-words">
diff --git a/client/src/components/instances/TailcatServePanel.test.jsx b/client/src/components/instances/TailcatServePanel.test.jsx
index 8e12de8d68..a1800bb933 100644
--- a/client/src/components/instances/TailcatServePanel.test.jsx
+++ b/client/src/components/instances/TailcatServePanel.test.jsx
@@ -1,5 +1,6 @@
+import { TailcatServeProvider } from './TailcatServeProvider';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render as renderUI, screen, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('../../services/api', () => ({
@@ -73,3 +74,45 @@ describe('TailcatServePanel', () => {
await waitFor(() => expect(stopTailcatServe).toHaveBeenCalled());
});
});
+
+function render(ui) { return renderUI(<TailcatServeProvider>{ui}</TailcatServeProvider>); }
+
+it('reveals the full address for manual copying when clipboard is unavailable', async () => {
+ getTailcatServe.mockResolvedValue(serving);
+ const user = userEvent.setup();
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });
+ render(<TailcatServePanel />);
+ await user.click(await screen.findByRole('button', { name: 'Copy address' }));
+ expect(screen.getByRole('textbox', { name: 'Full Tailcat address' })).toHaveValue(serving.tcAddress);
+ await user.click(screen.getByRole('button', { name: 'Hide address' }));
+ expect(screen.queryByRole('textbox', { name: 'Full Tailcat address' })).not.toBeInTheDocument();
+});
+
+it('does not overwrite a start receipt with an older in-flight status read', async () => {
+ let resolveRead;
+ getTailcatServe.mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
+ startTailcatServe.mockResolvedValue(serving);
+ const user = userEvent.setup();
+ render(<TailcatServePanel />);
+ await user.click(screen.getByRole('button', { name: 'Start serve' }));
+ expect(await screen.findByRole('button', { name: 'Stop' })).toBeInTheDocument();
+ await act(async () => resolveRead(stopped));
+ expect(screen.getByRole('button', { name: 'Stop' })).toBeInTheDocument();
+});
+
+it('keeps the newest status when visibility refreshes overlap', async () => {
+ let resolveOld;
+ getTailcatServe.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }))
+ .mockResolvedValue({ ...stopped, status: 'failed', lastError: 'Process exited' });
+ render(<TailcatServePanel />);
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ expect(await screen.findByText('Process exited')).toBeInTheDocument();
+ await act(async () => resolveOld(serving));
+ expect(screen.getByText('Process exited')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Stop' })).not.toBeInTheDocument();
+});
diff --git a/client/src/components/instances/TailcatServeProvider.jsx b/client/src/components/instances/TailcatServeProvider.jsx
new file mode 100644
index 0000000000..30bda0432f
--- /dev/null
+++ b/client/src/components/instances/TailcatServeProvider.jsx
@@ -0,0 +1,39 @@
+import { createContext, useCallback, useContext, useRef, useState } from 'react';
+import { getTailcatServe } from '../../services/api';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch';
+import toast from '../ui/Toast';
+
+const ServeContext = createContext(null);
+
+// One owner for both controls. Polls cannot overwrite a newer mutation receipt.
+export function TailcatServeProvider({ children }) {
+ const [status, setStatus] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const operation = useRef({ busy: false, generation: 0, read: 0 });
+ const load = useCallback(async () => {
+ if (operation.current.busy) return;
+ const generation = operation.current.generation;
+ const read = ++operation.current.read;
+ const data = await getTailcatServe({ silent: true });
+ if (!operation.current.busy && generation === operation.current.generation && read === operation.current.read) setStatus(data);
+ }, []);
+ useAutoRefetch(load, 10_000, { pollOnly: true });
+
+ const run = async (fn, successMessage) => {
+ if (operation.current.busy) return null;
+ operation.current.busy = true;
+ operation.current.generation += 1;
+ setBusy(true);
+ // API wrappers own failure toasts. A failed action keeps the last receipt.
+ const result = await Promise.resolve().then(fn).catch(() => null);
+ if (result) setStatus(result);
+ operation.current.busy = false;
+ setBusy(false);
+ if (result && successMessage) toast.success(successMessage);
+ return result;
+ };
+
+ return <ServeContext.Provider value={{ status, busy, run }}>{children}</ServeContext.Provider>;
+}
+
+export const useTailcatServe = () => useContext(ServeContext);
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 797bb54f52..2c61f67aa0 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -21,7 +21,7 @@ import {
getPeerFullSyncCoverage,
getBrainParityReports,
retryTailcatForward, forgetTailcatForward,
- startTailcatServe, getTailcatServe,
+ startTailcatServe,
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
@@ -34,6 +34,8 @@ 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 { TailcatServeProvider, useTailcatServe } from '../components/instances/TailcatServeProvider';
+import TailcatAddress from '../components/instances/TailcatAddress';
import TailcatForwardStatus from '../components/instances/TailcatForwardStatus';
import { timeAgo, timeUntil } from '../utils/formatters';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
@@ -224,13 +226,7 @@ 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 { status: serveStatus, busy: serveBusy, run: runServe } = useTailcatServe();
const handleSubmit = async (e) => {
e.preventDefault();
@@ -275,24 +271,8 @@ export function AddPeerForm({ onAdd, addressRef }) {
};
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 result = await runServe(() => startTailcatServe({}), 'Tailcat serve is running — copy the address for the other node');
+ if (result) onAdd?.();
};
const canSubmit = mode === 'tailcat'
@@ -318,7 +298,7 @@ export function AddPeerForm({ onAdd, addressRef }) {
type="button"
aria-pressed={mode === 'tailcat'}
disabled={adding || serveBusy}
- onClick={() => { setMode('tailcat'); refreshServe(); }}
+ onClick={() => setMode('tailcat')}
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
@@ -339,7 +319,7 @@ export function AddPeerForm({ onAdd, addressRef }) {
type="button"
aria-pressed={dialDirection === 'they-dial-us'}
disabled={adding || serveBusy}
- onClick={() => { setDialDirection('they-dial-us'); refreshServe(); }}
+ onClick={() => setDialDirection('they-dial-us')}
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
@@ -389,21 +369,9 @@ export function AddPeerForm({ onAdd, addressRef }) {
>
{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>
- )}
+ <TailcatAddress address={serveStatus?.tcAddress} preview={serveStatus?.tcAddressRedacted}
+ disabled={serveBusy} label="Copy our address" />
</div>
) : (
<div className="flex flex-wrap gap-2">
@@ -1520,6 +1488,10 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {
}
export default function Instances() {
+ return <TailcatServeProvider><InstancesContent /></TailcatServeProvider>;
+}
+
+function InstancesContent() {
// The Add Peer form is always on screen above the peer grid, so the empty
// state's call to action focuses its address field rather than opening one.
const peerAddressRef = useRef(null);
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 4e8a165492..1bf1a680b9 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -1,8 +1,10 @@
+import { TailcatServeProvider } from '../components/instances/TailcatServeProvider';
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { render as renderUI, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import TailcatServePanel from '../components/instances/TailcatServePanel';
import { AddPeerForm } from './Instances.jsx';
import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
-import { addPeer, addTailcatPeer, startTailcatServe, getTailcatServe } from '../services/api';
+import { addPeer, addTailcatPeer, startTailcatServe, getTailcatServe, stopTailcatServe } from '../services/api';
vi.mock('../services/api', () => ({
getInstances: vi.fn(),
@@ -43,8 +45,9 @@ describe('AddPeerForm port default', () => {
// Regression: the placeholder advertised :5554 (the Vite dev port) while the
// field defaulted to the API port, so clearing the field suggested a port
// PortOS never serves the API on.
- it('advertises the same port in the placeholder as it defaults to', () => {
+ it('advertises the same port in the placeholder as it defaults to', async () => {
render(<AddPeerForm onAdd={() => {}} />);
+ await act(async () => {});
const portInput = screen.getByLabelText('Peer port');
expect(portInput).toHaveValue(DEFAULT_PEER_PORT);
expect(portInput.getAttribute('placeholder')).toBe(String(DEFAULT_PEER_PORT));
@@ -146,3 +149,20 @@ describe('AddPeerForm dial direction', () => {
expect(addTailcatPeer).not.toHaveBeenCalled();
});
});
+
+function render(ui) { return renderUI(<TailcatServeProvider>{ui}</TailcatServeProvider>); }
+
+it('shares start and stop receipts between both serve controls', async () => {
+ getTailcatServe.mockResolvedValue({ live: false, enabled: false, status: 'stopped' });
+ startTailcatServe.mockResolvedValue({ live: true, enabled: true, status: 'active' });
+ stopTailcatServe.mockResolvedValue({ live: false, enabled: false, status: 'stopped' });
+ render(<><AddPeerForm onAdd={() => {}} /><TailcatServePanel /></>);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat' }));
+ fireEvent.click(screen.getByRole('button', { name: 'They dial us' }));
+ fireEvent.click(screen.getAllByRole('button', { name: 'Start serve' })[0]);
+ expect(await screen.findByRole('button', { name: 'Serve running' })).toBeDisabled();
+ fireEvent.click(await screen.findByRole('button', { name: 'Stop' }));
+ await waitFor(() => expect(screen.getAllByRole('button', { name: 'Start serve' })).toHaveLength(2));
+ expect(screen.queryByRole('button', { name: 'Serve running' })).not.toBeInTheDocument();
+});
diff --git a/server/services/tailcatServe.js b/server/services/tailcatServe.js
index ba382327d9..26a279aafd 100644
--- a/server/services/tailcatServe.js
+++ b/server/services/tailcatServe.js
@@ -154,7 +154,7 @@ export async function getTailcatServeStatus() {
}
return {
enabled: entry.enabled,
- status: live ? 'active' : entry.status,
+ status: live ? 'active' : (entry.status === 'active' ? 'stopped' : entry.status),
live,
localPort: entry.localPort,
keyName: entry.keyName,
@@ -328,16 +328,26 @@ export async function startServeProcess({
}
function killLiveServe() {
- if (liveServe?.child && !liveServe.child.killed) {
- try { liveServe.child.kill('SIGTERM'); } catch { /* best-effort */ }
- }
+ const child = liveServe?.child;
+ // Relinquish ownership before signalling: a synchronous exit is intentional.
liveServe = null;
+ if (child && !child.killed) {
+ try { child.kill('SIGTERM'); } catch { /* best-effort */ }
+ }
}
function trackServe(child, localPort, keyName) {
liveServe = { child, localPort, keyName };
- child.on('exit', () => {
- if (liveServe?.child === child) liveServe = null;
+ const owned = liveServe;
+ child.on('exit', (code, signal) => {
+ if (liveServe !== owned) return;
+ // Serialize the terminal write behind startup persistence. Retry/stop may
+ // already own the lifecycle lock, in which case their newer state wins.
+ void withLifecycle(async () => {
+ if (shuttingDown || liveServe !== owned) return;
+ liveServe = null;
+ await markServeFailed(new Error(`tailcat serve exited (code=${code}, signal=${signal})`));
+ }).catch((err) => console.error(`❌ Could not record tailcat serve exit: ${redactTailcatDiagnostics(err.message)}`));
});
}
diff --git a/server/services/tailcatServe.test.js b/server/services/tailcatServe.test.js
index a696cbb1b3..58421eef13 100644
--- a/server/services/tailcatServe.test.js
+++ b/server/services/tailcatServe.test.js
@@ -127,6 +127,32 @@ describe('tailcatServe helpers', () => {
expect(saved?.serve?.tcAddress).toBe(EXAMPLE_TC);
});
+ it('records an unexpected exit without overwriting a later retry or stop', async () => {
+ let saved = { version: 1, serve: null };
+ readJSONFile.mockImplementation(async () => saved);
+ atomicWrite.mockImplementation(async (_path, data) => { saved = data; });
+ const child = fakeChild();
+ const deps = {
+ ensureInstalled: async () => ({ bin: '/example/tailcat' }),
+ primeDerpMap: async () => ({}),
+ ensureKey: async () => ({}),
+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }),
+ };
+ await ensureTailcatServe(deps);
+ child.emit('exit', 1, null);
+ await vi.waitFor(() => expect(saved.serve.status).toBe('failed'));
+ expect(await getTailcatServeStatus()).toMatchObject({ live: false, status: 'failed', enabled: true });
+ expect(saved.serve.lastError).toContain('code=1');
+
+ const replacement = fakeChild();
+ await retryTailcatServe({ ...deps, startServe: async () => ({ child: replacement, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }) });
+ child.emit('exit', 1, null);
+ expect(await getTailcatServeStatus()).toMatchObject({ live: true, status: 'active' });
+ await stopTailcatServe();
+ replacement.emit('exit', 0, 'SIGTERM');
+ expect(await getTailcatServeStatus()).toMatchObject({ live: false, status: 'stopped', enabled: false, lastError: null });
+ });
+
it('stopTailcatServe disables restore-on-boot', async () => {
const child = fakeChild();
let saved = {