Skip to content

feat(browser): add isolated Chrome lifecycle - #28

Merged
ElbertePlinio merged 15 commits into
mainfrom
feat/browser-lifecycle
Jul 13, 2026
Merged

ElbertePlinio merged 15 commits into
mainfrom
feat/browser-lifecycle

Conversation

@ElbertePlinio

@ElbertePlinio ElbertePlinio commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Changed

  • Add isolated headed Chrome/Chromium sessions owning private Xvfb and ephemeral runtime directories.
  • Discover loopback CDP through port 0 and DevToolsActivePort without persisting capability URLs.
  • Persist and verify process identities before readiness, teardown Chrome → VNC → Xvfb, and keep partial cleanup retryable.
  • Add CLI/MCP create, status, destroy, and destroy-all support.
  • Remove the complete browser session directory after verified successful teardown.

This completes PR 5 of #17. Defensive pre-identity cleanup hardening is tracked in #29.

Validated

  • bun run typecheck
  • bun run build
  • Full coverage suite: 63 files, 705 passed / 2 skipped; thresholds met
  • Final browser lifecycle suite: 24/24 passed
  • Real built CLI: create → status → type/navigation → screenshot → destroy
  • Verified Chrome, Xvfb, profile, session logs, and record were removed
  • Verified chrome.log contained no ws:// or /devtools/browser/ capability URL
  • Serious local workflow review: correctness + security; targeted fix verification clean

Not tested

  • Installer/updater flow
  • Platforms outside Linux

Risk

Chrome runs under the invoking UID. Loopback CDP is not isolation from other same-UID local processes; use a VM or throwaway account for hostile pages.

Closes #18
Refs #17
Refs #29

