Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .ai/contexts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ change without re-reading `main.js`, now ~4100 LOC.
|---|---|
| Module-move codemod, VM stub inference and layout checks | [module-moves](module-moves.md) |
| CLI adapter contract, Claude delegation and pure launch argv | [cli-harnesses](cli-harnesses.md) |
| Managed browser lifecycle library, Linux identity/lock and test-pr cleanup | [managed-browser](managed-browser.md) |
| The fast pre-commit check (staged lint, test selection) | [fast-check](fast-check.md) |
| SQLite, indexing, search, heatmap aggregation, fs.watch | [session-cache](session-cache.md) |
| Cron schedules, schedule `.md` files, `claude --resume -p` spawn | [schedule-runner](schedule-runner.md) |
Expand Down
138 changes: 138 additions & 0 deletions .ai/contexts/managed-browser.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Managed browser lifecycle (#812, S2)

`src/main/browser/managed-browser.js` exports `createManager` and
`cleanupDataDir`. It is CommonJS and Electron-free. Requiring it or constructing
a manager does no filesystem, socket, HTTP or process work. No renderer, IPC,
settings or session-launch path calls Open/ensureStarted in this slice. There
is no MCP dependency or configuration writer yet; that belongs to S3.

The main process constructs the manager using the directory of DB_PATH.
`shutdownForExit` calls `stopForQuit` synchronously immediately after its
repeat guard and before starting the bounded drain. Only an owner of a verified
child-mode browser with its own matching spawner identity sends SIGTERM there.
Scope/detached browsers and followers receive no quit signal. Source-extraction
fixtures must supply the manager when evaluating this shutdown function.
The quit call is caught and logged so a manager exception cannot prevent the
remaining bounded shutdown or the repeat guard from taking effect.

Operations are queued. Linux starts on explicit Open or ensureStarted only;
other platforms return an unsupported result without touching storage or
spawning. Results include status, role, port, binary, mode, survival, notice
and error. Errors stay recoverable values. Browser-open is best-effort HTTP
activation, with a PUT new-page fallback; compositor focus is unverified.

Discovery accepts an absolute ELF executable or numeric-descending Chromium cache
revisions. Executable launcher scripts are refused with a request to configure
the real Chromium ELF binary, for example `/usr/lib/chromium/chromium`, rather
than `/usr/bin/chromium`. Only the four-byte ELF magic is checked, not the ELF
architecture or browser provenance. An explicit cache root is authoritative.
Symlink hops, directory links and final targets are checked for Snap; no installed-browser fallback,
download, headless-shell or personal profile is used. A private canonical data
directory holds profile, output, state and a per-start truncated log. Directory
modes are 0700, file modes 0600; foreign owners and symlinks are refused.
State writes use unique exclusive temporary files, fsync and rename. Output
pruning covers only ordinary old files directly under output, after ownership
has been acquired. No profile files are pruned.

Failure memo keys include configured paths, cache-root/revision candidates and
binary metadata. Installing a browser or changing the selected binary retries
without waiting sixty seconds. A synchronous spawn refusal clears the pending
reservation; publication failure after spawn terminates only the verified
launch before returning an error. Ambiguous outcomes retain their state.

The owner lock is a Unix listener at a hash-derived path in a private absolute
XDG_RUNTIME_DIR, or a short socket under the managed directory. Live socket
means follower. ECONNREFUSED permits one inode-checked stale unlink/retry.
Long/unsafe/unavailable paths refuse management. Operations retry acquisition
for followers; followers do not write state, prune, start or stop. There remains
a simultaneous stale-takeover check/unlink race: a competing new socket could
replace the checked inode before unlink. The browser profile singleton is the
last backstop, not the locking protocol. Socket close has a similar unavoidable
pathname race. Neither is a cross-user security boundary.

State schema version 1 records a persistent port, canonical profile/binary,
PID/startTime/boot identity, spawner identity, mode, unit and start time. Pending
launches also record the launcher's PID/startTime/boot immediately after spawn,
before readiness polling. A port
reservation may have no PID. Start time and boot ID, rather than PID existence,
decide whether a recorded browser still exists. A reused PID or another boot
resets the state to a port-only reservation without signalling the replacement.
An owner reconciles a pending ambiguous launch before Start or Stop: in the same
boot, a still-live launcher or an unavailable launcher identity blocks recovery
with an error, retaining the pending state and profile. Once the recorded
launcher identity is gone (including PID reuse), scan for the exact
binary/profile/port and adopt a verified match; no match clears the pending
state to a port-only reservation. A different boot clears it without scanning.
Missing boot identity or an adoption verification failure retains data.
Followers cannot reconcile or write pending state. Stop and cleanup therefore
cannot authorize profile deletion while a slow launcher could still exec the
browser, and another Open cannot spawn a duplicate. Legacy pending states
without a recorded launcher remain uncertain within the same boot.
An unverified failed/timed-out launch receives a best-effort positive-PID TERM
only when the recorded launcher identity still matches, rechecked immediately
before signalling. Its pending state remains available for owner recovery,
including when the launcher ignores TERM; a reused launcher PID is not signalled.
Reserve before discovery; reuse across Stop/Open. Foreign occupation replaces the port and returns a
restart-sessions notice. Bind/spawn races are checked against the actual
listener, with at most three allocations in the start budget.

Linux identity uses field 22 from proc stat (index 19 after the final `)`), boot
ID, executable, exact profile/port argv and the listening socket inode in that
PID's fds. TCP6 or wildcard listeners are refused. Joined and NUL argv forms
are supported, with bounded size and exactly one profile and debugging-port
argument. A version HTTP response alone cannot establish ownership.
Listener ownership by a browser child is deliberately unsupported pending real
headful evidence. Source orphan adoption requires a dead start-verified spawner
and records the new one before it can signal at quit.

Packaged starts use systemd-run --user --scope, detached/unref and file-backed
stdio; every command argument doubles dollars. Only a definite missing-user-bus
failure before a browser exists permits one detached fallback. It is marked as
not surviving restart. FATAL/sandbox errors and ambiguous timeouts never cause
a detached or no-sandbox retry. Chromium's sandbox remains enabled.
Dollar handling is NOT verified against real systemd: `--scope` may not perform
the environment expansion that doubling dollars assumes. The escaping behavior
is preserved pending a real systemd check, including literal-dollar paths.

Normal Stop re-verifies the endpoint, sends Browser.close, waits five seconds,
then re-verifies immediately before TERM (three seconds) and KILL (one second).
Descendant ancestry is captured before close, but ancestry alone does not
authorize a signal: a descendant must have the browser executable, an exact
profile argument, or a Chromium `--type=` argument on a crashpad handler
(`chrome_crashpad_handler` or `crashpad_handler`) alongside the browser binary.
An arbitrary executable's `--type=` is insufficient. Only verified descendants
become parents for further traversal: the walk stops at a native-messaging host
even if its children use the browser executable or Electron type markers.
Start time, boot ID and
these executable/argv markers are checked again immediately before each
positive-PID signal. Unrelated native-messaging hosts and download handlers,
including descendants that exec into them during close, are left alive.
When the browser identity still verifies but its listener has already closed,
Stop skips CDP and waits up to five seconds for exit before the usual verified
TERM/KILL escalation. A listener disappearing during endpoint verification uses
the same path. A foreign listener or identity change still refuses signalling.
Without pidfd, identity-check-to-signal races remain; no process group, name or
scope-wide kill is used. The twenty-second start readiness budget and bounded
HTTP responses do not prove Linux sandbox, cgroup or signed-in survival.

HTTP requests have both a 500 ms total deadline and an inactivity timeout, plus
a 64 KiB response limit. WebSocket uses the existing runtime `ws` dependency so
it also works without a Node global WebSocket. Permission failure during owner
socket setup closes the listener before rejecting acquisition.

`scripts/test-pr.js` captures SWITCHBOARD_DATA_DIR before fixture preparation,
awaits cleanup on launch success/rejection/fixture error, and removes launchCwd
only after confirmed browser exit. A cleanup error retains both paths with a
warning. `cleanWorktree` is now async and stops the browser before unlinking
the dependency junction or removing the worktree/data. It never creates a
manager when no managed-browser directory exists. Windows refuses cleanup of
an unexpected existing browser directory rather than guessing at Linux PIDs.

Tests use real disposable files, fake process/clock/lock boundaries, injected
procfs/net fixtures and a Node HTTP/WebSocket fake browser. Windows tests prove
the unsupported policy; Linux mode/permissions/process behavior still requires
Linux execution. No real browser, Electron or Playwright is needed for S2.

Loopback CDP has no user/session authentication. Other local processes can
control the signed-in browser; this library is not a filesystem or network
isolation boundary. Chromium's own sandbox stays enabled.
2 changes: 2 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
}

