Repository navigation
Description
Environment Information
Stagehand:
- Language/SDK:
browseCLI (packages/cli) - Stagehand version:
[email protected](npm latest), andmainat8901460d
AI Provider:
- Provider: none needed
- Model: none needed
Issue Description
If the driver daemon is told to stop while its first browser launch is still in flight, stop
returns { stopped: true } and removes the daemon's socket and pid files, but the launch then
finishes and the daemon keeps the new browser. Nothing closes it. In remote mode the Browserbase
session stays up until its own timeout. The daemon process does not exit either: oclif does not
call process.exit after run(), and the open browser connection (and, in local mode, the Chrome
child process) keeps the event loop busy. No browse command can reach it any more.
DriverSessionManager.close() only closes the browser it already holds. It does not know about an init that is still running, and that init installs its browser after close() returned.
Steps to Reproduce
browse open https://example.com --remote(or local). The daemon startsinitialize(). Launch takes a few seconds (Browserbase session create, extension provisioning,Stagehand.create, or local Chrome + extension startup).- The
browse openclient goes away before the launch returns: Ctrl+C, the client's own request timeout, or an agent harness killing it. browse stop. The daemon handles each connection on its own, sostopruns at once.closeServer()returns because no connection is left open.manager.close()finds no browser yet. The socket and pid files are removed.- The launch finishes. The manager stores the browser and Stagehand instance and keeps them.
Minimal Reproduction Code
A test in packages/cli/tests/driver-foundation.test.ts, next to the existing "closes the browser when Stagehand.create fails" tests. It mocks @browserbasehq/stagehand the same way they do, so there is no real browser. The launch is a promise the test resolves itself, so the order is fixed.
it("closes a browser whose launch was still in flight when the manager closed", async () => {
let finishLaunch!: (browser: unknown) => void;
const closeBrowser = vi.fn().mockResolvedValue(undefined);
const browser = { close: closeBrowser, context: {} };
const launch = vi.fn(
() =>
new Promise((resolve) => {
finishLaunch = resolve;
}),
);
const closeStagehand = vi.fn().mockResolvedValue(undefined);
const create = vi.fn().mockResolvedValue({ browser, close: closeStagehand });
vi.resetModules();
vi.doMock("@browserbasehq/stagehand", () => ({
localBrowser: { connect: vi.fn(), launch },
Stagehand: { create },
}));
try {
const { DriverSessionManager: MockedDriverSessionManager } =
await import("../src/lib/driver/session-manager.js");
const manager = new MockedDriverSessionManager("close-during-launch", {
headless: true,
kind: "managed-local",
});
// `browse open` starts the first init; the browser launch is still pending.
const opening = manager.stagehandInstance();
await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());
// `browse stop` (or SIGTERM) closes the manager before the launch returns.
await manager.close();
finishLaunch(browser);
await opening.catch(() => undefined);
expect(closeStagehand).toHaveBeenCalledOnce();
expect(closeBrowser).toHaveBeenCalledOnce();
expect((await manager.status()).initialized).toBe(false);
} finally {
vi.doUnmock("@browserbasehq/stagehand");
vi.resetModules();
}
});cd packages/cli && pnpm exec vitest run tests/driver-foundation.test.ts -t "still in flight"
Error Messages / Log trace
Current, 3 runs of 3 failed on 8901460d:
FAIL tests/driver-foundation.test.ts > driver foundation > closes a browser whose launch was still in flight when the manager closed
AssertionError: expected "vi.fn()" to be called once, but got 0 times
❯ tests/driver-foundation.test.ts:1365:30
1363| await opening.catch(() => undefined);
1364|
1365| expect(closeStagehand).toHaveBeenCalledOnce();
| ^
1366| expect(closeBrowser).toHaveBeenCalledOnce();
1367| expect((await manager.status()).initialized).toBe(false);
Test Files 1 failed (1)
Tests 1 failed | 51 skipped (52)
Expected: once the manager is closed, a browser that finishes launching afterwards is closed too, and the manager does not report itself as initialized.
The same test fails the same way against dist/lib/driver/session-manager.js from the published [email protected].
End-to-end verification on macOS (8901460d) with a real browse daemon child process and headless Chrome over the unix socket shows the same behavior: sending open (about:blank), dropping the open client socket while Chrome launch is in flight, and immediately sending stop returns {"data":{"stopped":true},"type":"success"} and unlinks both .sock and .pid, while the daemon Node process (exitCode: null) and its spawned headless Chrome process tree remain running.
Why it happens
On SHA 8901460d:
packages/cli/src/lib/driver/daemon/server.ts:43handles every connection on its own, so astoprequest does not wait for anopenin progress.shutdown()(server.ts:35-36) waits forcloseServer(), which only waits for open sockets. Once theopenclient has gone, it returns right away and callsmanager.close().packages/cli/src/lib/driver/session-manager.ts:207-224:close()readsthis.stagehandandthis.browser, sets them to null and closes what it found. It does not look atthis.initPromise(:335).session-manager.ts:402-408: the init still in flight then runsthis.browser = browser; this.stagehand = stagehand; this.context = ...afterclose()returned. Nothing checks that the manager was closed in between.
After that the daemon has no socket or pid file, so browse stop, browse status and browse open --session <same> cannot see it. A new open starts a second daemon and a second browser.
Suggested fix
Count closes, and have initialize() drop its result if a close happened while it ran. The existing catch block already closes browser:
private consecutiveInitFailures = 0;
+ // Bumped by close() so an init that was still in flight cannot install its browser afterwards.
+ private closeGeneration = 0;
@@ async close(): Promise<void> {
const stagehand = this.stagehand;
const browser = this.browser;
+ this.closeGeneration += 1;
this.stagehand = null;
@@ private async initialize(): Promise<void> {
+ const generation = this.closeGeneration;
const resolvedTarget = await this.resolveTarget();
@@
const stagehand = await Stagehand.create({
browser,
logging: { level: "off" },
});
+ if (generation !== this.closeGeneration) {
+ await stagehand.close().catch(() => undefined);
+ throw new Error("Driver session closed while it was initializing.");
+ }
this.browser = browser;This keeps close() from waiting on a launch that may hang. With it, both the DriverSessionManager test and a runDriverDaemon socket test pass, the end-to-end browse daemon + headless Chrome run closes Chrome and exits cleanly with code 0, and the full packages/cli test suite (589 passed across 44 files) plus pnpm --filter browse lint (oxfmt, oxlint, tsc --noEmit) pass cleanly.
Related Issues
None found for close() racing an in-flight initialize(). #3434 (open) touches session-manager.ts for the browse doctor hint only; #3436 and #3480 (open) cover client-side daemon recovery.
Activity