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

address review (claude): cancel in-flight start on stop, guard stale watcher, don't strand LAN peers

Adam Eivy31bbd33b8ca0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index db42a56257..ab97a2f8bd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -43,7 +43,7 @@
## 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`)
+- **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 *every* enabled peer is tailnet-only (a `*.ts.net` MagicDNS host or a `100.64.0.0/10` CGNAT address) and 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. A peer reachable without Tailscale (plain LAN IP or non-tailnet DNS host) is never deferred; it's probed immediately as before. Solo installs with no peers are unchanged (they never probe Tailscale at all). (`server/services/instances.js`, `server/lib/tailscale.js`)
## Pipeline
diff --git a/server/services/instances.js b/server/services/instances.js
index 52f3f13663..ba33884d48 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -55,6 +55,11 @@ let pollTimer = null;
// tear down either state, and so the boot gate is idempotent under double-start.
let tailscaleWatchTimer = null;
let pollingStartPending = false;
+// Bumped by stopPolling() to cancel any in-flight startPolling gate or deferred
+// watcher callback that is mid-await when the stop lands — without it, a stop
+// during the async window is a silent no-op and a timer gets created after stop
+// was requested.
+let pollingGeneration = 0;
function classifyProbeError(err, peer) {
const code = err?.code;
@@ -1074,41 +1079,68 @@ function beginPolling() {
pollTimer = setInterval(() => probeAllPeers(), POLL_INTERVAL_MS);
}
+// A peer we can only reach over the tailnet: its probe URL (see peerBaseUrl)
+// resolves to a MagicDNS name (*.ts.net) or a Tailscale CGNAT address
+// (100.64.0.0/10 for IPv4, fd7a:115c:a1e0::/48 for IPv6). A peer addressed by a
+// plain LAN/routable IP or a non-tailnet DNS host is reachable with Tailscale
+// down, so it must NOT be deferred by the gate below.
+function peerRequiresTailscale(peer) {
+ if (peer.host) return /\.ts\.net$/i.test(peer.host.trim());
+ const addr = (peer.address || '').trim();
+ const v4 = addr.match(/^100\.(\d{1,3})\./);
+ if (v4) {
+ const second = Number(v4[1]);
+ if (second >= 64 && second <= 127) return true; // 100.64.0.0/10 CGNAT
+ }
+ if (/^fd7a:115c:a1e0:/i.test(addr)) return true; // Tailscale IPv6 ULA
+ return false;
+}
+
// 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() {
+// Probing a tailnet-only peer's MagicDNS hostname while Tailscale is down just
+// spams DNS-failure + backoff logs (a laptop booted off-tailnet). So we defer
+// ONLY when every enabled peer is tailnet-dependent; a LAN/IP-reachable peer is
+// probed immediately (it doesn't need Tailscale). While deferred, a slow watcher
+// starts polling automatically the moment Tailscale connects. `gen` is captured
+// at startPolling time so a stopPolling() during either await aborts cleanly.
+async function evaluatePollingGate(gen) {
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) {
+ if (gen !== pollingGeneration) return; // stopPolling() landed during loadData
+ const enabledPeers = Array.isArray(data.peers) ? data.peers.filter(p => p.enabled) : [];
+
+ // No peers, or at least one peer reachable without Tailscale → run the loop
+ // now (silent no-op when there are no peers). Only an all-tailnet peer set
+ // gets deferred, so solo installs and LAN peers are unaffected.
+ const needsTailscale = enabledPeers.length > 0 && enabledPeers.every(peerRequiresTailscale);
+ if (!needsTailscale) {
beginPolling();
return;
}
const status = await getTailscaleStatus();
+ if (gen !== pollingGeneration) return; // stopPolling() landed during status check
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(() => {
+ // Capture the handle locally so a stale in-flight callback can't clear/null a
+ // watcher installed by a later startPolling() (identity guard below).
+ const myTimer = setInterval(() => {
getTailscaleStatus().then((s) => {
- if (!s.running) return;
- clearInterval(tailscaleWatchTimer);
+ if (!s.running || tailscaleWatchTimer !== myTimer) return;
+ clearInterval(myTimer);
tailscaleWatchTimer = null;
console.log('🌐 Tailscale connected — starting peer sync polling');
beginPolling();
}).catch(() => {});
}, TAILSCALE_RECHECK_MS);
+ tailscaleWatchTimer = myTimer;
// Don't let the recheck timer keep the process alive on its own.
- if (typeof tailscaleWatchTimer.unref === 'function') tailscaleWatchTimer.unref();
+ if (typeof myTimer.unref === 'function') myTimer.unref();
}
export function startPolling() {
@@ -1116,12 +1148,15 @@ export function startPolling() {
// synchronous startPolling() calls can't each spin up a schedule/watcher.
if (pollTimer || tailscaleWatchTimer || pollingStartPending) return;
pollingStartPending = true;
- evaluatePollingGate()
+ const gen = pollingGeneration;
+ evaluatePollingGate(gen)
.catch(err => console.error(`❌ Failed to start peer polling: ${err.message}`))
.finally(() => { pollingStartPending = false; });
}
export function stopPolling() {
+ // Invalidate any in-flight startPolling gate / deferred watcher callback.
+ pollingGeneration++;
if (tailscaleWatchTimer) {
clearInterval(tailscaleWatchTimer);
tailscaleWatchTimer = null;
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 38f2ff33bb..91c9d7ff4b 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -1556,8 +1556,8 @@ describe('instances.js', () => {
stopPolling();
});
- it('starts polling when peers exist and Tailscale is connected', async () => {
- readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true }] });
+ it('starts polling when tailnet peers exist and Tailscale is connected', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });
startPolling();
@@ -1569,8 +1569,24 @@ describe('instances.js', () => {
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 }] });
+ it('probes immediately for a LAN/IP peer even when Tailscale is down (never stranded)', async () => {
+ // A peer addressed by a plain LAN IP (no MagicDNS host, not a CGNAT addr)
+ // is reachable without Tailscale, so the gate must not defer it.
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'lan', enabled: true, address: '192.168.1.50' }] });
+ getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });
+
+ startPolling();
+ await flush();
+
+ expect(logged('Instance polling started')).toBe(true);
+ expect(logged('Peer sync deferred')).toBe(false);
+ // A non-tailnet peer means we don't even need to ask Tailscale.
+ expect(getTailscaleStatus).not.toHaveBeenCalled();
+ stopPolling();
+ });
+
+ it('defers polling when all peers are tailnet-only and Tailscale is down, then starts once it comes up', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });
startPolling();
@@ -1602,7 +1618,7 @@ describe('instances.js', () => {
});
it('stop clears a pending Tailscale watch so it never starts polling later', async () => {
- readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true }] });
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });
startPolling();
@@ -1619,5 +1635,23 @@ describe('instances.js', () => {
expect(logged('Instance polling started')).toBe(false);
});
+
+ it('aborts startup if stopPolling is called during the async gate window', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
+ getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });
+
+ startPolling(); // kicks off the async gate (loadData → getTailscaleStatus)
+ stopPolling(); // lands before the gate resolves — must cancel it
+ await flush();
+
+ // The generation bump makes the resolving gate bail before beginPolling().
+ expect(logged('Instance polling started')).toBe(false);
+
+ // And a fresh start afterward still works (state wasn't left wedged).
+ startPolling();
+ await flush();
+ expect(logged('Instance polling started')).toBe(true);
+ stopPolling();
+ });
});
});