// Shell profiles → shell-profiles.js
const { discoverShellProfiles, getShellProfiles, resolveShell, isWindows, isWslShell, windowsToWslPath, shellArgs, quoteArgvForShell } = require('./src/main/terminals/shell-profiles');

Check warning on line 86 in main.js

View workflow job for this annotation

GitHub Actions / lint

'discoverShellProfiles' is assigned a value but never used. Allowed unused vars must match /^_/u
const { startScheduler, scheduleLaunchRefusal, resolveScheduleSandbox, initialScheduleProjects, scanSchedules, setScheduleEnabled } = require('./src/main/schedules/schedule-runner');
const { buildScheduleList } = require('./src/main/schedules/schedule-list');
const { archivePlanForGroups, validArchiveGroups } = require('./archived-projects');
Expand Down Expand Up @@ -261,6 +261,7 @@
// The trace file sits next to switchboard.db — DB_PATH is the one resolution
// of SWITCHBOARD_DATA_DIR, never re-derived here.
const TRACE_DIR = path.dirname(DB_PATH);
const managedBrowser = require('./src/main/browser/managed-browser').createManager({ dataDir: TRACE_DIR, isPackaged: app.isPackaged });
const PLAIN_TERMINAL_INIT_DIR = path.join(path.dirname(DB_PATH), 'shell-init');
activityTrace.init(TRACE_DIR);
activityTrace.setEnabled(
Expand Down Expand Up @@ -596,8 +597,8 @@
getMainWindow: () => mainWindow,
log,
});
const { readSessionFile, readFolderFromFilesystem,

Check warning on line 600 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readFolderFromFilesystem' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 600 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readSessionFile' is assigned a value but never used. Allowed unused vars must match /^_/u
backfillEntrypoints, backfillCustomTitles, revealIfSdkSession, notifyRendererProjectsChanged, sendStatus, populateCacheViaWorker,

Check warning on line 601 in main.js

View workflow job for this annotation

GitHub Actions / lint

'sendStatus' is assigned a value but never used. Allowed unused vars must match /^_/u
scanFoldersViaWorker, setRemoteRoots, resolveFolderDir, isIndexingFinished } = sessionCache;
// see .ai/contexts/session-cache.md ("Projects query worker")
const { createProjectsWorkerClient } = require('./projects-worker-client');
Expand Down Expand Up @@ -3047,7 +3048,7 @@
// WSL profiles only work for plain terminals — Claude CLI sessions need the
// Windows shell because session data lives on the Windows filesystem.
const requestedProfile = resolveShell(effectiveProfileId);
const useWslProfile = isWslShell(requestedProfile.path) && isPlainTerminal;

