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(instances): make peer host clear sticky and surface tailnet DNS setup
Adam Eivy47cbb0e43933
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92760a7ef9..8b053ec07d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Fixed+- **Reverting a peer to plain IP (after enabling Tailnet DNS) is now sticky.** When a user cleared a peer's `host` on the Instances page to switch the federation hop back to `http://<ip>`, the next inbound `peers/announce` from that peer would silently re-adopt the DNS name — the only safeguard was "is `existing.host` empty?", which couldn't distinguish "user explicitly cleared" from "never set yet." Added a `hostManual` flag on each peer record: latched to `true` whenever the user sets or clears the host via `PUT /api/instances/peers/:id`, and respected by `handleAnnounce` (auto-adoption is gated on `!existing.host && !existing.hostManual`). Fresh peers and peers that were auto-learned still receive automatic host updates from announces; only explicit user intervention pins the choice. Also added a one-click `use IP only` inline action on each peer's host editor and a discoverable banner at the top of the Instances page that summarizes Tailnet DNS state, surfaces the local instance's MagicDNS name in the SelfCard, and walks through the three-step setup (MagicDNS admin toggle → `npm run setup:cert` → click `use <host>` per peer). Files: `server/services/instances.js`, `server/services/instances.test.js`, `client/src/pages/Instances.jsx`.- **LM Studio auto-loads a model on "No models loaded" 400.** Any caller of `callProviderAISimple` (taste questionnaire, identity, autobiography, insights, jiraReports, goalCheckIn) that hit a cold LM Studio used to error out with `Provider returned 400: { ... "No models loaded" ... }`. Now on that specific error pattern, the helper lists LM Studio's downloaded LLMs via `/api/v0/models`, picks one (preferring `provider.defaultModel`, then any id in `provider.models` that's downloaded, else the first downloaded LLM), loads it via `POST /api/v1/models/load`, and retries the chat-completion. Mirrors the existing pattern in `services/memoryClassifier.js` but driven from the provider config so every API caller benefits. File: `server/lib/aiProvider.js`.- **Stop showing the same error toast 3-4 times.** A single failing API call could surface its error message multiple times because three independent channels all toasted the same payload: `apiCore.request` toasts on every non-OK response, the server emits both `io.emit('error:occurred')` (broadcast) and `errorEvents → broadcastToErrors('error:notified')` (subscriber) for the same error, and `useErrorNotifications` listened to *both* socket events with the same handler. Two changes: (1) `useErrorNotifications` now subscribes to the targeted `error:notified` channel only — `error:occurred` was the duplicate broadcast leg — and (2) the Toast layer added a content-based dedup window (1.5s) so any duplicate from any source is silently dropped. Explicit-`id` toasts (loading→success swaps) skip dedup so progress toasts still update in place. Files: `client/src/components/ui/Toast.jsx`, `client/src/hooks/useErrorNotifications.js`.- **Media Gen Video defaults to the smallest model.** The macOS default was LTX-2 Unified (~42 GB). New default is LTX-2.3 Distilled Q4 (~22 GB) so a fresh install fits on smaller machines without a manual override. File: `server/services/videoGen/local.js`.diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex e234362e84..f845ce108a 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -6,7 +6,8 @@ import {ArrowUpRight, ArrowDownLeft, ArrowLeftRight,Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, RefreshCcwDot, Timer,- Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight+ Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,+ Lock, Globe, Info} from 'lucide-react';import toast from '../components/ui/Toast';import socket from '../services/socket';@@ -79,7 +80,68 @@ function HealthSummary({ health, version }) {);}-function SelfCard({ self, onUpdate, syncStatus }) {+function TailnetHelpBanner({ tailnetInfo }) {+ const [collapsed, setCollapsed] = useState(() => {+ return localStorage.getItem('portos-tailnet-help-collapsed') === '1';+ });+ const toggle = () => {+ const next = !collapsed;+ setCollapsed(next);+ localStorage.setItem('portos-tailnet-help-collapsed', next ? '1' : '0');+ };++ const status = tailnetInfo === null+ ? { label: 'Tailscale DNS not detected', tone: 'warn', detail: 'Install Tailscale and enable MagicDNS in your tailnet admin to auto-suggest peer DNS names.' }+ : tailnetInfo?.suffix+ ? { label: `MagicDNS: ${tailnetInfo.suffix}`, tone: 'ok', detail: tailnetInfo.self ? `This instance: ${tailnetInfo.self}` : null }+ : { label: 'Tailscale running but MagicDNS suffix not found', tone: 'warn', detail: 'Enable MagicDNS in your tailnet admin console (login.tailscale.com/admin/dns).' };++ const ToneIcon = status.tone === 'ok' ? CheckCircle2 : AlertCircle;+ const toneClass = status.tone === 'ok' ? 'text-port-success' : 'text-port-warning';++ return (+ <div className="bg-port-card border border-port-border rounded-xl">+ <button+ onClick={toggle}+ className="w-full flex items-center gap-2 p-4 text-left"+ >+ <Lock size={16} className="text-port-accent shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-sm font-medium text-white">Tailnet DNS & trusted HTTPS</span>+ <span className={`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded ${toneClass} bg-port-bg`}>+ <ToneIcon size={10} /> {status.label}+ </span>+ </div>+ </div>+ {collapsed ? <ChevronRight size={14} className="text-gray-500" /> : <ChevronDown size={14} className="text-gray-500" />}+ </button>++ {!collapsed && (+ <div className="px-4 pb-4 -mt-1 text-xs text-gray-400 space-y-2">+ {status.detail && (+ <div className="flex items-start gap-1.5">+ <Info size={11} className="mt-0.5 text-gray-500 shrink-0" />+ <span className="font-mono">{status.detail}</span>+ </div>+ )}+ <p>+ By default, federation traffic uses <span className="font-mono text-gray-300">http://{`<ip>`}:5555</span>. Setting a Tailscale MagicDNS host on a peer+ switches that hop to <span className="font-mono text-gray-300">https://{`<host>`}.{tailnetInfo?.suffix || `<tailnet>`}.ts.net</span> with a+ browser-trusted Let's Encrypt cert provisioned by Tailscale.+ </p>+ <ol className="list-decimal list-inside space-y-1 text-gray-500">+ <li>On each instance, enable MagicDNS + HTTPS Certificates in your tailnet admin (<span className="font-mono">login.tailscale.com/admin/dns</span>).</li>+ <li>Run <span className="font-mono text-gray-300">npm run setup:cert</span> on each instance to fetch the cert.</li>+ <li>Below, click <span className="text-port-accent">use {`<host>`}</span> on each peer to switch the link to HTTPS. Or click <span className="text-gray-400">use IP only</span> to revert.</li>+ </ol>+ </div>+ )}+ </div>+ );+}++function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {const [editing, setEditing] = useState(false);const [name, setName] = useState('');@@ -133,6 +195,19 @@ function SelfCard({ self, onUpdate, syncStatus }) {)}</div><p className="text-xs text-gray-500 font-mono">{self.instanceId}</p>+ {tailnetInfo?.self ? (+ <div className="flex items-center gap-1.5 text-[11px] mt-1" title="This instance's Tailscale MagicDNS name — peers can reach you over HTTPS at this name">+ <Globe size={11} className="text-port-accent" />+ <span className="font-mono text-port-accent">{tailnetInfo.self}</span>+ <span className="text-gray-600">·</span>+ <span className="text-gray-500">tailnet DNS</span>+ </div>+ ) : tailnetInfo === null ? null : (+ <div className="flex items-center gap-1.5 text-[11px] mt-1 text-gray-500" title="No MagicDNS name detected for this instance">+ <Globe size={11} />+ <span>No tailnet DNS — peers will reach you by IP</span>+ </div>+ )}{syncStatus?.local && (<div className="mt-2 pt-2 border-t border-port-border/50 grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-gray-400"><span className="flex items-center gap-1.5">@@ -551,6 +626,15 @@ function PeerHostEditor({ peer, onRefresh, tailnetInfo }) {);}+ const clearHost = async () => {+ setSaving(true);+ const result = await updatePeer(peer.id, { host: null }).catch(() => null);+ setSaving(false);+ if (!result) return;+ onRefresh();+ toast.success('Reverted to IP — federation hop will use http://<ip>');+ };+return (<div className="mt-0.5 flex items-center gap-1.5 flex-wrap">{peer.host ? (@@ -569,6 +653,16 @@ function PeerHostEditor({ peer, onRefresh, tailnetInfo }) {>{peer.host ? 'edit' : (suggestion ? `use ${suggestion}` : 'set DNS')}</button>+ {peer.host && (+ <button+ onClick={clearHost}+ disabled={saving}+ className="text-[10px] text-gray-500 hover:text-white underline disabled:opacity-50"+ title="Switch this hop back to http://<ip>"+ >+ use IP only+ </button>+ )}</div>);}@@ -779,8 +873,10 @@ export default function Instances() {<span className="text-sm text-gray-500">PortOS Federation</span></div>+ <TailnetHelpBanner tailnetInfo={tailnetInfo} />+<div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <SelfCard self={self} onUpdate={fetchData} syncStatus={syncStatus} />+ <SelfCard self={self} onUpdate={fetchData} syncStatus={syncStatus} tailnetInfo={tailnetInfo} /><AddPeerForm onAdd={fetchData} /></div>diff --git a/server/services/instances.js b/server/services/instances.jsindex 48601f88cb..19dd828f65 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -167,6 +167,11 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host })id: crypto.randomUUID(),address,host: normalizedHost || null,+ // Set to true once the user explicitly chooses a host (set/clear via UI).+ // Once true, handleAnnounce never auto-overwrites — it's the only way to+ // honor "the user explicitly cleared this; stay on IP" against a peer+ // that keeps announcing its DNS name.+ hostManual: !!normalizedHost,port,name: validName(name, normalizedHost || address),instanceId: null,@@ -217,6 +222,10 @@ export async function updatePeer(id, updates) {const normalized = validHost(updates.host);if (normalized !== undefined && normalized !== peer.host) {peer.host = normalized; // null clears, string sets+ // Latch manual mode so handleAnnounce stops auto-learning (esp.+ // important for clears — without this the next inbound announce+ // re-adopts the DNS name and the user can't revert to IP).+ peer.hostManual = true;hostChanged = true;console.log(`🌐 Peer host ${peer.host ? `set to ${peer.host}` : 'cleared'}: ${peer.name}`);}@@ -390,9 +399,11 @@ export async function handleAnnounce({ address, port, instanceId, name, host })if (sanitized && isIPAddress(existing.name)) {existing.name = sanitized;}- // Adopt host from inbound announce only when we don't already have one —- // never overwrite a user-set value, never blank one on a noisy announce.- if (normalizedHost && !existing.host) {+ // Adopt host from inbound announce only when we don't already have one+ // AND the user hasn't manually intervened. The hostManual flag covers+ // the "user explicitly cleared this — stay on IP" case that the+ // existing.host check alone can't distinguish from "never set".+ if (normalizedHost && !existing.host && !existing.hostManual) {existing.host = normalizedHost;console.log(`🌐 Peer host learned via announce: ${existing.name} → ${normalizedHost}`);}@@ -409,6 +420,9 @@ export async function handleAnnounce({ address, port, instanceId, name, host })id: crypto.randomUUID(),address,host: normalizedHost || null,+ // The host came from the peer's announce, not from a user — leave+ // hostManual false so subsequent updates from the peer can still refine.+ hostManual: false,port,name: validName(name, normalizedHost || address),instanceId,diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex db0937fce3..b60819857a 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -223,6 +223,26 @@ describe('instances.js', () => {expect(peer.port).toBe(8080);});++ it('should default hostManual to false when no host provided (allow auto-learn)', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ fetch.mockRejectedValue(new Error('not reachable'));++ const peer = await addPeer({ address: '10.0.0.6' });++ expect(peer.host).toBeNull();+ expect(peer.hostManual).toBe(false);+ });++ it('should latch hostManual when host is provided at add time', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ fetch.mockRejectedValue(new Error('not reachable'));++ const peer = await addPeer({ address: '10.0.0.7', host: 'machine.taile8179.ts.net' });++ expect(peer.host).toBe('machine.taile8179.ts.net');+ expect(peer.hostManual).toBe(true);+ });});describe('removePeer', () => {@@ -315,6 +335,26 @@ describe('instances.js', () => {expect(result.host).toBeNull();});+ it('should latch hostManual when user explicitly sets host', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: null, hostManual: false }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ const result = await updatePeer('peer-1', { host: 'machine.taile8179.ts.net' });++ expect(result.host).toBe('machine.taile8179.ts.net');+ expect(result.hostManual).toBe(true);+ });++ it('should latch hostManual when user explicitly clears host (the un-revert bug)', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'machine.taile8179.ts.net', hostManual: false }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ const result = await updatePeer('peer-1', { host: '' });++ expect(result.host).toBeNull();+ expect(result.hostManual).toBe(true);+ });+it('should ignore invalid host (leave unchanged)', async () => {const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'good.example.com' }];readJSONFile.mockResolvedValue({ self: null, peers });@@ -751,6 +791,61 @@ describe('instances.js', () => {expect(result.peer.host).toBe('manual.example.ts.net');});+ it('should not re-adopt host on cleared peer when hostManual is true', async () => {+ // Reproduces the original "can't undo Tailnet DNS" bug: user cleared+ // peer.host, but the next inbound announce silently re-adopted the DNS+ // name because the only safeguard was "is existing.host empty?".+ const existing = {+ id: 'p1',+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: null,+ hostManual: true,+ status: 'offline',+ directions: ['outbound']+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [existing] });++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'null.taile8179.ts.net'+ });++ expect(result.peer.host).toBeNull();+ expect(result.peer.hostManual).toBe(true);+ });++ it('should still learn host on a fresh peer when hostManual is unset', async () => {+ // Auto-learn must remain the default for never-touched peers — only+ // explicit user intervention should latch hostManual.+ const existing = {+ id: 'p1',+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: null,+ status: 'offline',+ directions: ['outbound']+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [existing] });++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'null.taile8179.ts.net'+ });++ expect(result.peer.host).toBe('null.taile8179.ts.net');+ });+it('should drop invalid host strings via validHost', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });fetch.mockRejectedValue(new Error('offline'));