When to Use WebSocket vs REST
Use WebSocket When:
- You need live agent thoughts and reasoning as tasks execute
- Building real-time dashboards or interactive UIs
- You want sub-second event notifications
- You need immediate guardrail detection
- Building applications where users watch tasks execute live
Use REST API When:
- Simple integrations where polling is acceptable
- Serverless environments (Lambda, Vercel)
- Stateless workflows
- You don’t need real-time updates
Rule of thumb: If you’re building a UI where users watch tasks execute, use WebSocket. Otherwise, REST is simpler.
Socket.IO Setup and Connection
Installation
Basic Connection
Event Types
agent
Live agent thoughts and reasoning as the task executes.
Event:
Handler:
action
Browser action performed by the agent.
Event:
Handler:
task_completed
Task finished successfully.
Event:
Handler:
guardrail_trigger
Agent needs human input to continue.
Event:
Handler:
error
Task failed with an error.
Event:
Handler:
end_session
Session terminated by server.
Event:
Reasons:
"completed" - Task completed successfully
"terminated" - User terminated session
"expired" - Session expired (5 minutes of inactivity)
"terminateOnCompletion" - Auto-terminated after task
"instance_lost" - Instance connection permanently lost
Handler:
instance:disconnected
Instance connection lost, entering grace period.
Event:
Handler:
instance:reconnected
Instance connection restored.
Event:
Handler:
Complete Working Example
Reconnection Handling
Automatic Reconnection
Socket.IO automatically reconnects on connection loss. The WebRun server maintains session state during brief disconnections.
Instance Disconnection vs Socket Disconnection
Two types of disconnections:
1. Socket Disconnection (client-server connection)
- Handled automatically by Socket.IO
- Session state preserved
- Events resume after reconnection
2. Instance Disconnection (browser instance connection)
- Server loses connection to browser instance
- Grace period to recover
- You receive
instance:disconnected event
- If recovered:
instance:reconnected event
- If not recovered within grace period: session terminates
Error Handling
Error Handler
Sending Commands
You can send commands to control the session via WebSocket:
Start New Task
Pause Task
Resume Task
Stop Task
Terminate Session
Respond to Guardrail
Manual Browser Control
Advanced Pattern: Multi-Task with Live Updates