Wire isolated Chrome sessions through the built CLI and MCP surfaces while preserving retryable process cleanup on partial startup failures.
@ElbertePlinio

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe5a9c649f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/browser/src/session.ts Outdated
Comment on lines +101 to +106
await fs.promises.mkdir(layout.profileDir, { recursive: true });
await fs.promises.mkdir(layout.xdgConfigHome, { recursive: true });
await fs.promises.mkdir(layout.xdgCacheHome, { recursive: true });
await fs.promises.mkdir(layout.xdgDataHome, { recursive: true });
await fs.promises.mkdir(layout.xdgStateHome, { recursive: true });
await fs.promises.mkdir(layout.tmpDir, { recursive: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make browser runtime directories private

On shared Linux hosts with the usual 022 umask, these mkdir calls create the Chrome profile, HOME/XDG parents, and tmp dir as traversable/readable by other local users until destroy. Since the new browser session can contain history, cache, cookies, downloads, and other page data during a run, the isolation guarantee should not depend on the caller's umask; create/chmod the session/profile/home/tmp tree to 0700 similarly to XDG_RUNTIME_DIR.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 368607e. Browser session, profile, HOME, XDG, and tmp directories are explicitly chmod 0700; a zero-umask regression asserts every mode.

Comment thread packages/browser/src/devtools.ts Outdated
Comment on lines +67 to +68
if (port !== undefined) {
return { ok: true, port };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Re-check Chrome is alive before accepting the port

If Chrome writes DevToolsActivePort and then immediately crashes, this returns success as soon as the stale file is visible, without verifying that the browser process or CDP endpoint is still alive. In that startup-crash window the supervisor can still be alive briefly, so createBrowserSession may record a running session with a dead/unusable CDP port instead of failing and cleaning it up.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 368607e. Startup now requires the recorded identity to remain live and a direct loopback 200 from /json/version, with abort and crash-after-port regressions.

Comment thread packages/core/src/paths.ts Outdated
Comment on lines +51 to +55
const base = path.resolve(sessionDir);
const resolved = path.resolve(profileDir);
return (
resolved === path.join(base, "profile") ||
resolved.startsWith(base + path.sep)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve symlinks before trusting profile confinement

Because this guard is purely lexical, a recorded profileDir such as <session>/link/cache passes even when <session>/link is a symlink to a directory outside the session tree. destroyBrowserSession then passes that path to fs.rm, which follows the intermediate symlink and can delete data outside PickLab's session directory; since this is the tamper guard, it needs realpath/lstat protection or should only accept the exact real profile directory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 368607e. Cleanup now uses async lstat/realpath confinement, rejects symlinked ancestry, and leaves the external target untouched in regression coverage.

Comment thread packages/core/src/session.ts Outdated
Comment on lines +312 to +314
await fs.promises.rm(sessionDir, { recursive: true, force: true }).catch(
() => {},
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve records when profile removal fails

When reaping a dead browser session, any failure to remove the session/profile directory is swallowed and the function still returns success, so reapDeadRunningSessions deletes the session record. On EPERM/EBUSY/NFS or other partial filesystem failures, profile data can be left behind with no errored record for retry or inspection, unlike destroyBrowserSession which aggregates cleanup failures.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 368607e. Reaper cleanup failures persist an errored retryable record; a transient failure regression proves the next reap completes removal.

Protect private runtime data, validate CDP readiness, and preserve retryable records when teardown cannot finish.
@ElbertePlinio

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 368607e03a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/browser/src/devtools.ts Outdated
const probeSignal =
signal === undefined
? timeoutSignal
: AbortSignal.any([signal, timeoutSignal]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid AbortSignal.any for advertised Node 20.0

AbortSignal.any was only added in Node 20.3, while these packages still advertise node >=20. When a signal is provided (for example MCP passes extra.signal into browser creation), Node 20.0–20.2 throws here; the surrounding catch then hides the TypeError and the DevTools probe returns false until startup times out even though Chrome is ready. Either raise the engine floor or compose the timeout/client signals without AbortSignal.any.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 25c5a74. Probe cancellation now composes caller abort and timeout with a local AbortController plus explicit listener/timer cleanup, compatible with the advertised Node 20 floor.

Compose probe cancellation without APIs introduced after the advertised runtime floor.
@ElbertePlinio

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 25c5a74495

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/browser/src/session.ts Outdated
Comment on lines +221 to +225
const daemon = await startDaemon(supervised.command, supervised.args, {
logDir,
name: "chrome",
env: childEnv,
cleanEnv: true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid persisting DevTools websocket URLs in chrome.log

When real Chrome starts with --remote-debugging-port, it writes the full ws://127.0.0.1:.../devtools/browser/<GUID> endpoint to stderr; this launch sends Chrome/supervisor stderr to the persistent chrome.log via startDaemon with name: "chrome". That means every live browser session records the capability URL the rest of this change carefully avoids storing in the session record, and callers with access to diagnostics/logDir can recover it. Suppress or scrub this line before persisting the Chrome log.

Useful? React with 👍 / 👎.

Comment on lines +329 to +333
: {
status: "error",
...(desktop === undefined ? {} : { desktop }),
...(browser === undefined ? {} : { browser }),
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark incomplete startup cleanup for retry

When startup fails after spawning Chrome/Xvfb and this cleanup is incomplete (for example the group is still unverified or profile removal failed), this branch preserves the pids/profile in an error record but does not set the reaperCleanupPending marker that reapDeadRunningSessions requires before retrying error-state cleanup. A later session create therefore skips the orphaned browser/Xvfb/profile even if it has become cleanable, leaving users to discover and destroy a failed id that create never returned; set the cleanup-pending metadata when cleanupComplete is false.

Useful? React with 👍 / 👎.

Comment thread packages/browser/src/session.ts Outdated
xvfbAlive,
displayAlive,
browserAlive,
alive: xvfbAlive && browserAlive,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat a missing browser display as dead

If the Xvfb socket disappears while the recorded Xvfb pid is still alive (for example after /tmp/.X11-unix/X* is removed), displayAlive is false but alive stays true here, so CLI/MCP status keeps reporting the browser session as running even though screenshot/input tools cannot connect to its display. Include displayAlive in this liveness result so unusable browser displays are surfaced as dead.

Useful? React with 👍 / 👎.

ElbertePlinio and others added 7 commits July 12, 2026 21:13
Redact CDP capabilities and make partial browser, display, and runtime cleanup identity-safe and retryable.
Retry failed teardown, verify display identities, escalate surviving groups, and honor cancellation through session commit.
Keep no-identity desktop records live without signaling bare PIDs and make malformed display records non-throwing.
Propagate cancellation into Xvfb launch and verify teardown before returning an abort.
Persist incomplete Xvfb ownership for retry and make browser readiness polling cancellation-aware.
Durably record browser and display identities before polling, and retain retryable teardown state on partial failures.
@ElbertePlinio

Copy link
Copy Markdown
Member Author

Current-head CI follow-up pushed in 02c444b.

Run 29233501902 exposed two test races, not product failures:

  • Fake Xvfb used a hardcoded /usr/bin/node; it now uses the active runtime path.
  • Supervisor cleanup can safely finish either before or after the leader is fully reaped; the test now asserts both valid outcomes and independently checks browser group, Xvfb, profile, and record cleanup.

Validation after the fix:

  • Xvfb abort test: 5/5
  • Supervisor race test: 20/20 across review + verification, exercising both branches
  • Full suite: 63 files, 705 passed / 2 skipped
  • Typecheck and diff check passed
  • Targeted local review and fix verifier clean

Waiting for required CI on the new HEAD.

@ElbertePlinio
ElbertePlinio merged commit eddf853 into main Jul 13, 2026
1 check passed
@ElbertePlinio
ElbertePlinio deleted the feat/browser-lifecycle branch July 13, 2026 08:27
@ElbertePlinio ElbertePlinio mentioned this pull request Sep 9, 2026
56 of 58 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add isolated headed Chrome browser sessions

1 participant