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

Harden Chrome Canary browser config

[._.]/ Adam Eivy8a4620033e1b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dfe0bcbe1a..e7f4ed9933 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
## Fixed
+- Custom browser setup is more reliable: macOS app bundles are paired automatically with Chrome-compatible browser paths, Canary setup no longer repeatedly prompts after you decline, and non-interactive updates no longer risk hanging on package-manager password prompts.
- **[catalog-ref-deletion-tombstones] Catalog ingredient unlinks now propagate to federation peers.** Unlinking an ingredient from a universe / series / issue used to hard-DELETE the `catalog_ingredient_refs` row with no `sync_sequence` bump and no tombstone — peers that already pulled the link kept it forever, leaving the "Appears in" panel stale across the federation. The ref table now soft-deletes (new `deleted` / `deleted_at` columns + an UPDATE trigger that bumps `sync_sequence` on delete/revive), `linkIngredientToRef` revives a tombstoned row on re-link, and `upsertRefFromPeer` mirrors remote deletes via `ON CONFLICT DO UPDATE`. `PORTOS_SCHEMA_VERSIONS.catalog` bumps from 1 to 2 so older peers can't push a v1-shaped payload that would silently miss tombstones.
- **[civitai-hidream-qwen-baseModels] Civitai LoRA suggestions now include HiDream and Qwen.** Both runner families existed in `RUNNER_FAMILIES` but were missing from the Civitai `baseModels` search map and the LoRA Manager UI — so every page load logged `Unknown runner family for Civitai search: hidream` / `qwen`, neither family got a "Top for …" section, and any HiDream/Qwen LoRA installed via URL ended up with `runnerFamily=null` (broken compat filter). The two families now map to Civitai's `HiDream` / `Qwen` baseModel strings and render alongside Flux 1, Flux 2, Z-Image, and ERNIE in the suggestions panel.
- **Creative Director long sessions stay fast.** Per-scene render orchestration no longer slows down as a project accumulates more scenes — previously a project could degrade from ~3.5 minutes per scene to 10–30 minutes after a long run, because every render reread and rewrote the full per-project run history as that history grew unbounded. The Runs tab now shows up to 200 of the most recent run entries per project; older completed/failed runs are dropped automatically while every in-flight task is always preserved.
diff --git a/PLAN.md b/PLAN.md
index 79ae11f1b3..f9f3fd4f03 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -37,7 +37,6 @@ The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`)
_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._
- [ ] [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).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **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`).
- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).
- [ ] [mediajobqueue-shared-provider-kind-predicate] **Share a `getJobProviderKind(job)` predicate between `getGenModuleForJob` and `resolveLiveParams` in `server/services/mediaJobQueue/index.js`.** Both now encode the same `video | image+codex | image+local` partition by hand (`getGenModuleForJob` at ~line 109, `resolveLiveParams.usesLocalPython` at ~line 122). A shared `getJobProviderKind(job) → 'video-local' | 'image-local' | 'image-codex' | null` would let both branches derive from one predicate and extend cleanly to future providers. Surfaced by reuse-review during the resolveLiveParams extract (2026-05-29); deferred because today's duplication is two lines and the seam is still small.
- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.
diff --git a/browser/server.js b/browser/server.js
index f5ec0f9650..c53ec718c9 100644
--- a/browser/server.js
+++ b/browser/server.js
@@ -4,6 +4,7 @@ import { readFile, mkdir } from 'fs/promises';
import { resolve, dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { platform, homedir } from 'os';
+import { deriveMacAppBundleFromChromePath } from '../server/lib/browserConfig.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = resolve(__dirname, '..');
@@ -42,10 +43,12 @@ function getChromePath(config) {
return defaultChromeBinary();
}
-function getMacAppBundle(config) {
+function getMacAppBundle(config, chromePath) {
if (typeof config?.macAppBundle === 'string' && config.macAppBundle.trim()) {
return config.macAppBundle;
}
+ const derived = deriveMacAppBundleFromChromePath(chromePath);
+ if (derived) return derived;
return DEFAULT_MAC_CHROME_APP;
}
@@ -168,6 +171,7 @@ function scheduleDownloadReconnect() {
async function launchBrowser() {
const config = await loadConfig();
const downloadDir = config.downloadDir || DEFAULT_DOWNLOAD_DIR;
+ headlessMode = config.headless === true;
// Reuse existing Chrome if CDP is already reachable (e.g. after PM2 restart)
if (await checkCdp()) {
@@ -177,10 +181,9 @@ async function launchBrowser() {
return;
}
- headlessMode = config.headless === true;
const profileDir = config.userDataDir || DEFAULT_PROFILE_DIR;
const chromePath = getChromePath(config);
- const macAppBundle = getMacAppBundle(config);
+ const macAppBundle = getMacAppBundle(config, chromePath);
await mkdir(profileDir, { recursive: true });
await mkdir(downloadDir, { recursive: true });
diff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsx
index ad14ef3656..9607c2c9ec 100644
--- a/client/src/pages/Browser.jsx
+++ b/client/src/pages/Browser.jsx
@@ -17,6 +17,13 @@ import { formatBytes } from '../utils/formatters';
const POLL_INTERVAL = 5000;
+function deriveMacAppBundle(chromePath) {
+ if (!chromePath?.trim()) return null;
+ const normalized = chromePath.trim().replaceAll('\\', '/');
+ const appIndex = normalized.toLowerCase().indexOf('.app/');
+ return appIndex >= 0 ? normalized.slice(0, appIndex + '.app'.length) : null;
+}
+
function formatUptime(timestamp) {
if (!timestamp) return '-';
const ms = Date.now() - timestamp;
@@ -242,7 +249,15 @@ export default function BrowserPage() {
id="chromePath"
type="text"
value={configDraft.chromePath || ''}
- onChange={e => setConfigDraft(d => ({ ...d, chromePath: e.target.value }))}
+ onChange={e => setConfigDraft(d => {
+ const chromePath = e.target.value;
+ const nextAppBundle = deriveMacAppBundle(chromePath);
+ const currentAppBundle = deriveMacAppBundle(d.chromePath);
+ const macAppBundle = !d.macAppBundle || d.macAppBundle === currentAppBundle
+ ? nextAppBundle
+ : d.macAppBundle;
+ return { ...d, chromePath, macAppBundle };
+ })}
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"
/>
diff --git a/scripts/setup-browser.js b/scripts/setup-browser.js
index 17112f01bc..aaf4cd8b82 100644
--- a/scripts/setup-browser.js
+++ b/scripts/setup-browser.js
@@ -9,20 +9,24 @@
* 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.
+ * Idempotent: if `data/browser-config.json` already has a custom browser path
+ * or the user declined Canary, this exits without re-prompting.
+ * Non-interactive (CI / pm2-managed update.sh) runs skip silently unless
+ * `PORTOS_USE_CANARY=1` opts in to using an already-installed Canary; package
+ * manager installs stay interactive to avoid hanging on password prompts.
+ * `PORTOS_USE_CANARY=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 { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs';
import { createInterface } from 'readline';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { homedir, platform } from 'os';
+import { randomUUID } from 'crypto';
+import { hasConfiguredBrowser, normalizeBrowserConfig } from '../server/lib/browserConfig.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
@@ -51,7 +55,14 @@ function loadConfig() {
function saveConfig(config) {
if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });
- writeFileSync(configFile, JSON.stringify(config, null, 2));
+ const tmp = `${configFile}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
+ writeFileSync(tmp, `${JSON.stringify(normalizeBrowserConfig(config), null, 2)}\n`);
+ try {
+ renameSync(tmp, configFile);
+ } catch (err) {
+ try { unlinkSync(tmp); } catch {}
+ throw err;
+ }
}
function hasCommand(cmd, args) {
@@ -63,9 +74,14 @@ function hasCommand(cmd, args) {
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;
+ for (const app of [
+ '/Applications/Google Chrome Canary.app',
+ join(homedir(), 'Applications', 'Google Chrome Canary.app')
+ ]) {
+ const bin = `${app}/Contents/MacOS/Google Chrome Canary`;
+ if (existsSync(bin)) return { app, bin };
+ }
+ return null;
}
if (os === 'win32') {
const localAppData = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
@@ -94,10 +110,31 @@ function applyCanaryToConfig(found) {
}
config.chromePath = found.bin;
if (found.app) config.macAppBundle = found.app;
+ delete config.canaryPromptDeclined;
saveConfig(config);
console.log(`✅ PortOS browser set to Chrome Canary → ${found.bin}`);
}
+function markCanaryDeclined() {
+ const config = loadConfig();
+ if (config === null) {
+ console.warn(' Skipping Canary preference write — fix the corrupt browser-config.json first.');
+ return;
+ }
+ config.canaryPromptDeclined = true;
+ saveConfig(config);
+}
+
+function parseCanaryEnv(value) {
+ if (value === undefined) return null;
+ const normalized = String(value).trim().toLowerCase();
+ if (!normalized) return null;
+ if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
+ if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
+ console.warn(`⚠️ Ignoring PORTOS_USE_CANARY=${value}; expected one of 1/0, true/false, yes/no, on/off.`);
+ return null;
+}
+
function promptYesNo(question, defaultYes = true) {
return new Promise((resolve) => {
const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -119,17 +156,23 @@ async function runCanarySetup() {
return;
}
+ const canaryEnv = parseCanaryEnv(process.env.PORTOS_USE_CANARY);
+ if (canaryEnv === false) return;
+
const config = loadConfig();
- if (typeof config?.chromePath === 'string' && config.chromePath.trim()) {
+ if (config === null) return;
+
+ const envOptIn = canaryEnv === true;
+ if (hasConfiguredBrowser(config)) {
// Already configured — don't re-prompt on subsequent setup/update runs.
return;
}
+ if (!envOptIn && config.canaryPromptDeclined === true) {
+ 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
@@ -143,7 +186,10 @@ async function runCanarySetup() {
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.');
+ else {
+ markCanaryDeclined();
+ console.log(' Keeping the platform-default Chrome. You can switch later in Settings → Browser.');
+ }
return;
}
@@ -154,8 +200,14 @@ async function runCanarySetup() {
return;
}
+ if (!interactive) {
+ console.log(`💡 Chrome Canary not detected. Install it interactively via ${install.label} or from https://www.google.com/chrome/canary/, then re-run setup.`);
+ return;
+ }
+
const ok = envOptIn ? true : await promptYesNo(`Install Chrome Canary via ${install.label} and use it as the PortOS-managed browser?`, true);
if (!ok) {
+ markCanaryDeclined();
console.log(' Keeping the platform-default Chrome. You can switch later in Settings → Browser.');
return;
}
@@ -163,7 +215,9 @@ async function runCanarySetup() {
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.`);
+ const detail = result.error?.message
+ || (result.signal ? `signal ${result.signal}` : `exit ${result.status}`);
+ console.log(`⚠️ ${install.label} install of Chrome Canary failed (${detail}). You can install it manually and re-run setup.`);
return;
}
diff --git a/server/lib/README.md b/server/lib/README.md
index 5e73359835..f638e4b12a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -168,6 +168,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
+| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
| `db.js` | PostgreSQL connection pool. |
| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
| `platform.js` | Platform/OS detection helpers. |
diff --git a/server/lib/browserConfig.js b/server/lib/browserConfig.js
new file mode 100644
index 0000000000..749bedd060
--- /dev/null
+++ b/server/lib/browserConfig.js
@@ -0,0 +1,49 @@
+export function isNonEmptyString(value) {
+ return typeof value === 'string' && value.trim().length > 0;
+}
+
+export function deriveMacAppBundleFromChromePath(chromePath) {
+ if (!isNonEmptyString(chromePath)) return null;
+ const normalized = chromePath.trim().replaceAll('\\', '/');
+ const appMarker = '.app/';
+ const appIndex = normalized.toLowerCase().indexOf(appMarker);
+ if (appIndex < 0) return null;
+ return normalized.slice(0, appIndex + '.app'.length);
+}
+
+export function hasConfiguredBrowser(config) {
+ return isNonEmptyString(config?.chromePath) || isNonEmptyString(config?.macAppBundle);
+}
+
+export function normalizeBrowserConfig(config) {
+ const next = { ...(config || {}) };
+ if (!isNonEmptyString(next.macAppBundle)) {
+ const derived = deriveMacAppBundleFromChromePath(next.chromePath);
+ if (derived) next.macAppBundle = derived;
+ }
+ return next;
+}
+
+export function isMacAppBundlePath(value) {
+ if (!isNonEmptyString(value)) return false;
+ return /(^|[/\\])[^/\\]+\.app[/\\]?$/i.test(value.trim());
+}
+
+export function validateChromePath(value) {
+ if (!isNonEmptyString(value)) return null;
+ const trimmed = value.trim();
+ if (/[\\/]$/.test(trimmed)) return 'chromePath must point to an executable file, not a directory';
+ if (isMacAppBundlePath(trimmed)) {
+ return 'chromePath must point to the executable inside the .app bundle; use macAppBundle for the bundle path';
+ }
+ if ((/^[a-z]:[\\/]/i.test(trimmed) || trimmed.includes('\\')) && !/\.exe$/i.test(trimmed)) {
+ return 'chromePath must point to a Windows .exe file';
+ }
+ return null;
+}
+
+export function validateMacAppBundle(value) {
+ if (!isNonEmptyString(value)) return null;
+ if (!isMacAppBundlePath(value)) return 'macAppBundle must point to a macOS .app bundle';
+ return null;
+}
diff --git a/server/lib/browserConfig.test.js b/server/lib/browserConfig.test.js
new file mode 100644
index 0000000000..9b41f1a061
--- /dev/null
+++ b/server/lib/browserConfig.test.js
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import {
+ deriveMacAppBundleFromChromePath,
+ hasConfiguredBrowser,
+ normalizeBrowserConfig,
+ validateChromePath,
+ validateMacAppBundle,
+} from './browserConfig.js';
+
+describe('browserConfig', () => {
+ it('derives a macOS app bundle from an executable inside the bundle', () => {
+ expect(deriveMacAppBundleFromChromePath('/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'))
+ .toBe('/Applications/Google Chrome Canary.app');
+ });
+
+ it('normalizes config by filling macAppBundle when chromePath points inside an app', () => {
+ expect(normalizeBrowserConfig({
+ chromePath: '/Users/me/Applications/Chromium.app/Contents/MacOS/Chromium',
+ })).toEqual({
+ chromePath: '/Users/me/Applications/Chromium.app/Contents/MacOS/Chromium',
+ macAppBundle: '/Users/me/Applications/Chromium.app',
+ });
+ });
+
+ it('treats either chromePath or macAppBundle as an existing custom browser choice', () => {
+ expect(hasConfiguredBrowser({ chromePath: '' })).toBe(false);
+ expect(hasConfiguredBrowser({ macAppBundle: '/Applications/Brave Browser.app' })).toBe(true);
+ expect(hasConfiguredBrowser({ chromePath: '/usr/bin/chromium' })).toBe(true);
+ });
+
+ it('rejects a macOS app bundle in chromePath', () => {
+ expect(validateChromePath('/Applications/Google Chrome Canary.app'))
+ .toMatch(/executable inside the \.app bundle/);
+ });
+
+ it('requires Windows-style chromePath values to point at an exe', () => {
+ expect(validateChromePath('C:\\Program Files\\Google\\Chrome SxS\\Application\\chrome.exe')).toBe(null);
+ expect(validateChromePath('C:\\Program Files\\Google\\Chrome SxS\\Application')).toMatch(/Windows \.exe/);
+ });
+
+ it('requires macAppBundle to be a .app path', () => {
+ expect(validateMacAppBundle('/Applications/Google Chrome Canary.app')).toBe(null);
+ expect(validateMacAppBundle('/Applications/Google Chrome Canary')).toMatch(/\.app bundle/);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index b7b7ebe947..d1464d3c50 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -135,6 +135,7 @@ export * from './renderSlot.js';
export * from './telegramClient.js';
// === Model & config ===
+export * from './browserConfig.js';
export * from './buildId.js';
export * from './db.js';
export * from './platform.js';
diff --git a/server/routes/browser.js b/server/routes/browser.js
index f21059e465..1fa3947a9a 100644
--- a/server/routes/browser.js
+++ b/server/routes/browser.js
@@ -1,6 +1,7 @@
import express from 'express';
import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
+import { validateChromePath, validateMacAppBundle } from '../lib/browserConfig.js';
import * as browserService from '../services/browserService.js';
const router = express.Router();
@@ -20,6 +21,16 @@ const optionalPath = z.preprocess(
).optional()
);
+const chromePathSchema = optionalPath.superRefine((value, ctx) => {
+ const message = validateChromePath(value);
+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });
+});
+
+const macAppBundleSchema = optionalPath.superRefine((value, ctx) => {
+ const message = validateMacAppBundle(value);
+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });
+});
+
const updateConfigSchema = z.object({
cdpPort: z.number().int().min(1024).max(65535).optional(),
cdpHost: z.enum(['127.0.0.1', 'localhost', '::1']).optional(),
@@ -35,10 +46,11 @@ const updateConfigSchema = z.object({
// back to the platform default (`/Applications/Google Chrome.app/...` on
// macOS, `C:\Program Files\Google\Chrome\...` on Windows, `google-chrome`
// on Linux).
- chromePath: optionalPath,
+ chromePath: chromePathSchema,
// 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
+ macAppBundle: macAppBundleSchema,
+ canaryPromptDeclined: z.boolean().optional()
});
// GET /api/browser - Full browser status
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 195551b267..ac67261d54 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -4,12 +4,13 @@
* Stores config in data/browser-config.json
*/
-import { writeFile, readdir, stat, unlink } from 'fs/promises';
+import { readdir, stat, unlink } from 'fs/promises';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { join, basename, resolve, extname } from 'path';
import { EventEmitter } from 'events';
-import { ensureDir, safeJSONParse, PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { ensureDir, safeJSONParse, PATHS, tryReadFile, atomicWrite } from '../lib/fileUtils.js';
+import { normalizeBrowserConfig } from '../lib/browserConfig.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
const execFileAsync = promisify(execFile);
@@ -43,21 +44,30 @@ const DEFAULT_CONFIG = {
};
let cachedConfig = null;
+let cachedConfigMtimeMs = null;
// ---------- Config persistence ----------
+async function getConfigMtimeMs() {
+ const info = await stat(CONFIG_FILE).catch(() => null);
+ return info?.isFile() ? info.mtimeMs : null;
+}
+
export async function loadConfig() {
- if (cachedConfig) return cachedConfig;
+ const mtimeMs = await getConfigMtimeMs();
+ if (cachedConfig && cachedConfigMtimeMs === mtimeMs) return cachedConfig;
const raw = await tryReadFile(CONFIG_FILE);
const parsed = safeJSONParse(raw, null);
- cachedConfig = parsed ? { ...DEFAULT_CONFIG, ...parsed } : { ...DEFAULT_CONFIG };
+ cachedConfig = normalizeBrowserConfig(parsed ? { ...DEFAULT_CONFIG, ...parsed } : { ...DEFAULT_CONFIG });
+ cachedConfigMtimeMs = mtimeMs;
return cachedConfig;
}
export async function saveConfig(config) {
await ensureDir(PATHS.data);
- cachedConfig = { ...DEFAULT_CONFIG, ...config };
- await writeFile(CONFIG_FILE, JSON.stringify(cachedConfig, null, 2));
+ cachedConfig = normalizeBrowserConfig({ ...DEFAULT_CONFIG, ...config });
+ await atomicWrite(CONFIG_FILE, cachedConfig);
+ cachedConfigMtimeMs = await getConfigMtimeMs();
browserEvents.emit('config:changed', cachedConfig);
return cachedConfig;
}
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
new file mode 100644
index 0000000000..56bd987e6f
--- /dev/null
+++ b/server/services/browserService.test.js
@@ -0,0 +1,57 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, rm, utimes, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+describe('browserService config persistence', () => {
+ let tempRoot;
+
+ beforeEach(() => {
+ vi.resetModules();
+ tempRoot = createTempDataRoot('portos-browser-service-');
+ });
+
+ afterEach(async () => {
+ vi.doUnmock('../lib/fileUtils.js');
+ await rm(tempRoot, { recursive: true, force: true });
+ });
+
+ async function importService() {
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: tempRoot,
+ extraOverrides: (root) => ({
+ browserProfile: join(root, 'browser-profile'),
+ browserDownloads: join(root, 'downloads'),
+ }),
+ });
+ });
+ return import('./browserService.js');
+ }
+
+ it('atomically saves normalized config with a derived macOS app bundle', async () => {
+ const service = await importService();
+ const saved = await service.saveConfig({
+ chromePath: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
+ });
+
+ expect(saved.macAppBundle).toBe('/Applications/Google Chrome Canary.app');
+ const onDisk = JSON.parse(await readFile(join(tempRoot, 'browser-config.json'), 'utf-8'));
+ expect(onDisk.macAppBundle).toBe('/Applications/Google Chrome Canary.app');
+ });
+
+ it('reloads config after the setup script writes browser-config.json directly', async () => {
+ const service = await importService();
+ await service.saveConfig({ cdpPort: 5556 });
+ await mkdir(tempRoot, { recursive: true });
+ const configPath = join(tempRoot, 'browser-config.json');
+ await writeFile(configPath, JSON.stringify({ cdpPort: 6000, headless: false }));
+ const later = new Date(Date.now() + 1000);
+ await utimes(configPath, later, later);
+
+ const reloaded = await service.getConfig();
+ expect(reloaded.cdpPort).toBe(6000);
+ expect(reloaded.headless).toBe(false);
+ });
+});