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: put peer actions ahead of connection setup (#7112)

[._.]/ Adam Eivyb0a04b906a8a
diff --git a/client/src/components/instances/TailcatForwardsPanel.jsx b/client/src/components/instances/TailcatForwardsPanel.jsx
index fb2b6b0df5..8bde3df6ed 100644
--- a/client/src/components/instances/TailcatForwardsPanel.jsx
+++ b/client/src/components/instances/TailcatForwardsPanel.jsx
@@ -15,7 +15,7 @@ import toast from '../ui/Toast';
import { getTailcatForwards, retryTailcatForward, forgetTailcatForward } from '../../services/api';
import TailcatForwardStatus from './TailcatForwardStatus';
-export default function TailcatForwardsPanel({ onChange, peerIds }) {
+export default function TailcatForwardsPanel({ onChange, peerIds, renderPanel = (panel) => panel }) {
// `null` = not loaded yet, `[]` = loaded and genuinely empty. Distinct so a
// pending fetch never renders as "no forwards".
const [forwards, setForwards] = useState(null);
@@ -67,9 +67,9 @@ export default function TailcatForwardsPanel({ onChange, peerIds }) {
toast.success('Tailcat forward and its saved address removed');
};
- if (!orphans || orphans.length === 0) return null;
+ if (!orphans || orphans.length === 0) return renderPanel(null, 0);
- return (
+ return renderPanel(
<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 — needs attention ({orphans.length})
@@ -94,6 +94,7 @@ export default function TailcatForwardsPanel({ onChange, peerIds }) {
</li>
))}
</ul>
- </div>
+ </div>,
+ orphans.length,
);
}
diff --git a/client/src/components/instances/UnattendedRenderRouting.jsx b/client/src/components/instances/UnattendedRenderRouting.jsx
index fb6bc79605..045d980103 100644
--- a/client/src/components/instances/UnattendedRenderRouting.jsx
+++ b/client/src/components/instances/UnattendedRenderRouting.jsx
@@ -98,7 +98,7 @@ function routeStatus(peers, route) {
* routing the provider contract forbids — so the choice lives in this
* instance's own settings and the server reads it at enqueue time.
*/
-export default function UnattendedRenderRouting({ peers }) {
+export default function UnattendedRenderRouting({ peers, renderPanel = (panel) => panel }) {
// `null` = not loaded yet, and NOT the same as `{}` (loaded, nothing routed).
// Conflating them is what would let a failed settings read save a routing map
// rebuilt from an empty object, clearing a route this page never saw.
@@ -176,17 +176,25 @@ export default function UnattendedRenderRouting({ peers }) {
// would leave a persisted route silently failing every enqueue with no
// on-screen explanation and no way to clear it.
if (loadFailed) {
- return (
+ return renderPanel(
<div className="mb-3 rounded-lg border border-port-border bg-port-bg/40 p-3">
<p className="text-[11px] text-port-warning">
Unattended render routing could not load this instance&rsquo;s settings, so it is read-only. Reload to try again.
</p>
- </div>
+ </div>,
+ true,
);
}
- if (routing === null || (!anyOptions && !hasSavedRoute)) return null;
+ if (routing === null || (!anyOptions && !hasSavedRoute)) return renderPanel(null, false);
+
+ const needsAttention = KINDS.some(({ kind }) => {
+ const current = savedRoute(kind);
+ if (!current) return false;
+ const option = optionsByKind[kind].find((candidate) => optionValue(candidate) === optionValue(current));
+ return !option || !option.ready || routeStatus(peers, current)?.tone !== 'success';
+ });
- return (
+ return renderPanel(
<div className="mb-3 rounded-lg border border-port-border bg-port-bg/40 p-3">
<div className="flex items-center gap-2 mb-1">
<Bot size={14} className="text-port-accent" />
@@ -253,6 +261,7 @@ export default function UnattendedRenderRouting({ peers }) {
);
})}
</div>
- </div>
+ </div>,
+ needsAttention,
);
}
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 00f939dc42..b0724c0bbf 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -9,6 +9,9 @@ import {
Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,
Lock, Globe, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints, Gauge
} from 'lucide-react';
+import { useSearchParams } from 'react-router';
+import Drawer from '../components/Drawer';
+import useDrawerTab from '../hooks/useDrawerTab';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -90,9 +93,7 @@ function HealthSummary({ health, version }) {
);
}
-function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
- const [editing, setEditing] = useState(false);
- const [name, setName] = useState('');
+function SelfCard({ self, onUpdate, syncStatus, tailnetInfo, editing, setEditing, name, setName }) {
const startEdit = () => {
setName(self?.name || '');
@@ -214,7 +215,7 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
// Exported for focused tests (the port input's placeholder must advertise the
// same default the form actually submits — see Instances.test.jsx).
-export function AddPeerForm({ onAdd, addressRef }) {
+export function AddPeerForm({ onAdd, addressRef, drawer }) {
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'
@@ -230,6 +231,11 @@ export function AddPeerForm({ onAdd, addressRef }) {
const [adding, setAdding] = useState(false);
const { status: serveStatus, busy: serveBusy, run: runServe } = useTailcatServe();
+ // This component stays mounted above its Drawer, retaining drafts on close.
+ useEffect(() => {
+ if (drawer?.open) addressRef?.current?.focus();
+ }, [drawer?.open, addressRef]);
+
const handleSubmit = async (e) => {
e.preventDefault();
if (mode === 'tailcat') {
@@ -281,7 +287,7 @@ export function AddPeerForm({ onAdd, addressRef }) {
? (dialDirection === 'dial-them' && !!tcAddress.trim())
: !!address.trim();
- return (
+ const form = (
<form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-xl p-5">
<h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3 flex items-center gap-2">
<Plus size={14} /> Add Peer
@@ -466,6 +472,9 @@ export function AddPeerForm({ onAdd, addressRef }) {
</div>
</form>
);
+ return drawer
+ ? <Drawer {...drawer} title="Add peer" closeLabel="Close add peer">{form}</Drawer>
+ : form;
}
function DirectionBadge({ directions = [] }) {
@@ -1303,7 +1312,7 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityRepor
return (
<div className={`bg-port-card border border-port-border rounded-xl p-5 transition-opacity ${!peer.enabled ? 'opacity-50' : ''}`}>
- <div className="flex items-start justify-between mb-3">
+ <div className="flex flex-wrap items-start justify-between gap-2 mb-3">
<div className="flex items-center gap-2">
<StatusIcon size={16} className={STATUS_COLORS[peer.status]} />
{editingName ? (
@@ -1458,9 +1467,22 @@ export default function Instances() {
}
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);
+ const [searchParams, setSearchParams] = useSearchParams();
+ const drawer = searchParams.get('connection');
+ const [settingsTab, setSettingsTab] = useDrawerTab('connectionTab', 'instance', ['instance', 'network', 'relay', 'routing']);
+ const [editingSelf, setEditingSelf] = useState(false);
+ const [selfName, setSelfName] = useState('');
+ const { status: serveStatus } = useTailcatServe();
+ const openDrawer = (value, tab) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (value) next.set('connection', value);
+ else next.delete('connection');
+ if (tab) next.set('connectionTab', tab);
+ return next;
+ }, { replace: true });
+ };
const [self, setSelf] = useState(null);
const [peers, setPeers] = useState([]);
const [syncStatus, setSyncStatus] = useState(null);
@@ -1527,68 +1549,109 @@ function InstancesContent() {
);
}
+ // Keep state owners above the remounting drawer tabs. The same snapshot
+ // drives attention summaries and recovery controls, including with no peers.
return (
- <div className="space-y-6">
- <div className="flex items-center gap-3">
- <Network size={24} className="text-port-accent" />
- <h1 className="text-2xl font-bold text-white">Instances</h1>
- <span className="text-sm text-gray-500">PortOS Federation</span>
- </div>
+ <TailcatForwardsPanel onChange={fetchData} peerIds={peers.map((peer) => peer.id)}
+ renderPanel={(forwardsPanel, orphanCount) => (
+ <UnattendedRenderRouting peers={peers} renderPanel={(routingPanel, routeAttention) => (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3">
+ <Network size={24} className="text-port-accent" />
+ <h1 className="text-2xl font-bold text-white">Instances</h1>
+ <span className="text-sm text-gray-500">PortOS Federation</span>
+ </div>
- <TailnetHelpBanner tailnetInfo={tailnetInfo} networkExposure={networkExposure} />
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={() => openDrawer('add')}
+ className="min-h-[44px] inline-flex items-center gap-1 rounded-lg bg-port-accent px-3 text-sm text-white">
+ <Plus size={16} /> Add peer
+ </button>
+ <button type="button" onClick={() => openDrawer('settings')}
+ className="min-h-[44px] rounded-lg border border-port-border px-3 text-sm text-gray-300 hover:text-white">
+ Connection settings
+ </button>
+ </div>
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-400">
+ <span className="break-words min-w-0">{self?.name || 'This instance'}</span>
+ <span>{networkExposure?.setup?.complete ? 'Tailscale HTTPS ready' : 'Network setup available'}</span>
+ <span>{peers.filter((peer) => peer.status === 'online').length} / {peers.length} peers online</span>
+ </div>
+ {(orphanCount > 0 || serveStatus?.status === 'failed') && (
+ <button type="button" onClick={() => openDrawer('settings', 'relay')}
+ className="block w-full rounded-lg border border-port-warning/40 p-3 text-left text-sm text-port-warning">
+ Tailcat needs attention — review forwards and serve
+ </button>
+ )}
+ {routeAttention && (
+ <button type="button" onClick={() => openDrawer('settings', 'routing')}
+ className="block w-full rounded-lg border border-port-warning/40 p-3 text-left text-sm text-port-warning">
+ Unattended render routing needs attention — review routes
+ </button>
+ )}
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <SelfCard self={self} onUpdate={fetchData} syncStatus={syncStatus} tailnetInfo={tailnetInfo} />
- <AddPeerForm onAdd={fetchData} addressRef={peerAddressRef} />
- </div>
+ {peers.length > 0 && (
+ <div>
+ <h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
+ Peers ({peers.length})
+ </h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
+ {peers.map(peer => (
+ // Reports key on instanceId (the stable federation identity), but
+ // a peer audited before it was ever probed files under its local
+ // registry id — mirror that fallback here or its report reads as
+ // "not checked".
+ <PeerCard
+ key={peer.id}
+ peer={peer}
+ onRefresh={fetchData}
+ syncStatus={syncStatus}
+ tailnetInfo={tailnetInfo}
+ parityReport={parityReports[peer.instanceId] ?? parityReports[peer.id] ?? null}
+ />
+ ))}
+ </div>
+ </div>
+ )}
- {/* Outside the peer-count guard on purpose: removing the last peer must
- not hide the only control that can clear a stale saved route, or every
- unattended render keeps failing its preflight with no way back. The
- component renders nothing when there is neither an option nor a saved
- route. */}
- <UnattendedRenderRouting peers={peers} />
-
- {/* Also outside the peer-count guard: a tailcat forward whose start failed
- never 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 && (
- <div>
- <h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
- Peers ({peers.length})
- </h2>
- <BrainParitySchedule />
- <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
- {peers.map(peer => (
- // Reports key on instanceId (the stable federation identity), but
- // a peer audited before it was ever probed files under its local
- // registry id — mirror that fallback here or its report reads as
- // "not checked".
- <PeerCard
- key={peer.id}
- peer={peer}
- onRefresh={fetchData}
- syncStatus={syncStatus}
- tailnetInfo={tailnetInfo}
- parityReport={parityReports[peer.instanceId] ?? parityReports[peer.id] ?? null}
+ {peers.length === 0 && (
+ <EmptyState
+ icon={Network}
+ title="No peers registered yet"
+ message="Add another PortOS instance by its Tailscale IP address to federate records between your machines."
+ actionLabel="Add your first peer"
+ onAction={() => openDrawer('add')}
/>
- ))}
+ )}
+ <AddPeerForm onAdd={fetchData} addressRef={peerAddressRef}
+ drawer={{ open: drawer === 'add', onClose: () => openDrawer(null) }} />
+ <Drawer open={drawer === 'settings'} onClose={() => openDrawer(null)}
+ title="Connection settings" size="md"
+ tabs={[
+ { id: 'instance', label: 'This instance' },
+ { id: 'network', label: 'Network' },
+ { id: 'relay', label: 'Tailcat' },
+ { id: 'routing', label: 'Render routes' },
+ ]}
+ activeTab={settingsTab} onTabChange={setSettingsTab}>
+ {settingsTab === 'instance' && (
+ <div className="space-y-4">
+ <SelfCard self={self} onUpdate={fetchData} syncStatus={syncStatus} tailnetInfo={tailnetInfo}
+ editing={editingSelf} setEditing={setEditingSelf} name={selfName} setName={setSelfName} />
+ <BrainParitySchedule />
+ </div>
+ )}
+ {settingsTab === 'network' && <TailnetHelpBanner tailnetInfo={tailnetInfo} networkExposure={networkExposure} />}
+ {settingsTab === 'relay' && (
+ <div className="space-y-4">
+ <TailcatServePanel onChange={fetchData} />
+ {forwardsPanel}
+ </div>
+ )}
+ {settingsTab === 'routing' && (routingPanel || <p className="text-sm text-gray-400">No render routes configured. Enable a Tailscale peer as a media provider to add one.</p>)}
+ </Drawer>
</div>
- </div>
- )}
-
- {peers.length === 0 && (
- <EmptyState
- icon={Network}
- title="No peers registered yet"
- message="Add another PortOS instance by its Tailscale IP address to federate records between your machines."
- actionLabel="Add your first peer"
- onAction={() => peerAddressRef.current?.focus()}
- />
- )}
- </div>
+ )} />
+ )} />
);
}
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 0f134c376a..598601fb97 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -1,14 +1,20 @@
+import { MemoryRouter } from 'react-router';
+import * as api from '../services/api';
+import socket from '../services/socket';
import { TailcatServeProvider } from '../components/instances/TailcatServeProvider';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render as renderUI, screen, within, fireEvent, waitFor, act } from '@testing-library/react';
import TailcatServePanel from '../components/instances/TailcatServePanel';
-import { AddPeerForm, PeerCard } from './Instances.jsx';
+import Instances, { AddPeerForm, PeerCard } from './Instances.jsx';
import { DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';
import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
import { addPeer, addTailcatPeer, startTailcatServe, getTailcatServe, stopTailcatServe, removePeer, listPeerSubscriptions, getPeerFullSyncCoverage, syncPeer } from '../services/api';
vi.mock('../services/api', () => ({
getInstances: vi.fn(),
+ getSettings: vi.fn().mockResolvedValue({}),
+ updateSettings: vi.fn(),
+ getCosJob: vi.fn().mockResolvedValue(null),
updateSelfInstance: vi.fn(),
addPeer: vi.fn(),
addTailcatPeer: vi.fn(),
@@ -276,3 +282,84 @@ describe('PeerCard snapshot progress', () => {
expect(badge('Pipeline').getByText('synced')).toBeInTheDocument();
});
});
+
+
+describe('Instances page connection drawers', () => {
+ const peer = { id: 'page-peer', name: 'Office', status: 'online', enabled: true, address: '192.0.2.10', port: 5555 };
+ beforeEach(() => {
+ api.getInstances.mockResolvedValue({ self: { name: 'Home' }, peers: [peer] });
+ api.getTailnetInfo.mockResolvedValue({ suffix: 'example', self: 'home' });
+ api.getNetworkExposure.mockResolvedValue({ setup: { complete: true } });
+ api.getBrainParityReports.mockResolvedValue({ reports: {} });
+ api.getSettings.mockResolvedValue({});
+ api.getTailcatForwards.mockResolvedValue({ forwards: [] });
+ api.getTailcatServe.mockResolvedValue({ status: 'stopped', live: false });
+ api.listPeerSubscriptions.mockResolvedValue({ subscriptions: [] });
+ });
+
+ // Regression: the full setup stack displaced peer actions, and moving it to
+ // remounting drawers could discard drafts or accidentally start networking.
+ it('prioritizes peers and retains drafts across drawer sections and failed adds', async () => {
+ renderUI(<MemoryRouter><Instances /></MemoryRouter>);
+ expect(await screen.findByRole('button', { name: 'Sync now' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Probe now' })).toBeEnabled();
+ expect(screen.queryByLabelText('Peer address')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Add peer' }));
+ expect(screen.getByLabelText('Peer address')).toHaveFocus();
+ fireEvent.change(screen.getByLabelText('Peer address'), { target: { value: '192.0.2.30' } });
+ api.addPeer.mockRejectedValueOnce(new Error('Unavailable'));
+ fireEvent.click(screen.getByRole('button', { name: 'Add', exact: true }));
+ await waitFor(() => expect(api.addPeer).toHaveBeenCalled());
+ expect(screen.getByLabelText('Peer address')).toHaveValue('192.0.2.30');
+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat', exact: true }));
+ fireEvent.change(screen.getByLabelText('Tailcat address'), { target: { value: 'tcEXAMPLE' } });
+ fireEvent.click(screen.getByRole('button', { name: 'They dial us' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Close add peer' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Connection settings', exact: true }));
+ const dialog = screen.getByRole('dialog');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Edit', exact: true }));
+ fireEvent.change(screen.getByLabelText('Instance name'), { target: { value: 'Draft name' } });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Connection settings sections' }), { target: { value: 'relay' } });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Connection settings sections' }), { target: { value: 'instance' } });
+ expect(screen.getByLabelText('Instance name')).toHaveValue('Draft name');
+ fireEvent.click(screen.getByRole('button', { name: 'Close settings' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Add peer' }));
+ expect(screen.getByRole('button', { name: 'They dial us' })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(screen.getByRole('button', { name: 'Dial them' }));
+ expect(screen.getByLabelText('Tailcat address')).toHaveValue('tcEXAMPLE');
+ fireEvent.click(screen.getByRole('button', { name: 'Host / port' }));
+ expect(screen.getByLabelText('Peer address')).toHaveValue('192.0.2.30');
+ expect(api.startTailcatServe).not.toHaveBeenCalled();
+ expect(api.syncPeer).not.toHaveBeenCalled();
+ expect(api.probePeer).not.toHaveBeenCalled();
+ expect(api.updateSettings).not.toHaveBeenCalled();
+ });
+
+ // Regression: removing the last peer must not hide orphan/serve recovery or
+ // the saved route that would keep unattended rendering pointed at that peer.
+ it('keeps actionable recovery and the add CTA after the last peer disappears', async () => {
+ api.getTailcatForwards.mockResolvedValue({ forwards: [{ id: 'orphan', peerId: peer.id, name: 'Saved forward', status: 'failed', remotePort: 5558 }] });
+ api.getTailcatServe.mockResolvedValue({ status: 'failed', live: false });
+ api.getSettings.mockResolvedValue({ federation: { mediaRouting: { image: { peerId: peer.id, engine: 'comfy', modelId: 'old-model' } } } });
+ renderUI(<MemoryRouter><Instances /></MemoryRouter>);
+ await screen.findByRole('button', { name: 'Sync now' });
+ const updatePeers = socket.on.mock.calls.find(([event]) => event === 'instances:peers:updated')[1];
+ act(() => updatePeers([]));
+ fireEvent.click(await screen.findByRole('button', { name: /Tailcat needs attention/ }));
+ expect(await screen.findByText('Saved forward')).toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: 'Retry', exact: true })).toHaveLength(2);
+ fireEvent.click(screen.getByRole('button', { name: 'Close settings' }));
+ fireEvent.click(screen.getByRole('button', { name: /render routing needs attention/ }));
+ const select = screen.getByLabelText('Image');
+ expect(select).toBeEnabled();
+ api.updateSettings.mockImplementation(async (patch) => patch);
+ api.getSettings.mockResolvedValue({ federation: { mediaRouting: { image: { peerId: peer.id, engine: 'comfy', modelId: 'old-model' } } } });
+ fireEvent.change(select, { target: { value: '' } });
+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledWith({ federation: { mediaRouting: { image: null } } }, { silent: true }));
+ fireEvent.click(screen.getByRole('button', { name: 'Close settings' }));
+ expect(screen.queryByRole('button', { name: /render routing needs attention/ })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Add your first peer' }));
+ expect(screen.getByRole('dialog', { name: 'Add peer' })).toBeInTheDocument();
+ expect(screen.getByLabelText('Peer address')).toHaveFocus();
+ });
+});