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
feat: support custom Chrome binary (Canary) for the PortOS-managed browser
Adam Eivy7e87a3780ba7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85921ef59f..298580acd2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,10 @@ Released: TBDTBD+## Added++- **Use a different Chrome variant for the PortOS-managed browser.** PortOS now reads a `chromePath` (and `macAppBundle` on macOS) from `data/browser-config.json`, so you can point it at Chrome Canary, Chromium, Brave, Edge, or any Chromium-based browser — separating the automation surface from your daily-driver Chrome. Setup (`./setup.sh` / `setup.ps1`) and update (`./update.sh` / `./update.ps1`) now offer to install and configure Chrome Canary automatically: on macOS via `brew install --cask google-chrome@canary`, on Windows via `winget install Google.Chrome.Canary`. The prompt is interactive-only (CI / non-TTY runs skip silently), idempotent (won't re-prompt once configured), and supports `PORTOS_USE_CANARY=1` for headless opt-in. The Browser page's Config panel exposes both fields for after-the-fact edits.+## Changed- **Universes table** — each row now shows a 48×48 thumbnail of the latest image from the universe's auto-managed media collection (the `Universe: <name>` bucket linked by `collection.universeId`). Rows without media fall back to a Globe placeholder; a broken file ref also degrades to the placeholder via `<img onError>`. Applies to both the desktop table and the mobile card layout.diff --git a/PLAN.md b/PLAN.mdindex a690a52043..f1504b88ab 100644--- a/PLAN.md+++ b/PLAN.md@@ -11,6 +11,7 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [peer-sync-per-category-version-gate] **Generalize the cross-install schema version gate from whole-payload to per-category.** Surfaced by code review during the batch-clear of `[peer-sync-video-collection-metadata-sync]` (2026-05-25). `compareSchemaVersions` (`server/lib/schemaVersions.js`) walks the UNION of category keys, and the three gate sites (`dataSync.js` `applyRemote`, `peerSync.js` push, `importer.js` import) reject the ENTIRE payload on any `ahead.length > 0`. So introducing a brand-new category key — or bumping one category — makes every not-yet-upgraded peer reject ALL categories (universe, pipeline, …), severing sync across a federation that upgrades on independent schedules. `videoHistory` sidestepped this by deliberately staying OUT of `PORTOS_SCHEMA_VERSIONS` (see the comment there), but `mediaCollections: 1` has the same latent property. Fix: scope the ahead-check to the category (for `applyRemote`/import) or the record's kind→category (for push) actually being transferred, so a newer sender's unknown/bumped category gates only THAT category's transfer, not unrelated ones. Keep the union-walk for diagnostics/UI. Needs new cross-key test coverage (today's tests only exercise same-category gaps).- [ ] [voice-weather-settings-location] **Wire a real `settings.location { lat, lon }` field so `weather_now` can use a configured location.** Surfaced during the batch-clear review of `[voice-cos-tool-expansion]` (2026-05-25). The `weather_now` voice tool already reads `settings?.location?.{lat,lon}` (forward-compatible, guarded) but no Settings UI or Zod slice ever sets it, so with no `lat`/`lon` args it always falls back to the default location. Add a `location` settings field (Settings UI + a Zod slice in `server/lib/validation.js`), then the existing tool path lights up. Small.- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.+- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).- [ ] [voice-tool-edge-hardening] **Edge-case hardening for the new voice tools (all low-severity, from the xhigh code-review 2026-05-25).** (c) `timer_set` is a bare in-memory `setTimeout` with no persistence (lost silently on restart) and no dedup across tool-loop iterations (LLM re-issue → double notification). Also minor: `dataSync.js` per-`(category,forPeerId)` `checksumCache` keys are never evicted (unbounded for cycling peer ids; negligible for a home federation). _(Fixed in the v2.9.0 release review: (a) the `calendar_today` DST-offset bug — `anchorLocalMidnightUtc` now samples the offset at the target midnight; (b) `calendar_next` now matches calendarSync's `endTime >= now` range so in-progress and all-day-today events surface; and `resolveExcludeSet` is now deferred to the `getChecksum` cache-miss path.)_## Deferred Architecture (human-led planning)diff --git a/browser/server.js b/browser/server.jsindex 2643f18421..c727990ae2 100644--- a/browser/server.js+++ b/browser/server.js@@ -26,14 +26,28 @@ let downloadWsReconnectTimer = null;let downloadDirCurrent = null;let shuttingDown = false;-function getChromePath() {+const DEFAULT_MAC_CHROME_APP = '/Applications/Google Chrome.app';++function defaultChromeBinary() {const os = platform();if (os === 'darwin') return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';if (os === 'win32') return 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';return 'google-chrome';}-const MAC_CHROME_APP = '/Applications/Google Chrome.app';+function getChromePath(config) {+ if (typeof config?.chromePath === 'string' && config.chromePath.trim()) {+ return config.chromePath;+ }+ return defaultChromeBinary();+}++function getMacAppBundle(config) {+ if (typeof config?.macAppBundle === 'string' && config.macAppBundle.trim()) {+ return config.macAppBundle;+ }+ return DEFAULT_MAC_CHROME_APP;+}async function loadConfig() {const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);@@ -155,7 +169,8 @@ async function launchBrowser() {headlessMode = config.headless === true;const profileDir = config.userDataDir || DEFAULT_PROFILE_DIR;- const chromePath = getChromePath();+ const chromePath = getChromePath(config);+ const macAppBundle = getMacAppBundle(config);await mkdir(profileDir, { recursive: true });await mkdir(downloadDir, { recursive: true });@@ -176,7 +191,7 @@ async function launchBrowser() {args.push('--headless=new');}- console.log(`🌐 Launching Chrome (headless=${headlessMode}, profile=${profileDir}) CDP on ${CDP_HOST}:${CDP_PORT}`);+ console.log(`🌐 Launching Chrome (headless=${headlessMode}, profile=${profileDir}, binary=${platform() === 'darwin' && !headlessMode ? macAppBundle : chromePath}) CDP on ${CDP_HOST}:${CDP_PORT}`);// macOS headed mode: launch via LaunchServices (`open -na`) so Chrome owns// its own TCC identity. As a direct subprocess of node/PM2, Chrome inherits@@ -190,7 +205,7 @@ async function launchBrowser() {// Headless mode skips this (no UI to click) and non-darwin platforms don't// have the TCC-responsibility problem at all.if (platform() === 'darwin' && !headlessMode) {- chromeProcess = spawn('/usr/bin/open', ['-na', MAC_CHROME_APP, '--args', ...args], { stdio: 'ignore' });+ chromeProcess = spawn('/usr/bin/open', ['-na', macAppBundle, '--args', ...args], { stdio: 'ignore' });chromeProcess.on('exit', () => {// `open` returns ~immediately once Chrome is handed off to launchd; that// exit is not Chrome's death. Chrome-exit detection happens via thediff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsxindex 36ead4d0a4..ad14ef3656 100644--- a/client/src/pages/Browser.jsx+++ b/client/src/pages/Browser.jsx@@ -233,6 +233,37 @@ export default function BrowserPage() {/><label htmlFor="autoConnect" className="text-sm text-gray-400">Auto-connect on startup</label></div>+ <div className="sm:col-span-2 lg:col-span-3">+ <label htmlFor="chromePath" className="block text-sm text-gray-400 mb-1">+ Chrome binary path+ <span className="ml-2 text-xs text-gray-600">(leave empty to use system default)</span>+ </label>+ <input+ id="chromePath"+ type="text"+ value={configDraft.chromePath || ''}+ onChange={e => setConfigDraft(d => ({ ...d, chromePath: e.target.value }))}+ placeholder="/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono focus:outline-hidden focus:border-port-accent placeholder-gray-600"+ />+ <p className="text-xs text-gray-500 mt-1">+ Point at Chrome Canary, Chromium, Brave, or any Chromium-based browser to differentiate the PortOS-managed browser from your daily-driver Chrome.+ </p>+ </div>+ <div className="sm:col-span-2 lg:col-span-3">+ <label htmlFor="macAppBundle" className="block text-sm text-gray-400 mb-1">+ macOS app bundle+ <span className="ml-2 text-xs text-gray-600">(headed mode only; leave empty for system default)</span>+ </label>+ <input+ id="macAppBundle"+ type="text"+ value={configDraft.macAppBundle || ''}+ onChange={e => setConfigDraft(d => ({ ...d, macAppBundle: e.target.value }))}+ placeholder="/Applications/Google Chrome Canary.app"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono focus:outline-hidden focus:border-port-accent placeholder-gray-600"+ />+ </div></div><div className="mt-4 flex justify-end"><buttondiff --git a/scripts/setup-browser.js b/scripts/setup-browser.jsindex 35d324672f..496c250939 100644--- a/scripts/setup-browser.js+++ b/scripts/setup-browser.js@@ -1,18 +1,165 @@#!/usr/bin/env node-import { existsSync, mkdirSync } from 'fs';++/**+ * Browser Setup Script+ *+ * Ensures the browser profile dir exists, and (interactively, first run only)+ * offers to use Chrome Canary as the PortOS-managed browser. Differentiating+ * PortOS's CDP browser from the user's daily-driver Chrome avoids profile+ * collisions and TCC ambiguity, and the Canary update cadence keeps the+ * automation surface fresh.+ *+ * Idempotent: if `data/browser-config.json` already has `chromePath` set, this+ * exits without re-prompting. Non-interactive (CI / pm2-managed update.sh)+ * runs skip silently. `PORTOS_USE_CANARY=1` opts in without prompting; `=0`+ * opts out without prompting.+ *+ * Called by: npm run setup, setup.sh/ps1, update.sh/ps1.+ */++import { execFileSync, spawnSync } from 'child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';+import { createInterface } from 'readline';import { dirname, join } from 'path';import { fileURLToPath } from 'url';+import { homedir, platform } from 'os';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');-const profileDir = join(rootDir, 'data', 'browser-profile');+const dataDir = join(rootDir, 'data');+const profileDir = join(dataDir, 'browser-profile');+const configFile = join(dataDir, 'browser-config.json');console.log('🌐 Ensuring browser profile directory exists...');--// Ensure browser profile directory existsif (!existsSync(profileDir)) {mkdirSync(profileDir, { recursive: true });console.log('📁 Created browser profile directory');}+function loadConfig() {+ if (!existsSync(configFile)) return {};+ try { return JSON.parse(readFileSync(configFile, 'utf-8')); } catch { return {}; }+}++function saveConfig(config) {+ if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });+ writeFileSync(configFile, JSON.stringify(config, null, 2));+}++function hasCommand(cmd, args) {+ try { execFileSync(cmd, args, { stdio: 'pipe' }); return true; } catch { return false; }+}++// macOS Canary lives at the conventional `.app` bundle. Windows Canary installs+// to LOCALAPPDATA (per-user). Linux has no Canary build — we no-op there.+function detectCanary() {+ const os = platform();+ if (os === 'darwin') {+ const app = '/Applications/Google Chrome Canary.app';+ const bin = `${app}/Contents/MacOS/Google Chrome Canary`;+ return existsSync(bin) ? { app, bin } : null;+ }+ if (os === 'win32') {+ const localAppData = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');+ const bin = join(localAppData, 'Google', 'Chrome SxS', 'Application', 'chrome.exe');+ return existsSync(bin) ? { bin } : null;+ }+ return null;+}++function canaryInstallCommand() {+ const os = platform();+ if (os === 'darwin' && hasCommand('brew', ['--version'])) {+ return { cmd: 'brew', args: ['install', '--cask', 'google-chrome@canary'], label: 'Homebrew' };+ }+ if (os === 'win32' && hasCommand('winget', ['--version'])) {+ return { cmd: 'winget', args: ['install', '--id', 'Google.Chrome.Canary', '-e', '--source', 'winget'], label: 'winget' };+ }+ return null;+}++function applyCanaryToConfig(found) {+ const config = loadConfig();+ config.chromePath = found.bin;+ if (found.app) config.macAppBundle = found.app;+ saveConfig(config);+ console.log(`✅ PortOS browser set to Chrome Canary → ${found.bin}`);+}++function promptYesNo(question, defaultYes = true) {+ return new Promise((resolve) => {+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ const suffix = defaultYes ? '[Y/n]' : '[y/N]';+ rl.question(` ${question} ${suffix}: `, (answer) => {+ rl.close();+ const t = (answer || '').trim();+ if (!t) return resolve(defaultYes);+ resolve(/^y(es)?$/i.test(t));+ });+ });+}++async function runCanarySetup() {+ const os = platform();+ if (os !== 'darwin' && os !== 'win32') {+ // Linux: no Canary build. Skip silently — the field is still+ // editable from Settings → Browser if the user wants Chromium/Brave.+ return;+ }++ const config = loadConfig();+ if (typeof config.chromePath === 'string' && config.chromePath.trim()) {+ // Already configured — don't re-prompt on subsequent setup/update runs.+ return;+ }++ const envOptOut = process.env.PORTOS_USE_CANARY === '0' || process.env.PORTOS_USE_CANARY === 'false';+ const envOptIn = process.env.PORTOS_USE_CANARY === '1' || process.env.PORTOS_USE_CANARY === 'true';+ const interactive = process.stdin.isTTY && process.stdout.isTTY;++ if (envOptOut) return;+ if (!interactive && !envOptIn) {+ // Non-TTY (CI, update.sh under pm2) and no explicit opt-in: print a+ // one-liner hint and bail. The user can re-run setup interactively or+ // toggle from Settings → Browser.+ console.log('💡 Tip: PortOS can use Chrome Canary as its managed browser (run setup interactively or set PORTOS_USE_CANARY=1).');+ return;+ }++ const found = detectCanary();++ if (found) {+ const ok = envOptIn ? true : await promptYesNo('Chrome Canary detected. Use it as the PortOS-managed browser?', true);+ if (ok) applyCanaryToConfig(found);+ else console.log(' Keeping the platform-default Chrome. You can switch later in Settings → Browser.');+ return;+ }++ const install = canaryInstallCommand();+ if (!install) {+ const downloadUrl = 'https://www.google.com/chrome/canary/';+ console.log(`💡 Chrome Canary not detected, and no package manager available to install it. Download manually: ${downloadUrl}`);+ return;+ }++ const ok = envOptIn ? true : await promptYesNo(`Install Chrome Canary via ${install.label} and use it as the PortOS-managed browser?`, true);+ if (!ok) {+ console.log(' Keeping the platform-default Chrome. You can switch later in Settings → Browser.');+ return;+ }++ console.log(`🍺 Installing Chrome Canary via ${install.label}...`);+ const result = spawnSync(install.cmd, install.args, { stdio: 'inherit' });+ if (result.status !== 0) {+ console.log(`⚠️ ${install.label} install of Chrome Canary failed (exit ${result.status}). You can install it manually and re-run setup.`);+ return;+ }++ const reFound = detectCanary();+ if (reFound) applyCanaryToConfig(reFound);+ else console.log('⚠️ Canary installed but the binary was not found at the expected path. You can set chromePath manually in Settings → Browser.');+}++await runCanarySetup();+console.log('✅ Browser setup complete');diff --git a/server/routes/browser.js b/server/routes/browser.jsindex e8a24166fb..f21059e465 100644--- a/server/routes/browser.js+++ b/server/routes/browser.js@@ -10,6 +10,16 @@ const navigateSchema = z.object({url: z.string().url()});+// Empty string from a "clear" UI action → unset (undefined), so the launcher+// falls back to the platform default Chrome instead of trying to spawn "".+const optionalPath = z.preprocess(+ v => (v === '' ? undefined : v),+ z.string().max(1024).refine(+ v => !v || !v.includes('..'),+ { message: 'path must not contain path traversal' }+ ).optional()+);+const updateConfigSchema = z.object({cdpPort: z.number().int().min(1024).max(65535).optional(),cdpHost: z.enum(['127.0.0.1', 'localhost', '::1']).optional(),@@ -20,7 +30,15 @@ const updateConfigSchema = z.object({downloadDir: z.string().refine(v => !v || !v.includes('..'),{ message: 'downloadDir must not contain path traversal' }- ).optional()+ ).optional(),+ // Custom Chrome binary (e.g. Chrome Canary). When unset, the launcher falls+ // back to the platform default (`/Applications/Google Chrome.app/...` on+ // macOS, `C:\Program Files\Google\Chrome\...` on Windows, `google-chrome`+ // on Linux).+ chromePath: optionalPath,+ // macOS headed mode launches via `open -na <app-bundle>` for TCC reasons,+ // so the bundle (`.app`) path is tracked separately from the executable.+ macAppBundle: optionalPath});// GET /api/browser - Full browser status