Skip to content

Commit f0c162a

Browse files
end BB session on exit (#534)
* end BB session on exit * cahngeset
1 parent f7d6aad commit f0c162a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Diff for: .changeset/ninety-scissors-study.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@browserbasehq/stagehand": patch
3+
---
4+
5+
call this.end() if the process exists

Diff for: lib/index.ts

+25
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,7 @@ export class Stagehand {
377377
private waitForCaptchaSolves: boolean;
378378
private localBrowserLaunchOptions?: LocalBrowserLaunchOptions;
379379
public readonly selfHeal: boolean;
380+
private cleanupCalled = false;
380381

381382
constructor(
382383
{
@@ -449,6 +450,30 @@ export class Stagehand {
449450

450451
this.selfHeal = selfHeal;
451452
this.localBrowserLaunchOptions = localBrowserLaunchOptions;
453+
454+
if (this.usingAPI) {
455+
this.registerSignalHandlers();
456+
}
457+
}
458+
459+
private registerSignalHandlers() {
460+
const cleanup = async (signal: string) => {
461+
if (this.cleanupCalled) return;
462+
this.cleanupCalled = true;
463+
464+
console.log(`[${signal}] received. Ending Browserbase session...`);
465+
try {
466+
await this.close();
467+
} catch (err) {
468+
console.error("Error ending Browserbase session:", err);
469+
} finally {
470+
// Exit explicitly once cleanup is done
471+
process.exit(0);
472+
}
473+
};
474+
475+
process.once("SIGINT", () => void cleanup("SIGINT"));
476+
process.once("SIGTERM", () => void cleanup("SIGTERM"));
452477
}
453478

454479
public get logger(): (logLine: LogLine) => void {

0 commit comments

Comments
 (0)