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
Defer peer sync polling until Tailscale is connected
Adam Eivy78bf08b7865d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3552ae4281..db42a56257 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,10 @@- **[issue-1975] View system logs straight from a failed AI run.** Failed runs in **Dev Tools → AI Runs History** now have a **View System Logs** button (both a quick icon on the collapsed row and a labeled button in the expanded error panel) that pops open the relevant PortOS system log — `portos-cos` for CoS-agent runs, `portos-server` for everything else — so an operator who doesn't know where the logs live can read the full error context without leaving the page. The log viewer includes a process picker and a tail-length selector, and is a reusable `ProcessLogModal` that any part of the app can open. (Closes #1975)- **[issue-1946] Download full videos from a YouTube or x.com URL.** A new **Dev Tools → Video Downloader** page lets you paste a YouTube (video/shorts/youtu.be) or x.com/Twitter status URL and download the *full video* (not just the audio, which is #1945's job) via `yt-dlp` — the same host dependency the music-video track import already uses. The clip lands in your video storage as a distinguishable `downloaded-<id>.mp4`, gets an auto-generated thumbnail, and — because it's written as a `source: 'download'` entry into the shared video-history store — also shows up in your media gallery alongside AI-generated renders (no new "library" concept; the existing media asset index picks it up through the same completed-video path it already uses, and prunes it on delete). Download progress streams live (download % → merging → finalizing) with a Cancel button, and the page lists everything you've downloaded (thumbnail, title, source link, age) with delete. x.com/Twitter pulls are best-effort — login-walled or rate-limited posts surface a clear error rather than a generic failure. Long/huge downloads are bounded (≤1h, ≤2GB) so a livestream or archive URL can't eat disk unbounded. `POST /api/devtools/video-download` (`server/services/videoDownload.js`, `server/routes/videoDownload.js`) mirrors #1945's async-job/SSE pattern. (Closes #1946)+## Federation++- **Peer sync polling now defers until Tailscale is actually connected.** A machine that booted off-tailnet (e.g. a laptop with Tailscale stopped) would immediately start probing every configured peer's MagicDNS hostname, spamming the logs with `⚠️ Probe failed … DNS lookup failed for X — is Tailscale MagicDNS up?` + escalating `⏳ Peer X backoff` lines on a 30s loop. `startPolling()` now checks the Tailscale backend state at boot (new `getTailscaleStatus`/`isTailscaleUp` in `server/lib/tailscale.js`, which reads `tailscale status --json` — `BackendState: "Running"` vs `"Stopped"`, so a mere "binary installed" check isn't mistaken for "connected"). When peers are configured but Tailscale isn't connected, probing is deferred with a single `🌐 Peer sync deferred …` line and a lightweight 60s watcher that starts the real probe loop automatically the moment Tailscale comes up — no manual "sync now" needed. Solo installs with no peers are unchanged (they never probe Tailscale at all). (`server/services/instances.js`, `server/lib/tailscale.js`)+## Pipeline- **[issue-1970] Pipeline image-gen drawers now group their settings into labeled sections.** The "Reference image gen" (NounsStage) and "Comic page image gen" (ComicScriptStage) config drawers previously rendered the shared `ImageGenSettingsForm` as one flat scroll; they now show three organized sections — **Backend**, **Model & LoRA**, and **Prompts & Style** — so the backend picker, per-model controls grid, and prompt/style textareas are visually separated instead of running together. Both drawers open at the `md` size so the per-model controls grid isn't cramped. The organization is opt-in via a new `grouped` prop on `ImageGenSettingsForm`, so the form's in-page host (UniverseBuilder's Batch-render card) keeps its existing flat layout unchanged. All controls and save/apply behavior are preserved — this is layout-only. The Backend section is dropped (leaving just the "no backend configured" warning) when no backend is available, and the Prompts & Style section is dropped when both style fields and the preset picker are hidden, so no empty section card ever shows. (`client/src/components/imageGen/ImageGenSettingsForm.jsx`, `client/src/components/pipeline/stages/NounsStage.jsx`, `client/src/components/pipeline/stages/ComicScriptStage.jsx`) (Closes #1970)diff --git a/server/lib/README.md b/server/lib/README.mdindex 52fa854864..422acd7465 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -166,7 +166,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sharingOrigin.js` | Origin metadata for records imported from share buckets. || `syncIntegrity.js` | Pure diff of local vs remote manifest lists. `INTEGRITY_STATUS` constants + `computeRecordIntegrity(localList, remoteList)` — classifies each record as `in-parity`, `local-only`, `peer-only`, `diverged`, or `assets-missing`. No I/O. || `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). |-| `tailscale.js` | Locate the Tailscale CLI binary and flag the sandboxed macOS App-bundle build (which can't write `tailscale cert` output outside its container). |+| `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build (which can't write `tailscale cert` output outside its container), and read backend state (`getTailscaleStatus` / `isTailscaleUp`) to know whether we're actually connected to the tailnet. || `httpsState.js` | Captures whether PortOS booted with HTTPS active. || `networkExposure.js` | Snapshot of scheme + bind + cert mode for the dashboard's Network Exposure widget. |diff --git a/server/lib/tailscale.js b/server/lib/tailscale.jsindex a63a6ca1c6..8a3166935f 100644--- a/server/lib/tailscale.js+++ b/server/lib/tailscale.js@@ -1,5 +1,10 @@import { existsSync } from 'fs';import { join, delimiter } from 'path';+import { execFile } from 'child_process';+import { promisify } from 'util';+import { safeJSONParse } from './fileUtils.js';++const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';const TAILSCALE_BIN = IS_WIN ? 'tailscale.exe' : 'tailscale';@@ -46,6 +51,49 @@ export function isSandboxedTailscale(binPath) {return binPath === MACOS_TAILSCALE_APP_BUNDLE;}+/**+ * Read the Tailscale backend state via `tailscale status --json`.+ *+ * Distinguishes the states that matter for deciding whether federated peer+ * probing is worth attempting — the CLI cleanly exits 0 with+ * `BackendState: "Stopped"` when Tailscale is installed but not connected, so a+ * mere "binary exists" check (findTailscale) is NOT enough to know we're on the+ * tailnet. Returns:+ * - available: the CLI binary was found+ * - running: BackendState === 'Running' (connected to the tailnet)+ * - state: raw BackendState string, or null when unknown+ * - reason: machine-readable classification for logs/UI+ *+ * Never throws — execFile failures and non-JSON output degrade to a+ * not-running result so callers can treat this as a plain boolean gate.+ */+export async function getTailscaleStatus() {+ const bin = findTailscale();+ if (!bin) return { available: false, running: false, state: null, reason: 'tailscale-not-installed' };+ const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 })+ .catch(() => ({ stdout: null }));+ if (!stdout) return { available: true, running: false, state: null, reason: 'tailscale-status-failed' };+ // Guard against non-JSON output (warnings, partial reads) so we never throw.+ const status = safeJSONParse(stdout, null);+ if (!status) return { available: true, running: false, state: null, reason: 'tailscale-parse-error' };+ const state = status.BackendState ?? null;+ return {+ available: true,+ running: state === 'Running',+ state,+ reason: state === 'Running' ? 'running' : `tailscale-${(state || 'unknown').toLowerCase()}`+ };+}++/**+ * Convenience boolean: true only when Tailscale is installed AND connected to+ * the tailnet (BackendState === 'Running').+ */+export async function isTailscaleUp() {+ const { running } = await getTailscaleStatus();+ return running;+}+export function hasOnlySandboxedTailscale() {if (process.platform !== 'darwin') return false;// True iff the MAS app bundle exists AND no unsandboxed binary isdiff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.jsindex 1431765f97..68864c7bf2 100644--- a/server/lib/tailscale.test.js+++ b/server/lib/tailscale.test.js@@ -4,11 +4,18 @@ vi.mock('fs', () => ({existsSync: vi.fn()}));+vi.mock('child_process', () => ({+ execFile: vi.fn()+}));+import { existsSync } from 'fs';+import { execFile } from 'child_process';import {findTailscale,isSandboxedTailscale,hasOnlySandboxedTailscale,+ getTailscaleStatus,+ isTailscaleUp,MACOS_TAILSCALE_APP_BUNDLE} from './tailscale.js';@@ -137,3 +144,60 @@ describe('hasOnlySandboxedTailscale', () => {expect(hasOnlySandboxedTailscale()).toBe(false);});});++describe('getTailscaleStatus / isTailscaleUp', () => {+ let originalPath;++ beforeEach(() => {+ originalPath = process.env.PATH;+ vi.clearAllMocks();+ // Default: a Tailscale binary exists at a known candidate path.+ existsSync.mockImplementation((p) => p === '/opt/homebrew/bin/tailscale');+ });++ afterEach(() => {+ process.env.PATH = originalPath;+ });++ // promisify(execFile) with no custom symbol resolves with the value passed as+ // the callback's first non-error arg — so returning { stdout } matches how the+ // real (custom-promisified) execFile resolves { stdout, stderr }.+ const mockStatusJSON = (obj) => {+ execFile.mockImplementation((cmd, args, opts, cb) => cb(null, { stdout: JSON.stringify(obj) }));+ };++ it('reports not-installed when no binary is found', async () => {+ existsSync.mockReturnValue(false);+ process.env.PATH = '';+ const status = await getTailscaleStatus();+ expect(status).toEqual({ available: false, running: false, state: null, reason: 'tailscale-not-installed' });+ expect(execFile).not.toHaveBeenCalled();+ expect(await isTailscaleUp()).toBe(false);+ });++ it('reports running when BackendState is Running', async () => {+ mockStatusJSON({ BackendState: 'Running' });+ const status = await getTailscaleStatus();+ expect(status).toMatchObject({ available: true, running: true, state: 'Running', reason: 'running' });+ expect(await isTailscaleUp()).toBe(true);+ });++ it('reports not-running when Tailscale is installed but Stopped', async () => {+ mockStatusJSON({ BackendState: 'Stopped' });+ const status = await getTailscaleStatus();+ expect(status).toMatchObject({ available: true, running: false, state: 'Stopped', reason: 'tailscale-stopped' });+ expect(await isTailscaleUp()).toBe(false);+ });++ it('degrades to not-running when the CLI errors', async () => {+ execFile.mockImplementation((cmd, args, opts, cb) => cb(new Error('boom')));+ const status = await getTailscaleStatus();+ expect(status).toMatchObject({ available: true, running: false, state: null, reason: 'tailscale-status-failed' });+ });++ it('degrades to not-running on non-JSON output', async () => {+ execFile.mockImplementation((cmd, args, opts, cb) => cb(null, { stdout: 'not json at all' }));+ const status = await getTailscaleStatus();+ expect(status).toMatchObject({ available: true, running: false, state: null, reason: 'tailscale-parse-error' });+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex 080e605002..52f3f13663 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -17,12 +17,17 @@ import { peerBaseUrl } from '../lib/peerUrl.js';import { peerFetch } from '../lib/peerHttpClient.js';import { withAbortTimeout } from '../lib/abortTimeout.js';import { getSelfHost } from '../lib/peerSelfHost.js';+import { getTailscaleStatus } from '../lib/tailscale.js';import { autoSubscribePeerToAllRecords } from './sharing/recordEvents.js';const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;const POLL_INTERVAL_MS = 30000;const INITIAL_PROBE_DELAY_MS = 2000;+// While peer probing is deferred (Tailscale not connected at boot), re-check+// Tailscale on this cadence and start polling the moment it comes up — so the+// user just has to connect Tailscale, no manual "sync now" required.+const TAILSCALE_RECHECK_MS = 60_000;// Sentinel returned by getInstanceId() and stamped onto sender/peer fields when// the local identity hasn't been initialized yet. Every consumer that fans@@ -45,6 +50,11 @@ const BACKOFF_TIERS_MS = [const withLock = createMutex();let pollTimer = null;+// Set while we're waiting for Tailscale to connect before starting the real+// probe loop (see startPolling). Kept separate from pollTimer so stopPolling can+// tear down either state, and so the boot gate is idempotent under double-start.+let tailscaleWatchTimer = null;+let pollingStartPending = false;function classifyProbeError(err, peer) {const code = err?.code;@@ -1037,12 +1047,15 @@ async function markDirection(peerId, direction) {// --- Polling ----export function startPolling() {+// Actually create the probe schedule (backoff clear + initial probe + interval).+// Idempotent: a no-op if the loop is already running.+function beginPolling() {if (pollTimer) return;console.log(`🌐 Instance polling started (${POLL_INTERVAL_MS / 1000}s interval)`);// Backoff is a rate limit on the polling loop, not a durable judgment about- // the peer — boot may itself be the deploy that fixes connectivity, so clear it.+ // the peer — boot (or a fresh Tailscale connect) may itself be the event that+ // fixes connectivity, so clear it.withData(async (data) => {let cleared = 0;for (const peer of data.peers) {@@ -1061,7 +1074,58 @@ export function startPolling() {pollTimer = setInterval(() => probeAllPeers(), POLL_INTERVAL_MS);}+// Decide whether to start probing now or defer until Tailscale connects.+// PortOS peers live on the tailnet, so probing their MagicDNS hostnames while+// Tailscale is down just spams DNS-failure + backoff logs (a laptop booted+// off-tailnet). When peers are configured but Tailscale isn't connected, defer+// and install a slow watcher that starts polling automatically once it's up.+async function evaluatePollingGate() {+ if (pollTimer || tailscaleWatchTimer) return;++ // No peers to probe → run the (silent, no-op) loop exactly as before and skip+ // the Tailscale probe entirely. Keeps solo single-machine installs unchanged.+ const data = await loadData();+ const hasEnabledPeers = Array.isArray(data.peers) && data.peers.some(p => p.enabled);+ if (!hasEnabledPeers) {+ beginPolling();+ return;+ }++ const status = await getTailscaleStatus();+ if (status.running) {+ beginPolling();+ return;+ }++ console.log(`🌐 Peer sync deferred — Tailscale not connected (${status.state || status.reason}); polling starts automatically once it's up`);+ tailscaleWatchTimer = setInterval(() => {+ getTailscaleStatus().then((s) => {+ if (!s.running) return;+ clearInterval(tailscaleWatchTimer);+ tailscaleWatchTimer = null;+ console.log('🌐 Tailscale connected — starting peer sync polling');+ beginPolling();+ }).catch(() => {});+ }, TAILSCALE_RECHECK_MS);+ // Don't let the recheck timer keep the process alive on its own.+ if (typeof tailscaleWatchTimer.unref === 'function') tailscaleWatchTimer.unref();+}++export function startPolling() {+ // pollingStartPending guards the async gap in evaluatePollingGate so two+ // synchronous startPolling() calls can't each spin up a schedule/watcher.+ if (pollTimer || tailscaleWatchTimer || pollingStartPending) return;+ pollingStartPending = true;+ evaluatePollingGate()+ .catch(err => console.error(`❌ Failed to start peer polling: ${err.message}`))+ .finally(() => { pollingStartPending = false; });+}+export function stopPolling() {+ if (tailscaleWatchTimer) {+ clearInterval(tailscaleWatchTimer);+ tailscaleWatchTimer = null;+ }if (pollTimer) {clearInterval(pollTimer);pollTimer = null;diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 2e5c1e6b18..38f2ff33bb 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -48,9 +48,14 @@ vi.mock('../lib/ports.js', () => ({DEFAULT_PEER_PORT: 5555}));+vi.mock('../lib/tailscale.js', () => ({+ getTailscaleStatus: vi.fn()+}));+// fetch is stubbed per-test in beforeEach and restored in afterEachimport { readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { getTailscaleStatus } from '../lib/tailscale.js';import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import {@@ -82,6 +87,7 @@ describe('instances.js', () => {vi.useFakeTimers();vi.stubGlobal('fetch', vi.fn());readJSONFile.mockResolvedValue({ self: null, peers: [] });+ getTailscaleStatus.mockResolvedValue({ available: true, running: true, state: 'Running', reason: 'running' });});afterEach(() => {@@ -1522,22 +1528,96 @@ describe('instances.js', () => {// --- Polling ---describe('startPolling / stopPolling', () => {- it('should start polling and not start twice', () => {+ let logSpy;++ beforeEach(() => {+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ afterEach(() => {+ logSpy.mockRestore();+ });++ // startPolling now defers to an async gate (loadData + Tailscale check);+ // flush the resolved-promise chain so the gate reaches beginPolling().+ const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); };+ const logged = (frag) => logSpy.mock.calls.some(c => String(c[0]).includes(frag));++ it('starts polling immediately with no peers (solo install), without probing Tailscale', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });+ getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });++ startPolling();+ await flush();++ expect(logged('Instance polling started')).toBe(true);+ // No peers → never even asks Tailscale.+ expect(getTailscaleStatus).not.toHaveBeenCalled();+ stopPolling();+ });++ it('starts polling when peers exist and Tailscale is connected', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true }] });+ getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });++ startPolling();+ await flush();++ expect(getTailscaleStatus).toHaveBeenCalled();+ expect(logged('Instance polling started')).toBe(true);+ expect(logged('Peer sync deferred')).toBe(false);+ stopPolling();+ });++ it('defers polling when peers exist but Tailscale is down, then starts once it comes up', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true }] });+ getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });startPolling();- startPolling(); // second call should be no-op+ await flush();++ expect(logged('Peer sync deferred')).toBe(true);+ expect(logged('Instance polling started')).toBe(false);++ // Tailscale connects; the recheck watcher should pick it up and start polling.+ getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });+ await vi.advanceTimersByTimeAsync(60_000);+ await flush();++ expect(logged('Tailscale connected — starting peer sync polling')).toBe(true);+ expect(logged('Instance polling started')).toBe(true);+ stopPolling();+ });++ it('does not start twice', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });- // Advance past initial probe delay- vi.advanceTimersByTime(2000);+ startPolling();+ startPolling(); // second call should be a no-op+ await flush();+ const starts = logSpy.mock.calls.filter(c => String(c[0]).includes('Instance polling started')).length;+ expect(starts).toBe(1);stopPolling();});- it('should stop polling cleanly', () => {+ it('stop clears a pending Tailscale watch so it never starts polling later', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true }] });+ getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });+startPolling();+ await flush();+ expect(logged('Peer sync deferred')).toBe(true);+stopPolling();stopPolling(); // double stop should be safe++ // Even if Tailscale comes up after stop, the (cleared) watcher must not fire.+ getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });+ await vi.advanceTimersByTimeAsync(60_000);+ await flush();++ expect(logged('Instance polling started')).toBe(false);});});});