Skip to content

Conversation

@RohitR311
Copy link
Contributor

@RohitR311 RohitR311 commented Jan 24, 2025

Closes: #374

Summary by CodeRabbit

  • New Features

    • Added tracking for robot run state in browser pool
    • Implemented middleware to prevent concurrent browser recording sessions
    • Enhanced socket communication for workflow interpretation completion
  • Bug Fixes

    • Improved handling of browser recording session management
    • Updated local storage management for run information
  • Refactor

    • Streamlined socket event handling in main page component
    • Improved browser pool state management

@coderabbitai
Copy link

coderabbitai bot commented Jan 24, 2025

Walkthrough

This pull request introduces enhancements to the browser management system, focusing on tracking robot run states across multiple components. The changes include adding an isRobotRun property to the BrowserPoolInfo interface, updating methods in the BrowserPool class to manage this new state, and modifying related components to support the new functionality. The modifications aim to provide better control and tracking of browser instances during robot runs, with improvements in route handling and socket event management.

Changes

File Change Summary
server/src/browser-management/classes/BrowserPool.ts - Added isRobotRun optional property to BrowserPoolInfo interface
- Updated addRemoteBrowser method to accept isRobotRun parameter
- Added hasActiveRobotRun() method to check for active robot runs
- Added clearRobotRunState() method to manage robot run state
server/src/browser-management/controller.ts - Modified addRemoteBrowser call to include true for isRobotRun parameter
server/src/routes/record.ts - Added middleware to check for active robot runs before initializing recording session
server/src/workflow-management/classes/Interpreter.ts - Added socket emission of run-completed event after interpretation
src/pages/MainPage.tsx - Updated socket event handling and local storage management for run information

Assessment against linked issues

Objective Addressed Explanation
Prevent remote browser opening on page reload [#374]

Possibly related PRs

Suggested labels

Type: Enhancement

Suggested reviewers

  • amhsirak

Poem

🐰 Hop, hop, through the browser's maze,
Tracking runs with robotic praise,
State management, a clever art,
Where each browser plays its part!
CodeRabbit's magic, clear and bright ✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 (9)
server/src/browser-management/classes/BrowserPool.ts (3)

18-19: Add documentation for the new isRobotRun property.
This helps future readers understand its purpose.

 interface BrowserPoolInfo {
     browser: RemoteBrowser,
     active: boolean,
+    /**
+     * Indicates whether the browser is part of a robot run.
+     */
     isRobotRun?: boolean;
 }

67-72: Consider logging a warning if the browser does not exist.
Currently, this.pool[id] is checked, but if the ID is invalid, no message is logged. This may be acceptable depending on your design, but if missing IDs are unexpected, a warning or error log could help identify issues.

 public clearRobotRunState(id: string): void {
     if (this.pool[id]) {
         this.pool[id].isRobotRun = false;
         logger.log('debug', `Robot run state cleared for browser ${id}`);
+    } else {
+        logger.log('warn', `No browser with id: ${id} found in the pool to clear robot run state.`);
     }
 }

84-85: Remove or justify the extra robot-run state clearing before deletion.
Clearing isRobotRun immediately before deletion may be unnecessary overhead if you have no side effects. If logging or side effects are intended, consider explaining it in a comment.

src/pages/MainPage.tsx (3)

71-78: Restore success notifications or confirm removal is intentional.
You’ve commented out the success/failure notifications, which might reduce user feedback. Consider reintroducing them or clarifying the user experience strategy.


93-98: Watch for potential sensitive data in localStorage.
Storing identifiers like browserId or runId is typically acceptable, but ensure no sensitive information is placed here without encryption.


108-118: Consider handling additional statuses beyond “success.”
The code checks only 'success', defaulting all other cases to an “error.” If more nuanced statuses exist (e.g., “partialSuccess”), handle them here for clarity.

server/src/routes/record.ts (3)

19-19: Consider restructuring the import to avoid potential circular dependencies.

Importing browserPool from '../server' could lead to circular dependencies. Consider moving the browserPool instance to a separate service file that both the server and routes can import from.


37-45: LGTM! Well-structured middleware implementation.

The middleware effectively prevents concurrent operations between recording and robot runs. The status code and error message are appropriate.

Consider adding error handling and request logging:

 router.use('/', requireSignIn, (req: AuthenticatedRequest, res: Response, next) => {
-    if (browserPool.hasActiveRobotRun()) {
+    try {
+        if (browserPool.hasActiveRobotRun()) {
+            logger.log('debug', `Denied browser initialization request from user ${req.user?.id} - robot run in progress`);
+            return res.status(403).json({
+                error: 'Cannot initialize recording browser while a robot run is in progress'
+            });
+        }
+        next();
+    } catch (error) {
+        logger.log('error', `Error checking robot run status: ${error}`);
+        return res.status(500).json({
+            error: 'Internal server error while checking robot run status'
+        });
+    }
-    }
-    next();
 });

46-47: Remove unnecessary empty line.

Consider removing one of the consecutive empty lines to maintain consistent spacing.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7b6788 and 102c72a.

📒 Files selected for processing (5)
  • server/src/browser-management/classes/BrowserPool.ts (3 hunks)
  • server/src/browser-management/controller.ts (1 hunks)
  • server/src/routes/record.ts (2 hunks)
  • server/src/workflow-management/classes/Interpreter.ts (1 hunks)
  • src/pages/MainPage.tsx (5 hunks)
🔇 Additional comments (6)
server/src/browser-management/classes/BrowserPool.ts (2)

51-57: Initialize isRobotRun consistently with the new parameter.
The addition of the isRobotRun parameter aligns well with your approach to manage state in the browser pool.


63-65: Efficiently check for a running robot.
Using .some() to detect any active robot run is a simple, concise solution.

server/src/browser-management/controller.ts (1)

62-62: Verify usage of the new isRobotRun parameter.
Passing true for both active and isRobotRun is logical. Ensure that downstream components handle the isRobotRun flag appropriately (e.g., preventing multiple runs, raising relevant events, etc.).

✅ Verification successful

isRobotRun parameter is properly implemented and handled
The BrowserPool implementation includes comprehensive robot run management with proper state tracking, prevention of multiple runs via hasActiveRobotRun(), and clean state management through clearRobotRunState(). The implementation aligns with the expected behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that references to `addRemoteBrowser` handle the new isRobotRun parameter correctly.
rg -A 5 'addRemoteBrowser'

Length of output: 1381


Script:

#!/bin/bash
# Search for robot-related code and multiple run prevention in BrowserPool
ast-grep --pattern 'class BrowserPool {
  $$$
  isRobotRun
  $$$
}'

