8000 fix(browser_profiler): cross-platform 'q' to quit - create profile by prokopis3 · Pull Request #1170 · unclecode/crawl4ai · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix(browser_profiler): cross-platform 'q' to quit - create profile #1170

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

Open
wants to merge 3 commits into
base: 2025-MAY-2
Choose a base branch
from

Conversation

prokopis3
Copy link
@prokopis3 prokopis3 commented May 30, 2025

Summary

This PR implements cross-platform keyboard input handling for the browser profiler's quit command, addressing platform compatibility issues between Windows and Unix-like systems.

  • Implemented msvcrt for Windows to capture keyboard input without requiring a newline.
  • Retained termios, tty, and select for Unix-like systems.
  • Added a check for browser process termination to gracefully exit the input listener.
  • Updated logger messages to use colored output for better user experience.

Fixes #1166

List of files changed and why

  • browser_profiler.py
    • Added platform-specific keyboard input handling using msvcrt for Windows
    • Retained termios, tty, and select for Unix systems
    • Implemented browser process exit detection
    • Enhanced logging with colored output

How Has This Been Tested?

Please describe the tests that you ran to verify your changes.

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • I have added/updated unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • Refactor
    • Improved cross-platform compatibility for keyboard input handling, ensuring smoother experience on both Windows and Unix-like systems.
    • Enhanced prompt messages with clearer instructions and color highlighting for key commands.
    • Improved reliability by ensuring proper restoration of terminal settings and early termination if the browser process exits.

This commit introduces platform-specific handling for the 'q' key press to quit the browser profiler, ensuring compatibility with both Windows and Unix-like systems. It also adds a check to see if the browser process has already exited, terminating the input listener if so.

- Implemented `msvcrt` for Windows to capture keyboard input without requiring a newline.
- Retained `termios`, `tty`, and `select` for Unix-like systems.
- Added a check for browser process termination to gracefully exit the input listener.
- Updated logger messages to use colored output for better user experience.
Copy link
coderabbitai bot commented May 30, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The code refactors the asynchronous keyboard input listener in crawl4ai/browser_profiler.py for cross-platform compatibility. It introduces platform-specific handling for Windows using msvcrt, retains the Unix approach, and ensures terminal settings are restored. Prompt messages are enhanced, and a helper checks browser process status within the input loop.

Changes

File(s) Change Summary
crawl4ai/browser_profiler.py Refactored async keyboard listener for cross-platform support; added Windows handling with msvcrt, improved Unix terminal restoration, enhanced prompts, and added browser process check in input loop.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Listener (Unix/Win)
    participant BrowserProcess

    Note over Listener (Unix/Win): Start async input listener
    loop Until 'q' pressed or browser exits
        Listener (Unix/Win) -> Listener (Unix/Win): Check for keypress ('q')
        Listener (Unix/Win) -> BrowserProcess: Check if browser exited
        BrowserProcess --> Listener (Unix/Win): Browser running/exited
        alt 'q' pressed or browser exited
            Listener (Unix/Win) -> Listener (Unix/Win): Exit input loop
        end
    end
    Listener (Unix/Win) -> Listener (Unix/Win): Cleanup (restore terminal if Unix)
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure listen_for_quit_command works on both Unix and Windows systems (#1166)
Remove reliance on Unix-specific libraries for Windows compatibility (#1166)
Properly restore terminal settings on Unix after input listening (#1166)

Poem

A rabbit hopped from Unix to Win,
Making keypresses work with a grin.
No more platform fuss,
Just press 'q'—no muss!
Now browsers and bunnies can both begin.
🐇✨


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@prokopis3 prokopis3 changed the base branch from 2025-MAY-2 to main June 6, 2025 09:00
@prokopis3 prokopis3 changed the base branch from main to 2025-JUN-1 June 6, 2025 09:02
@prokopis3 prokopis3 changed the base branch from 2025-JUN-1 to 2025-MAY-2 June 6, 2025 09:02
@ntohidi
Copy link
Collaborator
ntohidi commented Jun 12, 2025

@coderabbitai review

Copy link
coderabbitai bot commented Jun 12, 2025
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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 (2)
crawl4ai/browser_profiler.py (2)

240-257: Avoid blocking the event loop with select.select in tight async loops

select.select(..., timeout=0.5) blocks the entire asyncio event loop for up to half a second on every iteration, affecting concurrent tasks (e.g., network I/O in the crawler).

Consider running the blocking stdin poll in a background thread:

loop = asyncio.get_running_loop()
key = await loop.run_in_executor(None, sys.stdin.read, 1)

or off-loading the whole listener with asyncio.to_thread.

This keeps the main loop responsive without sacrificing portability.

Also applies to: 738-749


183-224: DRY: extract the nearly identical quit listeners into a reusable helper

The two listen_for_quit_command coroutines are almost identical (only log tags differ). Duplicating ~90 lines inflates maintenance cost and risks future divergence.

Refactor into one parametric helper, e.g.:

async def _await_quit_or_exit(
    tag: str,
    logger: AsyncLoggerBase,
    browser_proc: subprocess.Popen,
    done_evt: asyncio.Event,
):
    ...

Both call-sites can then await _await_quit_or_exit("PROFILE", self.logger, browser_process, user_done_event).

Also applies to: 695-726

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28125c1 and 4bcb717.

📒 Files selected for processing (1)
  • crawl4ai/browser_profiler.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
crawl4ai/browser_profiler.py (1)
crawl4ai/async_logger.py (4)
  • info (55-56)
  • info (236-238)
  • info (349-351)
  • LogColor (29-46)

@prokopis3
Copy link
Author

@ntohidi Would you like us to go ahead and make these changes? I can prep the update if you're good with it.

@ntohidi
Copy link
Collaborator
ntohidi commented Jun 12, 2025

@ntohidi Would you like us to go ahead and make these changes? I can prep the update if you're good with it.

@prokopis3 I believe it's worthwhile to consider this. Please proceed.

- fix handling of special keys in Windows msvcrt implementation
- Guard against UnicodeDecodeError from multi-byte key sequences
- Filter out non-printable characters and control sequences
- Add error handling to prevent coroutine crashes
- Add unit test to verify keyboard input handling

Key changes:
- Safe UTF-8 decoding with try/except for special keys
- Skip non-printable and multi-byte character sequences
- Add broad exception handling in keyboard listener

Test runs on Windows only due to msvcrt dependency.
…st_create_profile.py )

- Rename file to correct spelling
- No content changes
@prokopis3
Copy link
Author

@ntohidi done!

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
0