Skip to content

Conversation

@amhsirak
Copy link
Member

@amhsirak amhsirak commented Aug 21, 2025

closes #740 #739 #

Summary by CodeRabbit

  • Bug Fixes

    • Improved stability when a browser page closes mid-action: click/text input and selector-related queries now detect closed pages, return safe fallbacks, and avoid errors or hangs during automated workflows.
  • Chores

    • Minor formatting cleanup (trailing newline) with no user-visible impact.

@amhsirak amhsirak marked this pull request as draft August 21, 2025 14:55
@coderabbitai
Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

Add defensive guards that check Playwright page.isClosed() before running page.evaluate in click/cursor and selector-related flows; when closed, functions log a debug message and return safe fallbacks. No public API or signature changes.

Changes

Cohort / File(s) Summary
OnClick guard for closed page
server/src/workflow-management/classes/Generator.ts
Added page.isClosed() check in onClick flow for INPUT/TEXTAREA before page.evaluate; logs debug and returns early if closed. Minor EOF newline formatting.
Selector guards for closed page
server/src/workflow-management/selector.ts
Added page.isClosed() guards and debug logs across selector functions (getElementInformation, getRect, getSelectors, getNonUniqueSelectors, getChildSelectors) to return safe fallbacks (e.g., null, [], { generalSelector: '' }) when page is closed. No signature changes.

Sequence Diagram(s)

sequenceDiagram
    participant U as User Action
    participant G as Generator.onClick
    participant P as Playwright Page

    U->>G: onClick(INPUT/TEXTAREA, selector)
    G->>P: Check page.isClosed()
    alt Page is closed
        note right of G: Debug log and safe return
        G-->>U: Return early (skip page.evaluate)
    else Page open
        G->>P: page.evaluate(...) to compute cursor position
        P-->>G: Cursor position
        G-->>U: Continue onClick flow
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Handle page context destroyed on navigation (#740) — avoid evaluating on closed page and return safely

Possibly related PRs

Suggested labels

Priority: High

Suggested reviewers

  • RohitR311

Poem

"I’m a rabbit who checks the door,
If the page is closed I check no more.
I log a note, I skip the dive,
Safe returns keep the app alive.
Hops and fixes — quiet cheer!" 🥕

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch recorder-fix

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@amhsirak amhsirak added Type: Bug Something isn't working Scope: Recorder All issues/PRs related to recorder labels Aug 21, 2025
@amhsirak amhsirak marked this pull request as ready for review August 21, 2025 17:13
@amhsirak amhsirak requested a review from RohitR311 August 21, 2025 17:13
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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/src/workflow-management/selector.ts (1)

1987-1991: Boolean bug: overlay check is effectively always true

The condition uses negation with != null in a way that always evaluates to true when hoveredElement is non-null, ignoring overlay-controls. This can produce incorrect selector generation.

-      if (
-        hoveredElement != null &&
-        !hoveredElement.closest('#overlay-controls') != null
-      ) {
+      if (
+        hoveredElement != null &&
+        hoveredElement.closest('#overlay-controls') == null
+      ) {
🧹 Nitpick comments (7)
server/src/workflow-management/selector.ts (7)

24-27: Good defensive guard before page.evaluate; confirm return-type consistency

This prevents the crash on navigations. Minor: this branch returns null, while the JSDoc above says undefined when not found. Consider standardizing on a single sentinel (null) across codepaths and updating the doc to match.


309-312: Unify debug message wording (drop “else branch”)

Message suffix “(else branch)” is noisy and leaks control-flow details. Prefer a consistent message across branches.

- logger.debug('Page is closed, cannot get element information (else branch)');
+ logger.debug('Page is closed, cannot get element information');

849-852: Mirror guard reads well; keep behavior symmetrical across branches

LGTM. Same note as above about consistent logging copy if you decide to deduplicate messages.


8-15: Docs say “undefined” but code now returns “null” in several paths

Update the return annotation to include null (and ideally remove undefined to keep one sentinel), or adapt code to consistently return undefined. I recommend null for explicitness.

Proposed doc tweak:

/**
 * Checks the basic info about an element and returns a BaseActionInfo object.
 * If the element is not found, returns null.
 * ...
 * @returns {Promise<BaseActionInfo|null>}
 */

613-616: Standardize error logging (console.error vs logger)

Elsewhere you use logger.log('error', ...). Consider switching these console.error calls to logger for uniformity and better transport/filtering.

-    console.error('Error while retrieving selector:', message);
-    console.error('Stack:', stack);
+    logger.log('error', `Error while retrieving selector: ${message}`);
+    logger.log('error', `Stack: ${stack}`);

24-27: Consider a tiny “guardPageOpen” to DRY up repeated checks

You’ve added six identical guards; factoring them reduces duplication and mis-message drift.

Example utility (can live near top of this module):

function guardPageOpen(page: Page, debugMsg: string): boolean {
  if (page.isClosed()) {
    logger.debug(debugMsg);
    return true;
  }
  return false;
}

Usage:

if (guardPageOpen(page, 'Page is closed, cannot get element information')) return null;
// ...
if (guardPageOpen(page, 'Page is closed, cannot get element rect')) return null;

Also applies to: 309-312, 622-625, 849-852, 1095-1098, 2033-2036, 2391-2394, 2756-2759


1095-1098: Action: Integrate safeEvaluate and Replace Direct page.evaluate Calls

We verified that there are no strict undefined comparisons nor unsafe property accesses on potentially null selector results. However, direct calls to page.evaluate remain throughout the codebase and should be refactored to use the new safeEvaluate helper to gracefully handle “Execution context was destroyed” and related errors.

Key locations to update:

  • server/src/workflow-management/classes/Generator.ts
    • Line 548: const positionAndCursor = await page.evaluate(...)
  • server/src/workflow-management/selector.ts
    • Line 28, 313, 626, 853, 1098: initial elementInfo, rect, and selectors evaluations
    • Line 2037, 2395, 2760: additional selector and child-selectors evaluations
  • server/src/browser-management/classes/RemoteBrowser.ts
    • Line 487: injectable script injection via page.evaluate(getInjectableScript())
    • Line 712: list-selector/fields evaluation with page.evaluate(...)

For each of these, wrap the existing page.evaluate call in safeEvaluate(page, fn, arg, debugMsg) so that transient navigation or context-teardown errors are downgraded to a debug log and return null instead of bubbling up. This centralizes error handling, reduces noise, and preserves existing control flow (null checks already in place).

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 93a644b and 1eea629.

📒 Files selected for processing (1)
  • server/src/workflow-management/selector.ts (8 hunks)
🔇 Additional comments (4)
server/src/workflow-management/selector.ts (4)

622-625: Solid guard to avoid rect-evaluate on closed page

This is aligned with the PR objective and should eliminate a common crash path.


2033-2036: Non-unique selectors: safe fallback on closed page is appropriate

Returning a stable object shape with empty generalSelector is a good choice. Ensure downstream code treats both null (evaluate returning null) and { generalSelector: '' } equivalently as “not found.”


2391-2394: List branch guard mirrors non-list branch; LGTM

Consistent behavior across both branches. Same downstream handling note as above.


2756-2759: Child selectors: early bail-out is correct

Returning [] on a closed page aligns with callers expecting an array. Good choice.

@amhsirak amhsirak removed the request for review from RohitR311 August 25, 2025 14:04
@amhsirak amhsirak merged commit ae28802 into develop Aug 25, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Recorder All issues/PRs related to recorder Type: Bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Page context destroyed on navigation (some sites)

2 participants