Skip to content

Avoid native side effects during computer-server imports - #1569

Closed
0xjohnnydev wants to merge 2 commits into
chore/python-import-format-baselinefrom
fix/computer-server-import-safety
Closed

Avoid native side effects during computer-server imports#1569
0xjohnnydev wants to merge 2 commits into
chore/python-import-format-baselinefrom
fix/computer-server-import-safety

Conversation

@0xjohnnydev

@0xjohnnydev 0xjohnnydev commented May 18, 2026

Copy link
Copy Markdown
Contributor

Summary

  • lazy-export Server from computer_server instead of importing server code at package import time
  • move OS-specific handler imports into HandlerFactory.create_handlers()
  • remove macOS accessibility and screen-recording probes from module import
  • add subprocess import-safety coverage

Testing

  • cd libs/python/computer-server && uv run --frozen --with pytest --with pytest-asyncio pytest tests/test_import_safety.py

Summary by CodeRabbit

  • Refactor

    • Optimized module initialization to improve application startup performance across platforms
  • Tests

    • Added comprehensive import safety verification to ensure clean initialization

Review Change Stack

@vercel

vercel Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
docs Ignored Ignored Preview May 18, 2026 7:03pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

📦 Publishable packages changed

  • pypi/computer-server

Add release:<service> labels to auto-release on merge (+ optional bump:minor or bump:major, default is patch).
Or add no-release to skip.

@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto incremental reviews are disabled on this repository.

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.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d4416e98-7381-4c66-af10-e6a735080d97

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR defers module imports and removes initialization side effects across the Python computer server package. Package-level Server export becomes lazy via __getattr__. Handler factory moves OS-specific imports into scoped branches of create_handlers(). macOS handler removes permission-prompting code at import time. New tests verify import safety via subprocess isolation.

Changes

Lazy Loading and Import Safety

Layer / File(s) Summary
Package-level lazy export of Server
libs/python/computer-server/computer_server/__init__.py
Package now exposes Server via module-level __getattr__ instead of eagerly importing it, deferring the import until Server is actually accessed.
Handler factory lazy OS-specific imports
libs/python/computer-server/computer_server/handlers/factory.py
Handler factory moves OS-specific handler imports from module-level conditional blocks into branch-scoped imports within create_handlers(), deferring them until handler creation is called.
macOS handler side-effect cleanup
libs/python/computer-server/computer_server/handlers/macos.py
macOS handler module-level code that triggered permission prompts is removed; PIL imports are moved to module level for use by existing screenshot methods.
Import safety verification tests
libs/python/computer-server/tests/test_import_safety.py
New subprocess-based test module verifies that importing the package and handler modules completes cleanly without side effects, including macOS-specific handler creation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Imports lazy, side effects gone,
Permission prompts no longer call at dawn,
Tests subprocess-safe, clean and bright,
Loading deferred for the perfect flight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: avoiding native side effects during imports by implementing lazy loading patterns and removing permission-triggering code.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/computer-server-import-safety

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@sentry

sentry Bot commented May 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.86207% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...omputer-server/computer_server/handlers/factory.py 20.00% 4 Missing ⚠️
...python/computer-server/computer_server/__init__.py 60.00% 2 Missing ⚠️
...python/computer-server/tests/test_import_safety.py 94.73% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@libs/python/computer-server/tests/test_import_safety.py`:
- Around line 1-14: The test helper _assert_import_exits_cleanly inherits the
parent environment causing pre-set CUA_* variables to affect imports; fix it by
creating a sanitized env for subprocess.run (import os), e.g. copy os.environ
then remove any keys that start with "CUA_" (or explicitly pop "CUA_BACKEND" and
"CUA_VNC_*"), and pass that filtered env via the env= parameter to
subprocess.run so the child process runs in an isolated environment.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e833ae39-e356-415e-b820-1697b9b8357e

📥 Commits

Reviewing files that changed from the base of the PR and between 0f834c6 and f61570b.

📒 Files selected for processing (4)
  • libs/python/computer-server/computer_server/__init__.py
  • libs/python/computer-server/computer_server/handlers/factory.py
  • libs/python/computer-server/computer_server/handlers/macos.py
  • libs/python/computer-server/tests/test_import_safety.py

Comment on lines +1 to +14
import platform
import subprocess
import sys

import pytest


def _assert_import_exits_cleanly(import_statement: str):
result = subprocess.run(
[sys.executable, "-X", "faulthandler", "-c", f"{import_statement}; print('ok')"],
capture_output=True,
text=True,
timeout=20,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Isolate subprocess env to prevent flaky import-safety tests.

Line 9 currently inherits the parent environment, so pre-set CUA_BACKEND / CUA_VNC_* can alter HandlerFactory.create_handlers() and fail this test for non-import-safety reasons.

🔧 Suggested fix
+import os
 import platform
 import subprocess
 import sys
@@
 def _assert_import_exits_cleanly(import_statement: str):
+    env = os.environ.copy()
+    for key in ("CUA_BACKEND", "CUA_VNC_HOST", "CUA_VNC_PORT", "CUA_VNC_PASSWORD"):
+        env.pop(key, None)
+
     result = subprocess.run(
         [sys.executable, "-X", "faulthandler", "-c", f"{import_statement}; print('ok')"],
         capture_output=True,
         text=True,
         timeout=20,
+        env=env,
     )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/python/computer-server/tests/test_import_safety.py` around lines 1 - 14,
The test helper _assert_import_exits_cleanly inherits the parent environment
causing pre-set CUA_* variables to affect imports; fix it by creating a
sanitized env for subprocess.run (import os), e.g. copy os.environ then remove
any keys that start with "CUA_" (or explicitly pop "CUA_BACKEND" and
"CUA_VNC_*"), and pass that filtered env via the env= parameter to
subprocess.run so the child process runs in an isolated environment.

@github-actions

Copy link
Copy Markdown
Contributor

📦 Publishable packages changed

  • pypi/computer-server

Add release:<service> labels to auto-release on merge (+ optional bump:minor or bump:major, default is patch).
Or add no-release to skip.

@0xjohnnydev
0xjohnnydev changed the base branch from main to chore/python-import-format-baseline May 18, 2026 18:58
@0xjohnnydev
0xjohnnydev force-pushed the fix/computer-server-import-safety branch from 8c0c94b to 583ea92 Compare May 18, 2026 19:02
@github-actions

Copy link
Copy Markdown
Contributor

📦 Publishable packages changed

  • pypi/computer-server

Add release:<service> labels to auto-release on merge (+ optional bump:minor or bump:major, default is patch).
Or add no-release to skip.

@0xjohnnydev

Copy link
Copy Markdown
Contributor Author

Closing this for now to keep the current review queue focused on Dependabot remediation. The branch and commits are being preserved so this code-security work can be reopened or superseded when we return to that backlog.

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.

1 participant