Skip to content

fix: handling unexpected browser context closed error #498

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2025
Merged

Conversation

RohitR311
Copy link
Collaborator

@RohitR311 RohitR311 commented Mar 24, 2025

Closes: #492

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced the browser launch process by adding automatic retries and timeout controls. These improvements reduce startup issues and ensure a smoother, more reliable experience when initiating browser sessions.

@RohitR311 RohitR311 requested a review from amhsirak March 24, 2025 10:53
Copy link

coderabbitai bot commented Mar 24, 2025

Walkthrough

The update modifies the RemoteBrowser.initialize method to implement a retry mechanism for launching the browser, allowing up to three attempts. It wraps the context creation in a promise race with a 15-second timeout. Enhanced error logging is introduced, and the browser is closed if an error occurs during initialization. The proxy configuration and context options remain unchanged.

Changes

File(s) Change Summary
server/src/browser-management/.../RemoteBrowser.ts Modified the initialize method to add a retry mechanism (3 attempts) for launching the browser, integrate a 15-second timeout for context creation, and enhance error logging and resource cleanup.

Sequence Diagram(s)

sequenceDiagram
    participant RB as RemoteBrowser
    participant B as Browser
    participant C as Context
    participant L as Logger

    RB->>B: Attempt to launch browser (Attempt 1)
    alt Launch successful
        RB->>C: Initiate context creation (with 15s timeout)
        alt Context creation successful
            RB->>L: Log success and return browser/context
        else Timeout/Error
            RB->>L: Log context error and close browser
            Note over RB,B: Retry if attempt count < 3
        end
    else Launch failed
        RB->>L: Log launch failure and wait briefly
        Note over RB,B: Retry if attempt count < 3
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
browser.newContext: Target page, context or browser has been closed (#492)

Possibly related PRs

Suggested labels

Type: Bug

Suggested reviewers

  • amhsirak

Poem

I'm a bunny hopping down the code lane,
Where retries bloom like springtime rain.
Each error logged, each bug set free,
In robust flows, our browser sings with glee.
With a twitch of my nose, I cheer—code done perfectly!
🐰✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between 0c079e8 and 17eed12.

📒 Files selected for processing (1)
  • server/src/browser-management/classes/RemoteBrowser.ts (1 hunks)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
server/src/browser-management/classes/RemoteBrowser.ts (3)

248-251: Consider adding an exponential backoff to retry mechanism.
This would help spread out retry attempts, especially in scenarios where the environment might temporarily be under high load. Currently, the short, fixed 1-second delay might be insufficient or overly aggressive in some edge cases.

-  await new Promise(resolve => setTimeout(resolve, 1000));
+  const backoffDelay = Math.pow(2, retryCount) * 1000; // exponential backoff
+  await new Promise(resolve => setTimeout(resolve, backoffDelay));

303-321: Make the 15-second timeout configurable.
A hardcoded 15s timeout may cause issues in slower network or resource-constrained environments. By allowing a configurable timeout, you can better accommodate various runtime conditions.


322-345: Review the WebDriver patch script for ongoing maintenance.
Embedding a multi-line script is effective but can be brittle if browser APIs change. Consider isolating this logic in a separate function or file, with accompanying tests or documentation, to simplify maintenance and future updates.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c079e8 and 17eed12.

📒 Files selected for processing (1)
  • server/src/browser-management/classes/RemoteBrowser.ts (1 hunks)
🔇 Additional comments (1)
server/src/browser-management/classes/RemoteBrowser.ts (1)

252-272: Ensure concurrency safety for browser initialization.
If initialize can be called while another initialization is in progress, there could be concurrency issues (e.g., multiple browsers launching simultaneously). Consider adding a lock or a guard to prevent concurrent initialize calls on the same instance.

Comment on lines +374 to +391
retryCount++;
logger.log('error', `Browser initialization failed (attempt ${retryCount}/${MAX_RETRIES}): ${error.message}`);

if (this.browser) {
try {
await this.browser.close();
} catch (closeError) {
logger.log('warn', `Failed to close browser during cleanup: ${closeError}`);
}
this.browser = null;
}

if (retryCount >= MAX_RETRIES) {
throw new Error(`Failed to initialize browser after ${MAX_RETRIES} attempts: ${error.message}`);
}

await new Promise(resolve => setTimeout(resolve, 1000));
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve cleanup logic in the catch block.
When cleaning up after a failed attempt, ensure that partial initializations (e.g., a context that started to initialize) are also explicitly closed if needed. Currently, only the browser is gracefully closed. If a browser context was partially created and left behind, it might lead to resource leaks.

@amhsirak amhsirak added Type: Bug Something isn't working Status: 🚫🚫 DO NOT MERGE 🚫🚫 Don't merge this PR. It is not perfect. and removed Status: 🚫🚫 DO NOT MERGE 🚫🚫 Don't merge this PR. It is not perfect. labels Mar 24, 2025
@amhsirak amhsirak merged commit 474a3da into develop Mar 27, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

browser.newContext: Target page, context or browser has been closed
2 participants