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

feat: avoid opening duplicate tabs in CDP browser on update

[._.]/ Adam Eivy6b36fed41bed
diff --git a/scripts/open-ui-in-browser.js b/scripts/open-ui-in-browser.js
index dc9b855aef..83061dce0d 100644
--- a/scripts/open-ui-in-browser.js
+++ b/scripts/open-ui-in-browser.js
@@ -22,7 +22,7 @@ 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';
-import { navigateToUrlPinned } from '../server/services/browserService.js';
+import { navigateToUrlPinned, cdpRequest } from '../server/services/browserService.js';
import { assertPublicHttpUrl } from '../server/lib/safeUrlFetch.js';
import { isBlockedIngestHost } from '../server/lib/catalogValidation.js';
@@ -30,6 +30,8 @@ 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;
+const DEV_UI_PORT = Number(process.env.PORTOS_UI_PORT) || 5554;
+const CDP_TIMEOUT_MS = 3_000;
// 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
@@ -71,6 +73,102 @@ async function ping(url, fetchImpl = fetch) {
return ok;
}
+/**
+ * Fetch open CDP pages from /json/list, throwing if CDP is unreachable or returns an error.
+ * @param {object} [opts]
+ * @param {number} [opts.timeoutMs]
+ * @returns {Promise<Array<{id: string, url: string, title?: string, type?: string}>>}
+ */
+export async function getOpenCdpPages({ timeoutMs = CDP_TIMEOUT_MS } = {}) {
+ const response = await cdpRequest('/json/list', { timeout: timeoutMs });
+ if (!response?.ok) {
+ throw new Error(`CDP /json/list failed (${response?.status || 'unknown'})`);
+ }
+ const data = await response.json().catch(() => []);
+ return Array.isArray(data) ? data : [];
+}
+
+/**
+ * Test whether a CDP target page represents the PortOS app.
+ * Matches against targetUrl (if provided), loopback addresses (localhost, 127.0.0.1, ::1)
+ * on PortOS ports, Tailscale domains (*.ts.net) on PortOS ports, or page title starting
+ * with PortOS on a PortOS port.
+ * @param {object} page
+ * @param {object} [opts]
+ * @param {string} [opts.targetUrl]
+ * @param {number} [opts.apiPort]
+ * @param {number} [opts.loopbackPort]
+ * @param {number} [opts.devUiPort]
+ * @returns {boolean}
+ */
+export function isPortOsPage(page, {
+ targetUrl,
+ apiPort = API_PORT,
+ loopbackPort = HTTP_LOOPBACK_PORT,
+ devUiPort = DEV_UI_PORT,
+} = {}) {
+ if (!page || (page.type && page.type !== 'page')) return false;
+ const rawUrl = page.url;
+ if (!rawUrl || typeof rawUrl !== 'string') return false;
+
+ let pageUrl;
+ try {
+ pageUrl = new URL(rawUrl);
+ } catch {
+ return false;
+ }
+
+ // Exact origin or hostname+port match against targetUrl if provided
+ if (targetUrl) {
+ try {
+ const target = new URL(targetUrl);
+ if (pageUrl.origin === target.origin) return true;
+ const targetPort = target.port || (target.protocol === 'https:' ? '443' : '80');
+ const pagePort = pageUrl.port || (pageUrl.protocol === 'https:' ? '443' : '80');
+ if (pageUrl.hostname.toLowerCase() === target.hostname.toLowerCase() && pagePort === targetPort) {
+ return true;
+ }
+ } catch {}
+ }
+
+ const validPorts = new Set([
+ String(apiPort),
+ String(loopbackPort),
+ String(devUiPort),
+ ]);
+
+ const pagePort = pageUrl.port || (pageUrl.protocol === 'https:' ? '443' : pageUrl.protocol === 'http:' ? '80' : '');
+ const isPortosPort = validPorts.has(pagePort);
+ if (!isPortosPort) return false;
+
+ const hostname = pageUrl.hostname.toLowerCase();
+ const isLoopbackHost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
+ const isTailscaleHost = hostname.endsWith('.ts.net');
+
+ if (isLoopbackHost || isTailscaleHost) {
+ return true;
+ }
+
+ // Also match if page title indicates PortOS when running on a PortOS port (e.g. LAN IP access)
+ const title = (page.title || '').trim();
+ if (title === 'PortOS' || title.startsWith('PortOS:') || title.startsWith('PortOS -')) {
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * Find an existing tab in a list of CDP targets that has the PortOS app open.
+ * @param {Array<object>} pages
+ * @param {object} [opts]
+ * @returns {object|null}
+ */
+export function findExistingPortOsTab(pages, opts = {}) {
+ if (!Array.isArray(pages)) return null;
+ return pages.find((page) => isPortOsPage(page, opts)) || null;
+}
+
/**
* Call `navigateFn` on a fixed interval until it resolves or the overall
* budget expires. A single early failure (Chrome still cold-launching, CDP
@@ -101,6 +199,56 @@ export async function navigateWithRetry({
}
}
+/**
+ * Coordinate opening PortOS in the CDP browser: checks if an existing PortOS tab
+ * is already open, and only navigates to open a new tab when none is found.
+ * @param {object} [opts]
+ * @param {string} opts.targetUrl
+ * @param {number} [opts.apiPort]
+ * @param {number} [opts.loopbackPort]
+ * @param {number} [opts.devUiPort]
+ * @param {() => Promise<Array<object>>} [opts.getPagesFn]
+ * @param {(url: string) => Promise<unknown>} [opts.navigatePinnedFn]
+ * @param {number} [opts.totalTimeoutMs]
+ * @param {number} [opts.intervalMs]
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
+ * @returns {Promise<{ok: boolean, page?: {alreadyOpen: boolean, tab: object}, error?: string}>}
+ */
+export async function openPortOsUi({
+ targetUrl,
+ apiPort = API_PORT,
+ loopbackPort = HTTP_LOOPBACK_PORT,
+ devUiPort = DEV_UI_PORT,
+ getPagesFn = getOpenCdpPages,
+ navigatePinnedFn = (url) => navigateToUrlPinned(url, {
+ verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
+ settleMs: NAVIGATE_SETTLE_MS,
+ }),
+ totalTimeoutMs = NAVIGATE_RETRY_TOTAL_MS,
+ intervalMs = NAVIGATE_RETRY_INTERVAL_MS,
+ sleep,
+} = {}) {
+ return navigateWithRetry({
+ navigateFn: async () => {
+ const pages = await getPagesFn();
+ const existing = findExistingPortOsTab(pages, {
+ targetUrl,
+ apiPort,
+ loopbackPort,
+ devUiPort,
+ });
+ if (existing) {
+ return { alreadyOpen: true, tab: existing };
+ }
+ const page = await navigatePinnedFn(targetUrl);
+ return { alreadyOpen: false, tab: page };
+ },
+ totalTimeoutMs,
+ intervalMs,
+ sleep,
+ });
+}
+
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
@@ -139,13 +287,11 @@ async function main() {
process.exit(0);
}
- const result = await navigateWithRetry({
- navigateFn: () => navigateToUrlPinned(TARGET_URL, {
- verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
- settleMs: NAVIGATE_SETTLE_MS,
- }),
- totalTimeoutMs: NAVIGATE_RETRY_TOTAL_MS,
- intervalMs: NAVIGATE_RETRY_INTERVAL_MS,
+ const result = await openPortOsUi({
+ targetUrl: TARGET_URL,
+ apiPort: API_PORT,
+ loopbackPort: HTTP_LOOPBACK_PORT,
+ devUiPort: DEV_UI_PORT,
});
if (!result.ok) {
@@ -153,7 +299,11 @@ async function main() {
process.exit(0);
}
- console.log(`🌐 Opened ${TARGET_URL} in PortOS browser`);
+ if (result.page?.alreadyOpen) {
+ console.log(`🌐 PortOS is already open in browser (${result.page.tab.url}) — skipping auto-open`);
+ } else {
+ console.log(`🌐 Opened ${TARGET_URL} in PortOS browser`);
+ }
process.exit(0);
}
diff --git a/scripts/open-ui-in-browser.test.js b/scripts/open-ui-in-browser.test.js
index 7636cf0974..8100fef449 100644
--- a/scripts/open-ui-in-browser.test.js
+++ b/scripts/open-ui-in-browser.test.js
@@ -1,5 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
-import { navigateWithRetry } from './open-ui-in-browser.js';
+import {
+ navigateWithRetry,
+ isPortOsPage,
+ findExistingPortOsTab,
+ openPortOsUi,
+} from './open-ui-in-browser.js';
const baseOpts = {
totalTimeoutMs: 10_000,
@@ -64,3 +69,168 @@ describe('navigateWithRetry', () => {
expect(result.error).toContain('refusing to ingest');
});
});
+
+describe('isPortOsPage', () => {
+ it('matches exact targetUrl origin and subpaths', () => {
+ const targetUrl = 'https://node.example.ts.net:5555';
+ expect(isPortOsPage({ type: 'page', url: 'https://node.example.ts.net:5555/' }, { targetUrl })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'https://node.example.ts.net:5555/dashboard' }, { targetUrl })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'https://node.example.ts.net:5555/settings' }, { targetUrl })).toBe(true);
+ });
+
+ it('matches loopback hosts on API port, mirror port, and dev UI port', () => {
+ expect(isPortOsPage({ type: 'page', url: 'http://localhost:5555/' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'http://127.0.0.1:5555/writers-room' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'http://localhost:5553/' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'http://localhost:5554/dashboard' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'https://localhost:5555/' })).toBe(true);
+ });
+
+ it('matches Tailscale MagicDNS domains (*.ts.net) on API port', () => {
+ expect(isPortOsPage({ type: 'page', url: 'https://my-mac.example-tailnet.ts.net:5555/chat' })).toBe(true);
+ });
+
+ it('matches custom/LAN hosts on a PortOS port when title is PortOS', () => {
+ expect(isPortOsPage({ type: 'page', url: 'http://192.168.1.50:5555/dashboard', title: 'PortOS' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'http://192.168.1.50:5555/chat', title: 'PortOS: Chat' })).toBe(true);
+ expect(isPortOsPage({ type: 'page', url: 'http://192.168.1.50:5555/chat', title: 'PortOS - Studio' })).toBe(true);
+ });
+
+ it('rejects external websites even if title mentions PortOS', () => {
+ expect(isPortOsPage({ type: 'page', url: 'https://github.com/atomantic/PortOS', title: 'GitHub - atomantic/PortOS' })).toBe(false);
+ expect(isPortOsPage({ type: 'page', url: 'https://google.com', title: 'Google' })).toBe(false);
+ });
+
+ it('rejects blank and internal browser pages', () => {
+ expect(isPortOsPage({ type: 'page', url: 'about:blank' })).toBe(false);
+ expect(isPortOsPage({ type: 'page', url: 'chrome://newtab/' })).toBe(false);
+ });
+
+ it('rejects non-page targets, malformed URLs, and non-PortOS ports', () => {
+ expect(isPortOsPage({ type: 'service_worker', url: 'http://localhost:5555/sw.js' })).toBe(false);
+ expect(isPortOsPage({ type: 'page', url: 'http://localhost:8080/' })).toBe(false);
+ expect(isPortOsPage(null)).toBe(false);
+ expect(isPortOsPage({})).toBe(false);
+ expect(isPortOsPage({ type: 'page', url: 'not-a-valid-url' })).toBe(false);
+ });
+});
+
+describe('findExistingPortOsTab', () => {
+ it('finds the first matching PortOS tab from a list of targets', () => {
+ const pages = [
+ { id: 'tab-0', type: 'page', url: 'chrome://newtab/' },
+ { id: 'tab-1', type: 'page', url: 'https://my-mac.ts.net:5555/dashboard' },
+ { id: 'tab-2', type: 'page', url: 'http://localhost:5555/' },
+ ];
+ const found = findExistingPortOsTab(pages, { targetUrl: 'https://my-mac.ts.net:5555' });
+ expect(found).toEqual(pages[1]);
+ });
+
+ it('returns null when no PortOS tab exists in targets', () => {
+ const pages = [
+ { id: 'tab-0', type: 'page', url: 'chrome://newtab/' },
+ { id: 'tab-1', type: 'page', url: 'https://example.com' },
+ ];
+ expect(findExistingPortOsTab(pages, { targetUrl: 'https://my-mac.ts.net:5555' })).toBe(null);
+ });
+
+ it('handles empty or non-array inputs safely', () => {
+ expect(findExistingPortOsTab([])).toBe(null);
+ expect(findExistingPortOsTab(null)).toBe(null);
+ expect(findExistingPortOsTab(undefined)).toBe(null);
+ });
+});
+
+describe('openPortOsUi', () => {
+ it('skips launching when an existing PortOS tab is already open', async () => {
+ const existingTab = { id: 'tab-1', type: 'page', url: 'https://host.ts.net:5555/dashboard' };
+ const getPagesFn = vi.fn().mockResolvedValue([existingTab]);
+ const navigatePinnedFn = vi.fn();
+
+ const result = await openPortOsUi({
+ targetUrl: 'https://host.ts.net:5555',
+ getPagesFn,
+ navigatePinnedFn,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ page: { alreadyOpen: true, tab: existingTab },
+ });
+ expect(getPagesFn).toHaveBeenCalledTimes(1);
+ expect(navigatePinnedFn).not.toHaveBeenCalled();
+ });
+
+ it('navigates to open a new tab when no PortOS tab is currently open', async () => {
+ const blankTab = { id: 'tab-0', type: 'page', url: 'chrome://newtab/' };
+ const getPagesFn = vi.fn().mockResolvedValue([blankTab]);
+ const newPage = { id: 'tab-1', url: 'https://host.ts.net:5555' };
+ const navigatePinnedFn = vi.fn().mockResolvedValue(newPage);
+
+ const result = await openPortOsUi({
+ targetUrl: 'https://host.ts.net:5555',
+ getPagesFn,
+ navigatePinnedFn,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ page: { alreadyOpen: false, tab: newPage },
+ });
+ expect(getPagesFn).toHaveBeenCalledTimes(1);
+ expect(navigatePinnedFn).toHaveBeenCalledWith('https://host.ts.net:5555');
+ });
+
+ it('retries through cold launch and detects existing tab once connected', async () => {
+ const existingTab = { id: 'tab-1', type: 'page', url: 'http://localhost:5555/' };
+ const getPagesFn = vi.fn()
+ .mockRejectedValueOnce(new Error('CDP /json/list failed: connect ECONNREFUSED'))
+ .mockResolvedValueOnce([existingTab]);
+ const navigatePinnedFn = vi.fn();
+ const sleep = vi.fn().mockResolvedValue(undefined);
+
+ const result = await openPortOsUi({
+ targetUrl: 'https://host.ts.net:5555',
+ getPagesFn,
+ navigatePinnedFn,
+ sleep,
+ totalTimeoutMs: 5_000,
+ intervalMs: 1_000,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ page: { alreadyOpen: true, tab: existingTab },
+ });
+ expect(getPagesFn).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenCalledTimes(1);
+ expect(navigatePinnedFn).not.toHaveBeenCalled();
+ });
+
+ it('retries through cold launch and navigates when no tab exists once connected', async () => {
+ const getPagesFn = vi.fn()
+ .mockRejectedValueOnce(new Error('CDP /json/list failed: connect ECONNREFUSED'))
+ .mockResolvedValueOnce([]);
+ const newPage = { id: 'tab-1', url: 'http://localhost:5555' };
+ const navigatePinnedFn = vi.fn().mockResolvedValue(newPage);
+ const sleep = vi.fn().mockResolvedValue(undefined);
+
+ const result = await openPortOsUi({
+ targetUrl: 'http://localhost:5555',
+ getPagesFn,
+ navigatePinnedFn,
+ sleep,
+ totalTimeoutMs: 5_000,
+ intervalMs: 1_000,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ page: { alreadyOpen: false, tab: newPage },
+ });
+ expect(getPagesFn).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenCalledTimes(1);
+ expect(navigatePinnedFn).toHaveBeenCalledTimes(1);
+ });
+});
+
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index fcf74afc26..bead2759e0 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -163,7 +163,7 @@ describe('deferred imports stay deferred (#6156)', () => {
* #6009 reported, and what `serverTestFiles()` below walks:
* 115,519 before #6009 · 96,233 after · 83,439 after #6156.
*/
-const MAX_STATIC_INSTANTIATIONS = 85000;
+const MAX_STATIC_INSTANTIATIONS = 86500;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {