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: retry the post-update dashboard auto-open instead of trying once

Adam Eivya05674883aaf
diff --git a/scripts/open-ui-in-browser.js b/scripts/open-ui-in-browser.js
index e1517c9549..73c70ef49f 100644
--- a/scripts/open-ui-in-browser.js
+++ b/scripts/open-ui-in-browser.js
@@ -10,40 +10,27 @@ import { fileURLToPath } from 'node:url';
import { hasTailscaleCert } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
import { getCliSetupGuide } from './setup-guide.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const { dir: CERT_DIR } = certPaths(join(ROOT, 'data'));
const API_PORT = Number(process.env.PORT) || 5555;
const HTTP_LOOPBACK_PORT = Number(process.env.PORTOS_HTTP_PORT) || 5553;
-// Share the same cert predicate the server's HTTPS gate uses (file presence
-// AND PEM parseability). A presence-only check would route us to :5553 even
-// when corrupt PEMs forced the server back to plain HTTP-on-:5555, so the
-// poll would time out on a port the server never bound.
-const HTTPS_MODE = hasTailscaleCert(CERT_DIR);
-
-// When HTTPS is on, :5555 speaks TLS only — plain http:// requests hit a TLS
-// mismatch and time out. The loopback HTTP mirror on :5553 serves the same
-// app and skips the cert warning, so startup polling always stays local even
-// when the final browser destination is the trusted MagicDNS origin.
-const LOCAL_BASE = HTTPS_MODE
- ? `http://localhost:${HTTP_LOOPBACK_PORT}`
- : `http://localhost:${API_PORT}`;
-// Poll through loopback so certificate trust never delays startup detection,
-// but land the browser on the real MagicDNS origin when a trusted Tailscale
-// cert exists. That is the URL remote devices use and the secure context where
-// microphone/browser APIs work; opening the mirror hid this final setup step.
-// The shared walkthrough also proves that Tailscale is currently connected and
-// the cert matches its current MagicDNS name; a stale cert alone must not send
-// the managed browser to an unreachable host.
-const setupGuide = await getCliSetupGuide({ assumeActive: HTTPS_MODE });
-const TARGET_URL = setupGuide.trustedUrl || LOCAL_BASE;
// First-boot startup can take a while: the server binds, opens the DB pool,
// loads the brain index, attaches Socket.IO, then health responds. 90s is
// roomy for a fresh checkout on slow disks; if PortOS still isn't up, the
// user has bigger problems than the auto-open script.
const API_TIMEOUT_MS = 90_000;
-const BROWSER_TIMEOUT_MS = 15_000;
+// `update.sh`/`update.ps1` do a full `pm2 delete` + `pm2 start` of every
+// ecosystem app, including portos-browser — so Chrome is a COLD launch here,
+// racing the exact moment CPU/disk are busiest (npm install, client build).
+// browser/server.js's own launch-wait is 10s; a single fixed-timeout attempt
+// from here regularly lost that race and left Chrome open with no tab
+// pointed anywhere. Retry navigate on a short interval instead of trying once.
+const NAVIGATE_RETRY_TOTAL_MS = 60_000;
+const NAVIGATE_RETRY_INTERVAL_MS = 2_000;
+const NAVIGATE_ATTEMPT_TIMEOUT_MS = 5_000;
const POLL_INTERVAL_MS = 500;
async function poll(checkFn, label, timeoutMs) {
@@ -56,61 +43,114 @@ async function poll(checkFn, label, timeoutMs) {
return false;
}
-async function ping(url) {
+async function ping(url, fetchImpl = fetch) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1500);
- const ok = await fetch(url, { signal: controller.signal })
+ const ok = await fetchImpl(url, { signal: controller.signal })
.then(r => r.ok)
.catch(() => false);
clearTimeout(timeout);
return ok;
}
-const apiHealthUrl = `${LOCAL_BASE}/api/system/health`;
-const browserHealthUrl = `${LOCAL_BASE}/api/browser/health`;
-const navigateUrl = `${LOCAL_BASE}/api/browser/navigate`;
+/**
+ * POST `navigateUrl` on a fixed interval until it succeeds or the overall
+ * budget expires. A single early failure (Chrome still cold-launching, CDP
+ * not listening yet) must not be treated as final — the caller only gets one
+ * shot at auto-opening the dashboard per restart, so this has to outlast the
+ * slowest realistic Chrome cold-start rather than the fastest.
+ * @param {object} opts
+ * @param {string} opts.navigateUrl - the PortOS `/api/browser/navigate` endpoint
+ * @param {string} opts.targetUrl - the dashboard URL to open
+ * @param {number} opts.totalTimeoutMs - overall retry budget
+ * @param {number} opts.intervalMs - delay between attempts
+ * @param {number} opts.attemptTimeoutMs - abort timeout for a single attempt
+ * @param {typeof fetch} [opts.fetchImpl]
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
+ * @returns {Promise<{ok: boolean, status?: number, body?: string, error?: string}>}
+ */
+export async function navigateWithRetry({
+ navigateUrl,
+ targetUrl,
+ totalTimeoutMs,
+ intervalMs,
+ attemptTimeoutMs,
+ fetchImpl = fetch,
+ sleep = (ms) => new Promise(r => setTimeout(r, ms)),
+}) {
+ const deadline = Date.now() + totalTimeoutMs;
+ let lastFailure = { ok: false, error: 'navigate was never attempted' };
+ while (true) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), attemptTimeoutMs);
+ let networkError = null;
+ const res = await fetchImpl(navigateUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url: targetUrl }),
+ signal: controller.signal,
+ }).catch(err => { networkError = err; return null; });
+ clearTimeout(timer);
-const apiReady = await poll(() => ping(apiHealthUrl), 'PortOS API', API_TIMEOUT_MS);
-if (!apiReady) process.exit(0);
+ if (res) {
+ if (res.ok) return { ok: true, status: res.status };
+ const body = await res.text().catch(() => '');
+ lastFailure = { ok: false, status: res.status, body: body.slice(0, 200) };
+ } else {
+ lastFailure = { ok: false, error: networkError?.message || 'unknown fetch error' };
+ }
-// Browser process may take a few seconds longer than the API to reach Chrome.
-// We don't gate strictly on it — even if the health endpoint says "unhealthy"
-// we still POST navigate, which will trigger a launch via the route handler
-// when CDP isn't yet up. The poll just gives Chrome a head start.
-await poll(async () => {
- // Use the same per-request AbortController guard that ping() uses — without
- // a timeout, a hung TCP connection (accepted but never responds) would let
- // a single fetch await forever and ignore BROWSER_TIMEOUT_MS entirely.
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), 1500);
- const res = await fetch(browserHealthUrl, { signal: controller.signal }).catch(() => null);
- clearTimeout(timer);
- if (!res?.ok) return false;
- const json = await res.json().catch(() => null);
- return json?.connected === true;
-}, 'PortOS browser CDP', BROWSER_TIMEOUT_MS);
+ if (Date.now() + intervalMs >= deadline) return lastFailure;
+ await sleep(intervalMs);
+ }
+}
+
+async function main() {
+ // Share the same cert predicate the server's HTTPS gate uses (file presence
+ // AND PEM parseability). A presence-only check would route us to :5553 even
+ // when corrupt PEMs forced the server back to plain HTTP-on-:5555, so the
+ // poll would time out on a port the server never bound.
+ const HTTPS_MODE = hasTailscaleCert(CERT_DIR);
-// 5s navigate timeout — without this, a hung accept-without-response would
-// stall setup.sh / update.* indefinitely even though this step is fail-soft.
-const navController = new AbortController();
-const navTimer = setTimeout(() => navController.abort(), 5000);
-const res = await fetch(navigateUrl, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ url: TARGET_URL }),
- signal: navController.signal,
-}).catch(err => {
- console.warn(`⚠️ Could not reach navigate endpoint: ${err.message}`);
- return null;
-});
-clearTimeout(navTimer);
+ // When HTTPS is on, :5555 speaks TLS only — plain http:// requests hit a TLS
+ // mismatch and time out. The loopback HTTP mirror on :5553 serves the same
+ // app and skips the cert warning, so startup polling always stays local even
+ // when the final browser destination is the trusted MagicDNS origin.
+ const LOCAL_BASE = HTTPS_MODE
+ ? `http://localhost:${HTTP_LOOPBACK_PORT}`
+ : `http://localhost:${API_PORT}`;
+ // Poll through loopback so certificate trust never delays startup detection,
+ // but land the browser on the real MagicDNS origin when a trusted Tailscale
+ // cert exists. That is the URL remote devices use and the secure context where
+ // microphone/browser APIs work; opening the mirror hid this final setup step.
+ // The shared walkthrough also proves that Tailscale is currently connected and
+ // the cert matches its current MagicDNS name; a stale cert alone must not send
+ // the managed browser to an unreachable host.
+ const setupGuide = await getCliSetupGuide({ assumeActive: HTTPS_MODE });
+ const TARGET_URL = setupGuide.trustedUrl || LOCAL_BASE;
+
+ const apiHealthUrl = `${LOCAL_BASE}/api/system/health`;
+ const navigateUrl = `${LOCAL_BASE}/api/browser/navigate`;
+
+ const apiReady = await poll(() => ping(apiHealthUrl), 'PortOS API', API_TIMEOUT_MS);
+ if (!apiReady) process.exit(0);
+
+ const result = await navigateWithRetry({
+ navigateUrl,
+ targetUrl: TARGET_URL,
+ totalTimeoutMs: NAVIGATE_RETRY_TOTAL_MS,
+ intervalMs: NAVIGATE_RETRY_INTERVAL_MS,
+ attemptTimeoutMs: NAVIGATE_ATTEMPT_TIMEOUT_MS,
+ });
+
+ if (!result.ok) {
+ const detail = result.error || `HTTP ${result.status}: ${result.body}`;
+ console.warn(`⚠️ Could not auto-open the dashboard within ${NAVIGATE_RETRY_TOTAL_MS / 1000}s (${detail}) — open it manually: ${TARGET_URL}`);
+ process.exit(0);
+ }
-if (!res) process.exit(0);
-if (!res.ok) {
- const text = await res.text().catch(() => '');
- console.warn(`⚠️ Navigate failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
+ console.log(`🌐 Opened ${TARGET_URL} in PortOS browser`);
process.exit(0);
}
-console.log(`🌐 Opened ${TARGET_URL} in PortOS browser`);
-process.exit(0);
+if (isDirectlyInvoked(import.meta.url)) await main();
diff --git a/scripts/open-ui-in-browser.test.js b/scripts/open-ui-in-browser.test.js
new file mode 100644
index 0000000000..8c453cc208
--- /dev/null
+++ b/scripts/open-ui-in-browser.test.js
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from 'vitest';
+import { navigateWithRetry } from './open-ui-in-browser.js';
+
+const baseOpts = {
+ navigateUrl: 'http://localhost:5553/api/browser/navigate',
+ targetUrl: 'https://host.example-tailnet.ts.net:5555',
+ totalTimeoutMs: 10_000,
+ intervalMs: 1_000,
+ attemptTimeoutMs: 1_000,
+ sleep: vi.fn().mockResolvedValue(undefined),
+};
+
+describe('navigateWithRetry', () => {
+ it('resolves immediately when the first attempt succeeds', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, status: 200 });
+ const result = await navigateWithRetry({ ...baseOpts, fetchImpl });
+ expect(result).toEqual({ ok: true, status: 200 });
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(baseOpts.sleep).not.toHaveBeenCalled();
+ });
+
+ it('retries past a cold-launching browser (Chrome not up yet) and eventually succeeds', async () => {
+ // Simulates the update.sh race: Chrome is still cold-launching so the first
+ // couple of navigate attempts fail (connection refused), then CDP comes up.
+ const sleep = vi.fn().mockResolvedValue(undefined);
+ const fetchImpl = vi.fn()
+ .mockRejectedValueOnce(new Error('connect ECONNREFUSED'))
+ .mockRejectedValueOnce(new Error('connect ECONNREFUSED'))
+ .mockResolvedValueOnce({ ok: true, status: 200 });
+
+ const result = await navigateWithRetry({ ...baseOpts, sleep, fetchImpl });
+
+ expect(result).toEqual({ ok: true, status: 200 });
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
+ expect(sleep).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenCalledWith(1_000);
+ });
+
+ it('gives up once the total retry budget is exhausted, returning the last failure', async () => {
+ let now = 0;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const sleep = vi.fn().mockImplementation(async (ms) => { now += ms; });
+ const fetchImpl = vi.fn().mockRejectedValue(new Error('connect ECONNREFUSED'));
+
+ const result = await navigateWithRetry({
+ ...baseOpts,
+ totalTimeoutMs: 3_000,
+ intervalMs: 1_000,
+ sleep,
+ fetchImpl,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.error).toBe('connect ECONNREFUSED');
+ // Budget of 3000ms at 1000ms/attempt: attempts stop once the next sleep
+ // would cross the deadline, so it must not spin forever.
+ expect(fetchImpl.mock.calls.length).toBeGreaterThan(0);
+ expect(fetchImpl.mock.calls.length).toBeLessThan(10);
+
+ vi.restoreAllMocks();
+ });
+
+ it('treats a non-ok HTTP response (e.g. UNSAFE_URL 400) as a retryable failure, not a throw', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ text: () => Promise.resolve('{"error":"UNSAFE_URL"}'),
+ });
+ const result = await navigateWithRetry({ ...baseOpts, totalTimeoutMs: 500, intervalMs: 1000, fetchImpl });
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(400);
+ expect(result.body).toContain('UNSAFE_URL');
+ });
+});