Skip to content

Conversation

@shrey150
Copy link
Contributor

@shrey150 shrey150 commented Jan 5, 2026

Summary

  • Add handling for page close events to automatically update the active page when the current page closes
  • Add error handling for CDP operations to gracefully handle closed targets

Test plan

  • Verify multi-tab scenarios work correctly
  • Confirm page close events properly switch active page
  • Test that closed target errors are handled gracefully

🤖 Generated with Claude Code


Summary by cubic

Automatically switch the active page when the current tab closes and add targeted error handling to prevent crashes when CDP targets are closed. Improves multi-tab stability.

  • Bug Fixes
    • Switch active page to another open tab on Playwright page "close".
    • Register the close handler once; unregister frameId on close; skip work if a page is already closed.
    • Guard page creation/activation and CDP session/Page.enable calls; ignore known closed-target errors and rethrow others.

Written for commit 4eb04e3. Summary will update on new commits.

- Add handling for page close events to update active page when current page closes
- Add error handling for CDP operations on closed targets
- Remove unnecessary inline comments

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@changeset-bot
Copy link

changeset-bot bot commented Jan 5, 2026

⚠️ No Changeset found

Latest commit: 4eb04e3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@shrey150 shrey150 changed the title fix: handle page close events and avoid errors on closed targets [v2] fix: handle page close events and avoid errors on closed targets Jan 5, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="lib/StagehandContext.ts">

<violation number="1" location="lib/StagehandContext.ts:184">
P2: This close handler will be registered multiple times for the same page. The `handleNewPlaywrightPage` method is called twice per new page (directly and in the `finally` block of `init`), and `attachFrameNavigatedListener` also registers a close handler with similar logic. Consider adding a guard to prevent duplicate handler registration, or consolidating the close handling logic into one place.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Jan 5, 2026

Greptile Summary

Consolidated page close handling to prevent duplicate handlers and added automatic active page switching when tabs close. When the active page closes, the code now switches to another open tab. Added error guards for CDP operations to gracefully handle "Target closed" errors.

  • Fixed duplicate close handler registration by consolidating into handleNewPlaywrightPage with a guard check
  • Implemented active page switching logic when the current page closes
  • Added try-catch blocks around CDP session creation and Page.enable calls to silently handle closed target errors
  • Added isClosed() checks before CDP operations to prevent errors on already-closed pages

Confidence Score: 4/5

  • This PR is safe to merge with minimal risk
  • The changes improve multi-tab stability by properly handling page close events and CDP errors. The duplicate close handler issue from the previous thread has been addressed. One minor style suggestion was made to add an additional safety check when switching active pages.
  • No files require special attention

Important Files Changed

Filename Overview
lib/StagehandContext.ts Added page close handling to switch active page and error guards for CDP operations on closed targets. Consolidated duplicate close handlers into a single guarded registration.

Sequence Diagram

sequenceDiagram
    participant Context as StagehandContext
    participant PW as PlaywrightPage
    participant CDP as CDPSession
    participant Handler as Close Handler

    Note over Context,PW: New Page Creation Flow
    PW->>Context: page event fires
    Context->>Context: handleNewPlaywrightPage(pwPage)
    Context->>PW: isClosed() check
    
    alt Page not in pageMap
        Context->>Handler: Register close handler (once)
        Handler-->>Context: Handler registered
    end
    
    Context->>Context: createStagehandPage()
    Context->>Context: setActivePage()
    Context->>Context: attachFrameNavigatedListener()
    
    Note over Context,CDP: Attach CDP Listener Flow
    Context->>PW: isClosed() check
    Context->>CDP: newCDPSession(pwPage)
    
    alt Target closed error
        CDP-->>Context: Error (Target closed)
        Context->>Context: Catch and return silently
    else Success
        CDP-->>Context: Session created
        Context->>CDP: session.send("Page.enable")
        CDP->>CDP: Listen for Page.frameNavigated
    end
    
    Note over Handler,Context: Page Close Flow
    PW->>Handler: close event fires
    Handler->>Context: Get shPage from pageMap
    Handler->>Context: unregisterFrameId(shPage.frameId)
    
    alt Closed page is active
        Handler->>Context: Iterate through pages()
        Handler->>Context: Find first non-closed page
        Handler->>Context: setActivePage(foundPage)
    end
Loading

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

@shrey150
Copy link
Contributor Author

shrey150 commented Jan 5, 2026

@greptileai

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +191 to +197
for (const p of this.intContext.pages()) {
const sp = this.pageMap.get(p);
if (sp && sp !== shPage) {
this.setActivePage(sp);
break;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

style: check that candidate page p is not closed before setting as active

Suggested change
for (const p of this.intContext.pages()) {
const sp = this.pageMap.get(p);
if (sp && sp !== shPage) {
this.setActivePage(sp);
break;
}
}
for (const p of this.intContext.pages()) {
if (!p.isClosed()) {
const sp = this.pageMap.get(p);
if (sp && sp !== shPage) {
this.setActivePage(sp);
break;
}
}
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/StagehandContext.ts
Line: 191:197

Comment:
**style:** check that candidate page `p` is not closed before setting as active

```suggestion
            for (const p of this.intContext.pages()) {
              if (!p.isClosed()) {
                const sp = this.pageMap.get(p);
                if (sp && sp !== shPage) {
                  this.setActivePage(sp);
                  break;
                }
              }
            }
```

How can I resolve this? If you propose a fix, please make it concise.

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.

2 participants