ClioMonitor
The ClioMonitor class is the main interface for monitoring Playwright automation runs. It handles automatic video and trace capture, upload management, and integration with the Clio platform.
Constructor
Section titled “Constructor”ClioMonitor(api_key, **kwargs)
Section titled “ClioMonitor(api_key, **kwargs)”Creates a new ClioMonitor instance.
from clio import ClioMonitor
monitor = ClioMonitor( api_key="clio_your_api_key", base_url="https://api.cliomonitoring.com", retry_attempts=3, raise_on_error=False, verify_ssl=True)Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | Required | Your Clio API key (must start with clio_) |
base_url | str | "https://api.cliomonitoring.com" | The Clio API server URL |
retry_attempts | int | 3 | Number of retry attempts for failed uploads |
raise_on_error | bool | False | Whether to raise exceptions on errors |
verify_ssl | bool | True | Whether to verify SSL certificates |
Raises
Section titled “Raises”ValueError- If the API key is empty or doesn’t start withclio_ValueError- If thebase_urlhas an invalid formatSecurityWarning- If using HTTP with non-localhost URLs
Example
Section titled “Example”# Basic usagemonitor = ClioMonitor(api_key="clio_abc123...")
# Development configurationmonitor = ClioMonitor( api_key="clio_abc123...", base_url="http://localhost:8000", raise_on_error=True # Get detailed errors)
# Production configurationmonitor = ClioMonitor( api_key="clio_abc123...", retry_attempts=5, verify_ssl=True)Methods
Section titled “Methods”async start_run(context, automation_name, **kwargs)
Section titled “async start_run(context, automation_name, **kwargs)”Starts monitoring a Playwright automation run. This method automatically:
- Enables trace capture on the context
- Detects video recording configuration
- Sets up automatic upload when the context closes
- Creates a run record in your Clio organization
await monitor.start_run( context=context, automation_name="Login Flow Test", success_criteria="User successfully authenticates", playwright_instructions="Navigate to login, enter credentials, verify dashboard")Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
context | PlaywrightContext | Required | The Playwright browser context to monitor |
automation_name | str | Required | Human-readable name for this automation run |
success_criteria | str | None | Optional description of what defines success |
playwright_instructions | str | None | Optional step-by-step instructions for the automation |
Behavior
Section titled “Behavior”When you call start_run(), the SDK:
- Validates the context - Ensures it’s a valid Playwright context
- Creates a run record - Registers the run with your Clio organization
- Gets upload URLs - Retrieves secure, presigned S3 URLs for file uploads
- Enables tracing - Automatically starts Playwright tracing with screenshots and snapshots
- Detects video configuration - Finds the
record_video_dirfrom context options - Patches context.close() - Monkey-patches the close method to trigger uploads
Thread Safety
Section titled “Thread Safety”The method is thread-safe and uses internal locks to prevent race conditions when monitoring multiple contexts simultaneously.
Error Handling
Section titled “Error Handling”- Validates API key format and server connectivity
- Handles authentication errors (401) and rate limits (429)
- Masks sensitive data in all error messages
- Gracefully handles contexts that are already being monitored
Example
Section titled “Example”async with async_playwright() as p: browser = await p.chromium.launch() context = await browser.new_context( record_video_dir="./recordings", record_video_size={"width": 1920, "height": 1080} )
# Start monitoring await monitor.start_run( context=context, automation_name="E2E Checkout Flow", success_criteria="Order placed successfully with confirmation email", playwright_instructions=""" 1. Navigate to product page 2. Add item to cart 3. Proceed to checkout 4. Fill shipping information 5. Complete payment 6. Verify confirmation page """ )
# Your automation code here... page = await context.new_page() # ... test steps ...
# Upload happens automatically await context.close()Automatic Upload Process
Section titled “Automatic Upload Process”When the monitored context closes, the SDK automatically:
- Stops tracing - Saves the trace file to a secure temporary location
- Finds video files - Locates the most recent video in the recording directory
- Uploads concurrently - Streams both video and trace files to S3 simultaneously
- Progress tracking - Logs upload progress for large files (>10MB use streaming)
- Retry logic - Retries failed uploads with exponential backoff
- Cleanup - Removes temporary trace files after successful upload
- Notifies completion - Tells the Clio server that files are ready for processing
Internal Methods
Section titled “Internal Methods”These methods are used internally by the SDK and typically don’t need to be called directly:
async _handle_upload(context)
Section titled “async _handle_upload(context)”Handles the actual file upload process after a context closes. This method is called automatically.
_cleanup_temp_files()
Section titled “_cleanup_temp_files()”Cleans up temporary trace files. Called automatically on process exit.
Properties
Section titled “Properties”config
Section titled “config”Access to the underlying Config object with masked sensitive data:
monitor = ClioMonitor(api_key="clio_secret123")print(monitor.config) # Config(api_key='clio_****', base_url='https://api.cliomonitoring.com', ...)uploader
Section titled “uploader”Access to the internal Uploader instance (advanced usage only).
Error Handling
Section titled “Error Handling”The ClioMonitor class handles errors gracefully:
# Silent mode (default) - logs errors but continuesmonitor = ClioMonitor(api_key="clio_abc123", raise_on_error=False)
# Development mode - raises exceptions for debuggingmonitor = ClioMonitor(api_key="clio_abc123", raise_on_error=True)Common exceptions:
ClioAuthError- Invalid API key or authentication failureClioRateLimitError- Monthly rate limit exceededClioUploadError- File upload failuresClioError- General API or network errors
Security Features
Section titled “Security Features”- API key masking - Sensitive data never appears in logs or error messages
- SSL verification - Enabled by default, configurable for development
- Secure uploads - Uses presigned S3 URLs for direct-to-storage uploads
- Collision detection - Prevents multiple monitors on the same context
- Clean exit handling - Ensures temporary files are cleaned up
Performance Considerations
Section titled “Performance Considerations”- Streaming uploads - Files larger than 10MB are streamed to prevent memory issues
- Concurrent uploads - Video and trace files upload simultaneously
- Dynamic timeouts - Upload timeouts scale with file size (minimum 30s, maximum 10 minutes)
- Connection pooling - Reuses HTTP connections for efficiency
- WeakKeyDictionary - Automatic cleanup when contexts are garbage collected
Thread Safety
Section titled “Thread Safety”The ClioMonitor class is designed for concurrent use:
monitor = ClioMonitor(api_key="clio_abc123")
# Safe to use the same monitor instance across multiple contextsasync def test_scenario_1(): context1 = await browser.new_context(record_video_dir="./videos1") await monitor.start_run(context1, "Scenario 1") # ... test code ... await context1.close()
async def test_scenario_2(): context2 = await browser.new_context(record_video_dir="./videos2") await monitor.start_run(context2, "Scenario 2") # ... test code ... await context2.close()
# Run concurrentlyawait asyncio.gather(test_scenario_1(), test_scenario_2())Internal locks ensure thread-safe access to shared resources.
Best Practices
Section titled “Best Practices”- Reuse monitor instances - Create one
ClioMonitorper API key/configuration - Enable video recording - The SDK requires Playwright’s
record_video_dir - Use descriptive names - Automation names help identify runs in the dashboard
- Handle errors appropriately - Use
raise_on_error=Trueduring development - Set success criteria - Help the AI analysis understand what success looks like
- Use environment variables - Store API keys securely outside your code