Check warning on line 3051 in main.js

View workflow job for this annotation

GitHub Actions / lint

'useWslProfile' is assigned a value but never used. Allowed unused vars must match /^_/u
const shellProfile = (isWslShell(requestedProfile.path) && !isPlainTerminal)
? resolveShell('auto')
: requestedProfile;
Expand Down Expand Up @@ -4215,6 +4216,7 @@
}
function shutdownForExit() {
if (shutdownPromise) return shutdownPromise;
try { managedBrowser.stopForQuit(); } catch (error) { log.error('[shutdown] managed browser quit failed', error); }
shutdownPromise = boundedShutdown(() => writer.beginShutdown(async () => {
appQuitting = true;
if (TRACE.on) trace('app.quit', null, {});
Expand Down
21 changes: 16 additions & 5 deletions scripts/test-pr.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const path = require('node:path');
const { execFileSync, spawn } = require('node:child_process');
const { isDeepStrictEqual } = require('node:util');
const { scrubSessionEnv } = require('../src/main/shared/clean-env');
const { cleanupDataDir } = require('../src/main/browser/managed-browser');

function validatePr(pr) {
if (!/^\d+$/.test(String(pr ?? ''))) throw new Error('PR must be numeric: task test-pr PR=<number>');
Expand Down Expand Up @@ -160,12 +161,14 @@ function parseBundleScript(script) {
return options;
}

function cleanWorktree({ checkout, pr, home = process.env.HOME || os.homedir(), run = runCommand }) {
async function cleanWorktree({ checkout, pr, home = process.env.HOME || os.homedir(), run = runCommand, stopBrowser = cleanupDataDir }) {
validatePr(pr);
const data = path.join(home, `.switchboard-dev-pr${pr}`);
if (!await stopBrowser(data)) throw new Error(`Browser exit uncertain; retaining ${data} and worktree`);
const worktree = path.join(checkout, '.worktrees', `pr-${pr}-test`);
unlinkNodeModules(worktree);
run('git', ['worktree', 'remove', '--force', worktree], { cwd: checkout, stdio: 'inherit' });
fs.rmSync(path.join(home, `.switchboard-dev-pr${pr}`), { recursive: true, force: true });
fs.rmSync(data, { recursive: true, force: true });
}

function runElectron(executable, args, options) {
Expand Down Expand Up @@ -193,6 +196,7 @@ function runElectron(executable, args, options) {

async function main({ checkout = path.resolve(__dirname, '..'), env = process.env,
clean = false, run = runCommand, launch = runElectron, fixtures = prepareFixtures,
stopBrowser = cleanupDataDir,
log = console.log, warn = console.error,
removeDir = dir => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) } = {}) {
const pr = env.PR;
Expand All @@ -201,7 +205,7 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en
const allowClaude = validateAllowClaude(env.ALLOW_CLAUDE, isolated);
const home = env.HOME || os.homedir();
if (clean) {
cleanWorktree({ checkout, pr, home, run });
await cleanWorktree({ checkout, pr, home, run, stopBrowser });
log(`Cleaned up worktree and data dir for PR #${pr}`);
return 0;
}
Expand Down Expand Up @@ -236,10 +240,11 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en
}
let tempHome;
let launchCwd;
let config;
try {
launchCwd = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `sb-pr-${pr}-`)));
if (isolated) tempHome = launchCwd;
const config = buildLaunch({ pr, home, env, isolated, allowClaude, tempHome, port: env.DEBUG_PORT || 9223,
config = buildLaunch({ pr, home, env, isolated, allowClaude, tempHome, port: env.DEBUG_PORT || 9223,
entry: path.resolve(worktree) });
if (isolated) {
fixtures(tempHome, config.env, { allowClaude });
Expand All @@ -254,7 +259,13 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en
const executable = require(path.join(worktree, 'node_modules', 'electron'));
return await launch(executable, config.args, { cwd: launchCwd, env: config.env });
} finally {
if (launchCwd) {
let stopped = true;
if (config) {
try { stopped = await stopBrowser(config.env.SWITCHBOARD_DATA_DIR); }
catch (error) { stopped = false; warn(`Browser cleanup failed: ${error.message}`); }
if (!stopped) warn(`Browser exit uncertain; retaining ${launchCwd} and ${config.env.SWITCHBOARD_DATA_DIR}. Stop the verified browser before removing them.`);
}
if (launchCwd && stopped) {
try {
removeDir(launchCwd);
} catch (error) {
Expand Down
58 changes: 58 additions & 0 deletions src/main/browser/discovery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';

const path = require('node:path');

function snap(file) {
return /(^|\/)snap(\/|$)|(^|\/)(snap|snapd)$/.test(file.replace(/\\/g, '/'));
}

function executable(file, fs) {
if (!path.isAbsolute(file)) throw new Error('Browser binary must be absolute');
let current = file;
for (let hop = 0; hop < 40; hop++) {
if (snap(current)) throw new Error('Snap browsers are unsupported; configure a native executable');
const parts = path.resolve(current).split(path.sep);
let prefix = parts.shift() + path.sep;
let redirected = false;
for (let i = 0; i < parts.length; i++) {
prefix = path.join(prefix, parts[i]);
const stat = fs.lstatSync(prefix);
if (stat.isSymbolicLink()) {
current = path.resolve(path.dirname(prefix), fs.readlinkSync(prefix), ...parts.slice(i + 1));
redirected = true;
break;
}
}
if (redirected) continue;
const real = fs.realpathSync(current);
if (snap(real) || /headless[_-]shell/.test(real)) throw new Error('Snap and headless-shell browsers are unsupported');
if (!fs.statSync(real).isFile()) throw new Error('Browser is not an executable file');
fs.accessSync(real, fs.constants?.X_OK ?? 1);
const fd = fs.openSync(real, 'r');
const magic = Buffer.alloc(4);
try { fs.readSync(fd, magic, 0, magic.length, 0); } finally { fs.closeSync(fd); }
if (!magic.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) throw new Error(`Browser ${real} is not ELF; configure the real Chromium binary (for example /usr/lib/chromium/chromium), not its launcher script`);
return real;
}
throw new Error('Browser symlink chain is too long');
}

function discoverBrowser({ binaryPath = '', env = process.env, home = require('node:os').homedir(), fs = require('node:fs') } = {}) {
if (binaryPath) {
try { return { binary: executable(binaryPath, fs), source: 'configured' }; }
catch (error) { throw new Error(`Configure an absolute executable Chromium binary: ${error.message}`); }
}
const root = env.PLAYWRIGHT_BROWSERS_PATH ?? path.join(home, '.cache', 'ms-playwright');
if (!path.isAbsolute(root)) throw new Error('PLAYWRIGHT_BROWSERS_PATH must be absolute');
let revisions;
try { revisions = fs.readdirSync(root).filter(name => /^chromium-\d+$/.test(name)); } catch { revisions = []; }
revisions.sort((a, b) => Number(b.slice(9)) - Number(a.slice(9)));
for (const revision of revisions) {
for (const layout of ['chrome-linux64', 'chrome-linux']) {
try { return { binary: executable(path.join(root, revision, layout, 'chrome'), fs), source: 'playwright-cache' }; } catch {}
}
}
throw new Error('Install Playwright Chromium manually or configure an absolute executable browser path');
}

module.exports = { discoverBrowser };
Loading
Loading