# Search for robot-related event handlers and prevention logic
rg -i "robot.*run|prevent.*run|multiple.*run" server/src/browser-management/

# Look for usage of pool entries
rg "this\.pool\[.*\]" server/src/browser-management/

Length of output: 1859

src/pages/MainPage.tsx (2)

130-130: Unsubscribe from ‘run-completed’ event properly.
This call is correct. The removal helps prevent memory leaks when the component unmounts or re-renders.


145-186: Handle possible JSON parse errors and remove console logs in production.
Using JSON.parse on runInfo might fail if the data is invalid. Also, consider removing or guarding the console.log statement for production environments.

 useEffect(() => {
     const storedRunInfo = localStorage.getItem('runInfo');
-    console.log('storedRunInfo', storedRunInfo);
+    if (process.env.NODE_ENV !== 'production') {
+        console.log('storedRunInfo', storedRunInfo);
+    }

     if (storedRunInfo) {
        let runInfo;
        try {
+           runInfo = JSON.parse(storedRunInfo);
        } catch (e) {
+           notify('error', t('main_page.notifications.invalid_run_info'));
+           return;
        }
        ...
     }
 }, []);
✅ Verification successful

The review comment is valid and should be implemented as suggested.
The suggested changes improve error handling for JSON parsing and introduce proper production environment checks for logging. Consider applying similar patterns to other unguarded JSON.parse calls and console logs throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for JSON.parse usage
echo "=== JSON.parse patterns ==="
ast-grep --pattern 'JSON.parse($_)'

echo -e "\n=== Console.log patterns ==="
rg "console\.log\(" -A 1

echo -e "\n=== Environment checks ==="
rg "process\.env\.NODE_ENV"

Length of output: 19406

server/src/routes/record.ts (1)

37-45: Verify alignment with PR objective.

The changes prevent browser initialization during robot runs, but it's not clear how this addresses the PR objective of fixing browser reload functionality. Could you clarify how this middleware helps solve the issue where "Browser reload does not trigger remote browser to open"?

Let's verify the browser reload functionality:

Comment on lines +335 to +336
this.socket.emit('run-completed', "success");

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure failure cases also emit an appropriate run-completed status.
Currently, the code always emits "success". It may confuse the client if an error occurs. Consider handling failing or partial outcomes too.

 this.socket.emit('run-completed', "success");
+// Proposed example:
+// if (status === 'success') {
+//   this.socket.emit('run-completed', 'success');
+// } else {
+//   this.socket.emit('run-completed', 'error');
+// }

Committable suggestion skipped: line range outside the PR's diff.

@amhsirak amhsirak changed the title fix: Browser reload does not trigger remote browser to open fix: prevent page reload on run trigger to open remote browser Jan 24, 2025
@amhsirak amhsirak added the Type: Bug Something isn't working label Jan 24, 2025
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.

Bug: Page reload on run triggers remote browser to open

2 participants