> Opened by @user_01KNA8J74D4RF84RXSDRX26BS9
> Opened by @user_01KNA8J74D4RF84RXSDRX26BS9
## Summary
Fixes#28664
Once the Stagehand browser had run on a profile, every later launch on
that profile could fail with `ECONNREFUSED 127.0.0.1:<port>`. Killing
Chrome didn't fix it. The only fix was deleting the profile, which also
wipes saved logins.
**Primary cause:** chrome-launcher opens `<profile>/chrome-err.log` in
append mode. It finds the DevTools port by taking the *first* `DevTools
listening on ws://…:<port>/` match in the whole file. On a reused
profile, that match is the port from the earliest launch, which is dead
by now. (Diagnosis and real-Chrome repro by @NikAiyer.)
**Secondary cause:** Mastra Code never closed the Chrome it launched. It
didn't on exit, on relaunch, or when `/browser` replaced or disabled it.
A leftover Chrome could keep holding the profile.
**Changes:**
- **`@mastra/core`** (minor, new API):
- Before launching on a local profile, a new `prepareLocalProfile()`
step checks the profile's Chrome lock.
- A stale lock is removed.
- A live holder throws the new exported `BrowserProfileInUseError`,
which names the profile and the PID.
- A live local PID that hasn't started listening on the socket yet
(Chrome creates the lock first) gets up to 3s before its lock counts as
stale.
- Only after that check passes does it delete `chrome-err.log` and
`chrome-out.log`.
- The step is skipped on Windows and for remote browsers.
- Close and disconnect only remove the lock when no Chrome is listening,
so a late close can't delete the lock of a browser that took the profile
meanwhile.
- New `MastraBrowser.retire()` closes a browser for good, so later
`ensureReady()` and `launch()` calls throw.
- New `MastraBrowser.killProcesses()` SIGKILLs the browser's process
groups.
- **`@mastra/stagehand`**: thread-scoped browsers also run
`prepareLocalProfile()` before each thread's Chrome starts, when the
installed core has it. The core peer range stays `>=1.80.0-0`; on 1.80.0
Stagehand behaves as before instead of throwing.
- **`mastracode`**:
- It retires the active browser on exit, on relaunch, and when
`/browser` replaces or disables it. If the retire fails or takes longer
than 5s, it kills the browser's processes.
- A generation guard stops a `/browser` call that lost a race from
attaching its browser or saving settings.
## Proof
- Core `browser.test.ts`: 36/36 pass. Each of these fails when its fix
is removed:
- relaunch reading the second port
- stale logs cleared before `doLaunch()`
- stale lock and live holder handling, including a SIGKILLed holder that
left its socket behind (`ECONNREFUSED`)
- a live holder that starts listening 300ms after locking is treated as
holding the profile
- a late close leaving the new holder's lock alone
- retire blocking a relaunch that is already waiting in `ensureReady()`
- `killProcesses()` is tested against a real detached process group.
- Stagehand unit tests: 70/70 pass. The thread-scope profile-prep test
and the "core without `prepareLocalProfile()`" test each fail without
their change.
- `mastracode/tui` `/browser` and lifecycle tests: 56/56 pass. The race,
close-order and kill-on-hang tests each fail when their fix is removed.
- @NikAiyer ran real Chrome on macOS at `0204188b` and `ff7acb14`,
including the real `~/.mastracode/browser-profile-stagehand` profile:
open → close → reopen works and keeps saved cookies; released Mastra
Code fails it with `ECONNREFUSED`.
- `tsc --noEmit` is clean for core, stagehand and mastracode/tui. oxlint
and the peer-dep validator are clean.
## Unverified
- Lock behaviour on Windows and Linux. Real Chrome was only run on
macOS.
- The 3s startup window has not been run against real Chrome.
- Two Stagehand `manual close` e2e cases fail on `hasLockFiles`. They
fail the same way on base.
- A lock from a different hostname is treated as stale.
## Risk
**Low.** Only two launcher log files are deleted, and only when we're
about to launch Chrome on that profile and no live browser holds it.
Lock files are removed only when nothing accepts connections on the
singleton socket. Remote browsers are untouched. Retiring and killing
only affect browsers Mastra Code is replacing or shutting down.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
Old Chrome files or a Chrome process that still uses a browser profile
can stop a new browser from starting. This change removes stale files,
reports when a profile is still in use, and closes browsers that Mastra
Code replaces or shuts down.
## What changed
- Before launching with a local profile, core checks for a live Chrome
lock. On non-Windows systems, it removes stale lock files and clears
Chrome launcher logs without deleting the profile. If a browser is using
the profile, it throws `BrowserProfileInUseError` with the profile path
and available process details. Core waits up to three seconds for a live
local lock holder to start listening.
- `MastraBrowser.retire()` closes a browser and prevents it from
launching again. `killProcesses()` force-stops tracked browser processes
where supported. Core uses these APIs during close and retirement.
- Stagehand prepares local profiles before thread-scoped browser
creation. It does not prepare profiles for Browserbase or CDP
connections. The Stagehand peer dependency requires `@mastra/core
>=1.81.0-0`; the code-sdk changeset also requires core 1.81.0 or later.
- Mastra Code closes browsers on shutdown, replacement, and disable.
Generation checks prevent superseded commands from attaching a browser
or saving settings. Replacements wait for earlier closes. If retirement
fails or takes more than five seconds, Mastra Code calls
`killProcesses()`.
- Tests cover profile-lock recovery, profile reuse, browser retirement
and process cleanup, Stagehand thread-scoped preparation, and
overlapping browser commands.
## Validation
The PR reports 36/36 core browser tests, 70/70 Stagehand unit tests, and
56/56 Mastra Code TUI browser and lifecycle tests passing. It also
reports clean TypeScript, oxlint, and peer-dependency checks, plus
real-Chrome testing on macOS. Windows and Linux lock behavior and the
three-second startup window were not verified with real Chrome. Two
Stagehand manual-close end-to-end cases fail on this branch and on the
base branch.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>