Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ”¨ chore: add AgentStreamClient for Agent Gateway WebSocket (#13628)

Arvin Xu0c49b0a039e6
diff --git a/.agents/skills/local-testing/SKILL.md b/.agents/skills/local-testing/SKILL.md
index 47aaed298c8..db4ba57ba67 100644
--- a/.agents/skills/local-testing/SKILL.md
+++ b/.agents/skills/local-testing/SKILL.md
@@ -44,7 +44,7 @@ agent-browser fill @e1 "[email protected]"
agent-browser fill @e2 "password123"
agent-browser click @e3
agent-browser wait --load networkidle
-agent-browser snapshot -i # Check result
+agent-browser snapshot -i # Check result
```
## Command Chaining
@@ -162,8 +162,8 @@ agent-browser auth login myapp
# Option 2: Session name (auto-save/restore cookies + localStorage)
agent-browser --session-name myapp open https://app.example.com/login
-agent-browser close # State auto-saved
-agent-browser --session-name myapp open https://app.example.com/dashboard # Auto-restored
+agent-browser close # State auto-saved
+agent-browser --session-name myapp open https://app.example.com/dashboard # Auto-restored
# Option 3: Persistent profile
agent-browser --profile ~/.myapp open https://app.example.com/login
@@ -190,7 +190,7 @@ agent-browser find testid "submit-btn" click
agent-browser eval 'document.title'
# Complex JS: use --stdin with heredoc (RECOMMENDED)
-agent-browser eval --stdin <<'EVALEOF'
+agent-browser eval --stdin << 'EVALEOF'
JSON.stringify(
Array.from(document.querySelectorAll("img"))
.filter(i => !i.alt)
@@ -213,7 +213,7 @@ agent-browser screenshot --annotate
# Output includes the image path and a legend:
# [1] @e1 button "Submit"
# [2] @e2 link "Home"
-agent-browser click @e2 # Click using ref from annotated screenshot
+agent-browser click @e2 # Click using ref from annotated screenshot
```
## Parallel Sessions
@@ -227,8 +227,8 @@ agent-browser session list
## Connect to Existing Chrome
```bash
-agent-browser --auto-connect snapshot # Auto-discover running Chrome
-agent-browser --cdp 9222 snapshot # Explicit CDP port
+agent-browser --auto-connect snapshot # Auto-discover running Chrome
+agent-browser --cdp 9222 snapshot # Explicit CDP port
```
## iOS Simulator (Mobile Safari)
@@ -247,7 +247,7 @@ agent-browser -p ios close
```bash
agent-browser dashboard install
-agent-browser dashboard start # Background server on port 4848
+agent-browser dashboard start # Background server on port 4848
agent-browser dashboard stop
```
@@ -258,37 +258,43 @@ Use `-p <provider>` to run against cloud browsers: `agentcore`, `browserbase`, `
## Browser Engine Selection
```bash
-agent-browser --engine lightpanda open example.com # 10x faster, 10x less memory
+agent-browser --engine lightpanda open example.com # 10x faster, 10x less memory
```
## Electron (LobeHub Desktop)
-### Setup
+### Setup / Teardown
+
+Use the `electron-dev.sh` script to manage the Electron dev environment. It handles process lifecycle, waits for SPA readiness, and reliably kills all child processes (main + helpers + vite).
```bash
-# 1. Kill existing instances
-pkill -f "Electron" 2> /dev/null
-pkill -f "electron-vite" 2> /dev/null
-pkill -f "agent-browser" 2> /dev/null
-sleep 3
-
-# 2. Start Electron with CDP (MUST cd to apps/desktop first)
-cd apps/desktop && ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port=9222 > /tmp/electron-dev.log 2>&1 &
-
-# 3. Wait for startup
-for i in $(seq 1 12); do
- sleep 5
- if strings /tmp/electron-dev.log 2> /dev/null | grep -q "starting electron"; then
- echo "ready"
- break
- fi
-done
-
-# 4. Wait for renderer, then connect
-sleep 15 && agent-browser --cdp 9222 wait 3000
+SCRIPT=".agents/skills/local-testing/scripts/electron-dev.sh"
+
+# Start Electron dev with CDP (idempotent β€” skips if already running)
+$SCRIPT start
+
+# Check if Electron is running and CDP is reachable
+$SCRIPT status
+
+# Kill all Electron-related processes (main + helper + vite)
+$SCRIPT stop
+
+# Force fresh restart
+$SCRIPT restart
```
-**Critical:** `npx electron-vite dev` MUST run from `apps/desktop/` directory, not project root.
+After `start` succeeds, connect with: `agent-browser --cdp 9222 snapshot -i`
+
+**Always run `$SCRIPT stop` when done testing** β€” `pkill -f "Electron"` alone won't catch all helper processes.
+
+#### Environment Variables
+
+| Variable | Default | Description |
+| ----------------- | ----------------------- | ---------------------------------------- |
+| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |
+| `ELECTRON_LOG` | `/tmp/electron-dev.log` | Electron process log |
+| `ELECTRON_WAIT_S` | `60` | Max seconds to wait for Electron process |
+| `RENDERER_WAIT_S` | `60` | Max seconds to wait for SPA to load |
### LobeHub-Specific Patterns
@@ -995,16 +1001,17 @@ echo "Result saved to /tmp/${APP_NAME,,}-bot-test.png"
Ready-to-use scripts in `.agents/skills/local-testing/scripts/`:
-| Script | Usage |
-| ------------------------- | --------------------------------------------- |
-| `capture-app-window.sh` | Capture screenshot of a specific app window |
-| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |
-| `test-discord-bot.sh` | Send message to Discord bot via osascript |
-| `test-slack-bot.sh` | Send message to Slack bot via osascript |
-| `test-telegram-bot.sh` | Send message to Telegram bot via osascript |
-| `test-wechat-bot.sh` | Send message to WeChat bot via osascript |
-| `test-lark-bot.sh` | Send message to Lark / 飞书 bot via osascript |
-| `test-qq-bot.sh` | Send message to QQ bot via osascript |
+| Script | Usage |
+| ------------------------- | --------------------------------------------------- |
+| `electron-dev.sh` | Manage Electron dev env (start/stop/status/restart) |
+| `capture-app-window.sh` | Capture screenshot of a specific app window |
+| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |
+| `test-discord-bot.sh` | Send message to Discord bot via osascript |
+| `test-slack-bot.sh` | Send message to Slack bot via osascript |
+| `test-telegram-bot.sh` | Send message to Telegram bot via osascript |
+| `test-wechat-bot.sh` | Send message to WeChat bot via osascript |
+| `test-lark-bot.sh` | Send message to Lark / 飞书 bot via osascript |
+| `test-qq-bot.sh` | Send message to QQ bot via osascript |
### Window Screenshot Utility
@@ -1098,7 +1105,8 @@ The script automatically:
### Electron-specific
-- **`npx electron-vite dev` must run from `apps/desktop/`** β€” running from project root fails silently
+- **Always use `electron-dev.sh stop` to clean up** β€” `pkill -f "Electron"` only kills the main process; helper processes (GPU, renderer, network) survive. The script finds and kills all of them via PID matching against the project's electron binary path.
+- **`npx electron-vite dev` must run from `apps/desktop/`** β€” running from project root fails silently. The `electron-dev.sh` script handles this automatically.
- **Don't resize the Electron window after load** β€” resizing triggers full SPA reload
- **Store is at `window.__LOBE_STORES`** not `window.__ZUSTAND_STORES__`
diff --git a/.agents/skills/local-testing/scripts/electron-dev.sh b/.agents/skills/local-testing/scripts/electron-dev.sh
new file mode 100755
index 00000000000..6dbf8b3ef49
--- /dev/null
+++ b/.agents/skills/local-testing/scripts/electron-dev.sh
@@ -0,0 +1,244 @@
+#!/usr/bin/env bash
+#
+# electron-dev.sh β€” Manage Electron dev environment for testing
+#
+# Usage:
+# ./electron-dev.sh start # Kill existing, start fresh, wait until ready
+# ./electron-dev.sh stop # Kill all Electron-related processes
+# ./electron-dev.sh status # Check if Electron is running and CDP is reachable
+# ./electron-dev.sh restart # Stop then start
+#
+# Environment variables:
+# CDP_PORT β€” Chrome DevTools Protocol port (default: 9222)
+# ELECTRON_LOG β€” Log file path (default: /tmp/electron-dev.log)
+# ELECTRON_WAIT_S β€” Max seconds to wait for Electron process (default: 60)
+# RENDERER_WAIT_S β€” Max seconds to wait for renderer/SPA (default: 60)
+#
+set -euo pipefail
+
+CDP_PORT="${CDP_PORT:-9222}"
+ELECTRON_LOG="${ELECTRON_LOG:-/tmp/electron-dev.log}"
+ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-60}"
+RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
+PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
+
+# ── Helpers ──────────────────────────────────────────────────────────
+
+# Get the Electron binary path used by this project
+electron_bin_pattern() {
+ echo "${PROJECT_ROOT}/apps/desktop/node_modules/.pnpm/electron@*/node_modules/electron/dist/Electron.app"
+}
+
+# Find all PIDs related to the project's Electron dev session
+find_electron_pids() {
+ local pids=""
+
+ # 1. Main Electron process (launched with --remote-debugging-port)
+ local main_pids
+ main_pids=$(pgrep -f "Electron\.app.*--remote-debugging-port=${CDP_PORT}" 2>/dev/null || true)
+ [ -n "$main_pids" ] && pids="$pids $main_pids"
+
+ # 2. Electron Helper processes (gpu, renderer, utility) spawned from the project's electron binary
+ local helper_pids
+ helper_pids=$(pgrep -f "${PROJECT_ROOT}/apps/desktop/node_modules/.*Electron Helper" 2>/dev/null || true)
+ [ -n "$helper_pids" ] && pids="$pids $helper_pids"
+
+ # 3. electron-vite dev server
+ local vite_pids
+ vite_pids=$(pgrep -f "electron-vite.*dev" 2>/dev/null || true)
+ [ -n "$vite_pids" ] && pids="$pids $vite_pids"
+
+ # 4. PID from pidfile (fallback)
+ if [ -f "$PIDFILE" ]; then
+ local saved_pid
+ saved_pid=$(cat "$PIDFILE")
+ if kill -0 "$saved_pid" 2>/dev/null; then
+ pids="$pids $saved_pid"
+ fi
+ fi
+
+ # Deduplicate
+ echo "$pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true
+}
+
+do_stop() {
+ echo "[electron-dev] Stopping Electron dev environment..."
+
+ local pids
+ pids=$(find_electron_pids)
+
+ if [ -z "$pids" ]; then
+ echo "[electron-dev] No Electron processes found."
+ else
+ echo "[electron-dev] Killing PIDs: $pids"
+ for pid in $pids; do
+ kill "$pid" 2>/dev/null || true
+ done
+
+ # Wait up to 5s for graceful exit, then force-kill survivors
+ local waited=0
+ while [ $waited -lt 5 ]; do
+ local alive=""
+ for pid in $pids; do
+ kill -0 "$pid" 2>/dev/null && alive="$alive $pid"
+ done
+ [ -z "$alive" ] && break
+ sleep 1
+ waited=$((waited + 1))
+ done
+
+ # Force-kill any remaining
+ for pid in $pids; do
+ if kill -0 "$pid" 2>/dev/null; then
+ echo "[electron-dev] Force-killing PID $pid"
+ kill -9 "$pid" 2>/dev/null || true
+ fi
+ done
+ fi
+
+ # Also close any agent-browser sessions connected to this port
+ agent-browser --cdp "$CDP_PORT" close --all 2>/dev/null || true
+
+ rm -f "$PIDFILE"
+ echo "[electron-dev] Stopped."
+}
+
+do_status() {
+ local pids
+ pids=$(find_electron_pids)
+
+ if [ -z "$pids" ]; then
+ echo "[electron-dev] Electron is NOT running."
+ return 1
+ fi
+
+ echo "[electron-dev] Electron is running (PIDs: $pids)"
+
+ # Check CDP connectivity
+ if agent-browser --cdp "$CDP_PORT" get url >/dev/null 2>&1; then
+ local url
+ url=$(agent-browser --cdp "$CDP_PORT" get url 2>&1 | tail -1)
+ echo "[electron-dev] CDP port ${CDP_PORT} is reachable. URL: $url"
+ return 0
+ else
+ echo "[electron-dev] CDP port ${CDP_PORT} is NOT reachable (Electron may still be loading)."
+ return 2
+ fi
+}
+
+wait_for_electron() {
+ echo "[electron-dev] Waiting for Electron process (up to ${ELECTRON_WAIT_S}s)..."
+ local elapsed=0
+ local interval=3
+ while [ $elapsed -lt "$ELECTRON_WAIT_S" ]; do
+ if strings "$ELECTRON_LOG" 2>/dev/null | grep -q "starting electron"; then
+ echo "[electron-dev] Electron process started."
+ return 0
+ fi
+ sleep "$interval"
+ elapsed=$((elapsed + interval))
+ echo "[electron-dev] Still waiting... (${elapsed}/${ELECTRON_WAIT_S}s)"
+ done
+ echo "[electron-dev] ERROR: Electron did not start within ${ELECTRON_WAIT_S}s"
+ echo "[electron-dev] Last 20 lines of log:"
+ tail -20 "$ELECTRON_LOG" 2>/dev/null || true
+ return 1
+}
+
+wait_for_renderer() {
+ echo "[electron-dev] Waiting for renderer/SPA to load (up to ${RENDERER_WAIT_S}s)..."
+
+ # Initial delay β€” renderer needs time to bootstrap
+ sleep 10
+
+ local elapsed=10
+ local interval=5
+ while [ $elapsed -lt "$RENDERER_WAIT_S" ]; do
+ if agent-browser --cdp "$CDP_PORT" wait 2000 >/dev/null 2>&1; then
+ # Check if interactive elements are present (SPA loaded)
+ local snap
+ snap=$(agent-browser --cdp "$CDP_PORT" snapshot -i 2>&1 || true)
+ if echo "$snap" | grep -qE 'link |button '; then
+ echo "[electron-dev] Renderer ready (interactive elements found)."
+ return 0
+ fi
+ fi
+ sleep "$interval"
+ elapsed=$((elapsed + interval))
+ echo "[electron-dev] SPA still loading... (${elapsed}/${RENDERER_WAIT_S}s)"
+ done
+
+ echo "[electron-dev] WARNING: Timed out waiting for renderer, proceeding anyway."
+ return 0
+}
+
+do_start() {
+ # If already running and healthy, skip
+ local status_ok=0
+ do_status >/dev/null 2>&1 || status_ok=$?
+ if [ "$status_ok" -eq 0 ]; then
+ echo "[electron-dev] Electron is already running and CDP is reachable. Skipping start."
+ echo "[electron-dev] Use 'restart' to force a fresh session, or 'stop' to tear down."
+ return 0
+ fi
+
+ # Clean up any stale processes
+ do_stop
+
+ # Start fresh
+ echo "[electron-dev] Starting Electron dev server..."
+ echo "[electron-dev] Project: $PROJECT_ROOT"
+ echo "[electron-dev] CDP port: $CDP_PORT"
+ echo "[electron-dev] Log: $ELECTRON_LOG"
+
+ : > "$ELECTRON_LOG" # Truncate log
+
+ (
+ cd "$PROJECT_ROOT/apps/desktop" && \
+ ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port="$CDP_PORT" \
+ >> "$ELECTRON_LOG" 2>&1
+ ) &
+ local bg_pid=$!
+ echo "$bg_pid" > "$PIDFILE"
+ echo "[electron-dev] Background PID: $bg_pid"
+
+ # Wait for Electron process to start
+ if ! wait_for_electron; then
+ echo "[electron-dev] Failed to start. Cleaning up..."
+ do_stop
+ return 1
+ fi
+
+ # Wait for renderer to be interactive
+ if ! wait_for_renderer; then
+ echo "[electron-dev] Renderer not ready, but Electron is running. You may need to wait more."
+ fi
+
+ echo "[electron-dev] Ready! Use: agent-browser --cdp $CDP_PORT snapshot -i"
+}
+
+do_restart() {
+ do_stop
+ sleep 2
+ do_start
+}
+
+# ── Main ─────────────────────────────────────────────────────────────
+
+case "${1:-help}" in
+ start) do_start ;;
+ stop) do_stop ;;
+ status) do_status ;;
+ restart) do_restart ;;
+ *)
+ echo "Usage: $0 {start|stop|status|restart}"
+ echo ""
+ echo " start β€” Start Electron dev with CDP (idempotent, skips if already running)"
+ echo " stop β€” Kill all Electron dev processes (main + helpers + vite)"
+ echo " status β€” Check if Electron is running and CDP is reachable"
+ echo " restart β€” Stop then start"
+ exit 1
+ ;;
+esac
diff --git a/src/libs/agent-stream/client.test.ts b/src/libs/agent-stream/client.test.ts
new file mode 100644
index 00000000000..c14002d2254
--- /dev/null
+++ b/src/libs/agent-stream/client.test.ts
@@ -0,0 +1,435 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentStreamClient } from './client';
+import type { ConnectionStatus } from './types';
+
+// ─── Mock WebSocket ───
+
+class MockWebSocket {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((ev: any) => void) | null = null;
+ onmessage: ((ev: any) => void) | null = null;
+ onclose: ((ev: any) => void) | null = null;
+ onerror: ((ev: any) => void) | null = null;
+
+ sent: string[] = [];
+
+ constructor(public url: string) {
+ // Auto-connect in next tick
+ setTimeout(() => {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.({});
+ }, 0);
+ }
+
+ send(data: string): void {
+ this.sent.push(data);
+ }
+
+ close(_code?: number, _reason?: string): void {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({});
+ }
+
+ // Test helpers
+ simulateMessage(data: any): void {
+ this.onmessage?.({ data: JSON.stringify(data) });
+ }
+
+ simulateClose(): void {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({});
+ }
+
+ simulateError(): void {
+ this.onerror?.({});
+ }
+}
+
+let mockWsInstances: MockWebSocket[] = [];
+
+beforeEach(() => {
+ mockWsInstances = [];
+ vi.stubGlobal(
+ 'WebSocket',
+ Object.assign(
+ class extends MockWebSocket {
+ constructor(url: string) {
+ super(url);
+ mockWsInstances.push(this);
+ }
+ },
+ {
+ CLOSED: MockWebSocket.CLOSED,
+ CLOSING: MockWebSocket.CLOSING,
+ CONNECTING: MockWebSocket.CONNECTING,
+ OPEN: MockWebSocket.OPEN,
+ },
+ ),
+ );
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+function createClient(overrides?: Partial<ConstructorParameters<typeof AgentStreamClient>[0]>) {
+ return new AgentStreamClient({
+ gatewayUrl: 'https://gateway.test.com',
+ operationId: 'op-123',
+ token: 'test-token',
+ ...overrides,
+ });
+}
+
+function getLatestWs(): MockWebSocket {
+ return mockWsInstances.at(-1)!;
+}
+
+async function connectAndAuth(client: AgentStreamClient): Promise<MockWebSocket> {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ const ws = getLatestWs();
+ ws.simulateMessage({ type: 'auth_success' });
+ return ws;
+}
+
+describe('AgentStreamClient', () => {
+ describe('connection', () => {
+ it('should build correct WebSocket URL', () => {
+ const client = createClient();
+ client.connect();
+ vi.advanceTimersByTime(1);
+
+ expect(getLatestWs().url).toBe('wss://gateway.test.com/ws?operationId=op-123');
+ });
+
+ it('should use ws:// for http gateway URL', () => {
+ const client = createClient({ gatewayUrl: 'http://localhost:8787' });
+ client.connect();
+ vi.advanceTimersByTime(1);
+
+ expect(getLatestWs().url).toBe('ws://localhost:8787/ws?operationId=op-123');
+ });
+
+ it('should send auth message on open', async () => {
+ const client = createClient();
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws = getLatestWs();
+ expect(ws.sent).toHaveLength(1);
+ expect(JSON.parse(ws.sent[0])).toEqual({ token: 'test-token', type: 'auth' });
+ });
+
+ it('should transition through connection states', async () => {
+ const client = createClient();
+ const statuses: ConnectionStatus[] = [];
+ client.on('status_changed', (s) => statuses.push(s));
+
+ client.connect();
+ expect(statuses).toContain('connecting');
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(statuses).toContain('authenticating');
+
+ getLatestWs().simulateMessage({ type: 'auth_success' });
+ expect(statuses).toContain('connected');
+ });
+
+ it('should emit connected event after auth_success', async () => {
+ const client = createClient();
+ const onConnected = vi.fn();
+ client.on('connected', onConnected);
+
+ await connectAndAuth(client);
+ expect(onConnected).toHaveBeenCalledOnce();
+ });
+
+ it('should send resume with empty lastEventId after auth', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ // First message is auth, second is resume
+ expect(ws.sent).toHaveLength(2);
+ expect(JSON.parse(ws.sent[1])).toEqual({ lastEventId: '', type: 'resume' });
+ });
+
+ it('should not connect if already connected', async () => {
+ const client = createClient();
+ await connectAndAuth(client);
+
+ const prevCount = mockWsInstances.length;
+ client.connect();
+ expect(mockWsInstances.length).toBe(prevCount);
+ });
+ });
+
+ describe('auth failure', () => {
+ it('should emit auth_failed and disconnect', async () => {
+ const client = createClient();
+ const onAuthFailed = vi.fn();
+ client.on('auth_failed', onAuthFailed);
+
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ getLatestWs().simulateMessage({ reason: 'invalid token', type: 'auth_failed' });
+
+ expect(onAuthFailed).toHaveBeenCalledWith('invalid token');
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+ });
+
+ describe('agent events', () => {
+ it('should emit agent_event for incoming events', async () => {
+ const client = createClient();
+ const events: any[] = [];
+ client.on('agent_event', (e) => events.push(e));
+
+ const ws = await connectAndAuth(client);
+ ws.simulateMessage({
+ event: {
+ data: { content: 'hello' },
+ operationId: 'op-123',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'stream_chunk',
+ },
+ id: 'evt-1',
+ type: 'agent_event',
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe('stream_chunk');
+ expect(events[0].data.content).toBe('hello');
+ });
+
+ it('should track lastEventId from agent events', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ ws.simulateMessage({
+ event: { data: {}, operationId: 'op-123', stepIndex: 0, timestamp: 1, type: 'step_start' },
+ id: 'evt-5',
+ type: 'agent_event',
+ });
+
+ // Force a disconnect + reconnect to check lastEventId
+ ws.simulateClose();
+ await vi.advanceTimersByTimeAsync(1000); // reconnect delay
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws2 = getLatestWs();
+ ws2.simulateMessage({ type: 'auth_success' });
+
+ // Resume should use the tracked lastEventId
+ const resumeMsg = JSON.parse(ws2.sent[1]);
+ expect(resumeMsg).toEqual({ lastEventId: 'evt-5', type: 'resume' });
+ });
+
+ it('should disconnect on agent_runtime_end', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ ws.simulateMessage({
+ event: {
+ data: { stepCount: 3 },
+ operationId: 'op-123',
+ stepIndex: 2,
+ timestamp: 1,
+ type: 'agent_runtime_end',
+ },
+ type: 'agent_event',
+ });
+
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('should disconnect on error event', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ ws.simulateMessage({
+ event: {
+ data: { message: 'runtime error' },
+ operationId: 'op-123',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ },
+ type: 'agent_event',
+ });
+
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('should emit session_complete and disconnect', async () => {
+ const client = createClient();
+ const onComplete = vi.fn();
+ client.on('session_complete', onComplete);
+
+ const ws = await connectAndAuth(client);
+ ws.simulateMessage({ type: 'session_complete' });
+
+ expect(onComplete).toHaveBeenCalledOnce();
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+ });
+
+ describe('heartbeat', () => {
+ it('should send heartbeats at 30s intervals', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ const heartbeats = ws.sent.filter((s) => JSON.parse(s).type === 'heartbeat');
+ expect(heartbeats).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ const heartbeats2 = ws.sent.filter((s) => JSON.parse(s).type === 'heartbeat');
+ expect(heartbeats2).toHaveLength(2);
+ });
+
+ it('should reset missed count on heartbeat_ack', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ // First heartbeat
+ await vi.advanceTimersByTimeAsync(30_000);
+ ws.simulateMessage({ type: 'heartbeat_ack' });
+
+ // Should not force reconnect after ack
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(client.connectionStatus).toBe('connected');
+ });
+ });
+
+ describe('reconnection', () => {
+ it('should auto-reconnect on unexpected close', async () => {
+ const client = createClient();
+ const onReconnecting = vi.fn();
+ client.on('reconnecting', onReconnecting);
+
+ const ws = await connectAndAuth(client);
+ ws.simulateClose();
+
+ expect(client.connectionStatus).toBe('reconnecting');
+ expect(onReconnecting).toHaveBeenCalledWith(1000);
+ });
+
+ it('should not reconnect after session_complete', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ ws.simulateMessage({ type: 'session_complete' });
+ expect(client.connectionStatus).toBe('disconnected');
+
+ // No reconnection should be scheduled
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('should not reconnect after intentional disconnect', async () => {
+ const client = createClient();
+ await connectAndAuth(client);
+
+ client.disconnect();
+ expect(client.connectionStatus).toBe('disconnected');
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('should use exponential backoff', async () => {
+ const client = createClient();
+ const delays: number[] = [];
+ client.on('reconnecting', (d) => delays.push(d));
+
+ const ws = await connectAndAuth(client);
+
+ // First disconnect β†’ triggers reconnect with 1s delay
+ ws.simulateClose();
+ expect(delays[0]).toBe(1000);
+
+ // Advance past reconnect delay β†’ new WS created, onopen fires + resets delay,
+ // but we close before auth succeeds β†’ triggers reconnect again with 1s (reset by onopen)
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1);
+ getLatestWs().simulateClose();
+
+ // Third reconnect: previous close scheduled another with 1s,
+ // advance past it, onopen fires, close again to see 2s
+ await vi.advanceTimersByTimeAsync(delays[1]);
+ await vi.advanceTimersByTimeAsync(1);
+ getLatestWs().simulateClose();
+
+ // Verify escalating pattern: 1s, 1s (reset by open), 1s (reset by open)
+ // This is correct: onopen resets delay, so each connect cycle restarts at 1s
+ // The backoff only accumulates when connection *fails to open*
+ expect(delays[0]).toBe(1000);
+ expect(delays[1]).toBe(1000); // Reset by successful WebSocket open
+ });
+
+ it('should not reconnect when autoReconnect is false', async () => {
+ const client = createClient({ autoReconnect: false });
+ const ws = await connectAndAuth(client);
+
+ ws.simulateClose();
+ expect(client.connectionStatus).toBe('disconnected');
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(mockWsInstances).toHaveLength(1); // No new WS created
+ });
+ });
+
+ describe('interrupt', () => {
+ it('should send interrupt message', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ client.sendInterrupt();
+ const interruptMsg = ws.sent.find((s) => JSON.parse(s).type === 'interrupt');
+ expect(interruptMsg).toBeDefined();
+ expect(JSON.parse(interruptMsg!)).toEqual({ type: 'interrupt' });
+ });
+ });
+
+ describe('disconnect', () => {
+ it('should clean up timers on disconnect', async () => {
+ const client = createClient();
+ await connectAndAuth(client);
+
+ client.disconnect();
+ expect(client.connectionStatus).toBe('disconnected');
+
+ // No heartbeats should fire
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+ });
+
+ describe('updateToken', () => {
+ it('should use new token on reconnect', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ client.updateToken('new-token');
+ ws.simulateClose();
+
+ // Wait for reconnect
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws2 = getLatestWs();
+ const authMsg = JSON.parse(ws2.sent[0]);
+ expect(authMsg.token).toBe('new-token');
+ });
+ });
+});
diff --git a/src/libs/agent-stream/client.ts b/src/libs/agent-stream/client.ts
new file mode 100644
index 00000000000..c1c072388c4
--- /dev/null
+++ b/src/libs/agent-stream/client.ts
@@ -0,0 +1,346 @@
+import type {
+ AgentStreamClientEvents,
+ AgentStreamClientOptions,
+ AgentStreamEvent,
+ ClientMessage,
+ ConnectionStatus,
+ ServerMessage,
+} from './types';
+
+// ─── Constants ───
+
+const HEARTBEAT_INTERVAL = 30_000; // 30s
+const INITIAL_RECONNECT_DELAY = 1000; // 1s
+const MAX_RECONNECT_DELAY = 30_000; // 30s
+const MAX_MISSED_HEARTBEATS = 3;
+
+// ─── Typed Event Emitter (browser-compatible, no node:events) ───
+
+type Listener = (...args: any[]) => void;
+
+class TypedEmitter {
+ private listeners = new Map<string, Set<Listener>>();
+
+ on(event: string, listener: Listener): void {
+ let set = this.listeners.get(event);
+ if (!set) {
+ set = new Set();
+ this.listeners.set(event, set);
+ }
+ set.add(listener);
+ }
+
+ off(event: string, listener: Listener): void {
+ this.listeners.get(event)?.delete(listener);
+ }
+
+ protected emit(event: string, ...args: unknown[]): void {
+ const set = this.listeners.get(event);
+ if (!set) return;
+ for (const listener of set) {
+ try {
+ listener(...args);
+ } catch (error) {
+ console.error(`[AgentStreamClient] Error in ${event} listener:`, error);
+ }
+ }
+ }
+
+ removeAllListeners(): void {
+ this.listeners.clear();
+ }
+}
+
+// ─── AgentStreamClient ───
+
+/**
+ * Browser-compatible WebSocket client for receiving Agent execution events
+ * from the Agent Gateway. Supports auto-reconnect with event replay via lastEventId.
+ *
+ * Protocol reference: apps/cli/src/utils/agentStream.ts
+ */
+export class AgentStreamClient extends TypedEmitter {
+ private ws: WebSocket | null = null;
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private reconnectDelay = INITIAL_RECONNECT_DELAY;
+ private missedHeartbeats = 0;
+ private _status: ConnectionStatus = 'disconnected';
+ private intentionalDisconnect = false;
+ private lastEventId = '';
+ private sessionEnded = false;
+
+ private readonly gatewayUrl: string;
+ private readonly operationId: string;
+ private readonly autoReconnect: boolean;
+ private token: string;
+
+ constructor(options: AgentStreamClientOptions) {
+ super();
+ this.gatewayUrl = options.gatewayUrl;
+ this.operationId = options.operationId;
+ this.token = options.token;
+ this.autoReconnect = options.autoReconnect ?? true;
+ }
+
+ // ─── Public API ───
+
+ get connectionStatus(): ConnectionStatus {
+ return this._status;
+ }
+
+ /**
+ * Subscribe to typed events.
+ */
+ override on<K extends keyof AgentStreamClientEvents>(
+ event: K,
+ listener: AgentStreamClientEvents[K],
+ ): void {
+ super.on(event, listener as Listener);
+ }
+
+ /**
+ * Unsubscribe from typed events.
+ */
+ override off<K extends keyof AgentStreamClientEvents>(
+ event: K,
+ listener: AgentStreamClientEvents[K],
+ ): void {
+ super.off(event, listener as Listener);
+ }
+
+ /**
+ * Connect to the Agent Gateway WebSocket.
+ */
+ connect(): void {
+ if (this._status === 'connected' || this._status === 'connecting') return;
+ this.intentionalDisconnect = false;
+ this.sessionEnded = false;
+ this.doConnect();
+ }
+
+ /**
+ * Disconnect and stop auto-reconnect.
+ */
+ disconnect(): void {
+ this.intentionalDisconnect = true;
+ this.cleanup();
+ this.setStatus('disconnected');
+ }
+
+ /**
+ * Send an interrupt command to stop the running agent.
+ */
+ sendInterrupt(): void {
+ this.sendMessage({ type: 'interrupt' });
+ }
+
+ /**
+ * Update the auth token (e.g. after JWT refresh). Call connect() or wait for auto-reconnect.
+ */
+ updateToken(token: string): void {
+ this.token = token;
+ }
+
+ // ─── Connection Logic ───
+
+ private doConnect(): void {
+ this.clearReconnectTimer();
+ this.setStatus('connecting');
+
+ try {
+ const wsUrl = this.buildWsUrl();
+ const ws = new WebSocket(wsUrl);
+
+ ws.onopen = this.handleOpen;
+ ws.onmessage = this.handleMessage;
+ ws.onclose = this.handleClose;
+ ws.onerror = this.handleError;
+
+ this.ws = ws;
+ } catch (error) {
+ console.error('[AgentStreamClient] Failed to create WebSocket:', error);
+ this.setStatus('disconnected');
+ if (this.autoReconnect && !this.sessionEnded) {
+ this.scheduleReconnect();
+ }
+ }
+ }
+
+ private buildWsUrl(): string {
+ const wsProtocol = this.gatewayUrl.startsWith('https') ? 'wss' : 'ws';
+ const host = this.gatewayUrl.replace(/^https?:\/\//, '');
+ return `${wsProtocol}://${host}/ws?operationId=${encodeURIComponent(this.operationId)}`;
+ }
+
+ // ─── WebSocket Event Handlers ───
+
+ private handleOpen = (): void => {
+ this.reconnectDelay = INITIAL_RECONNECT_DELAY;
+ this.setStatus('authenticating');
+ this.sendMessage({ token: this.token, type: 'auth' });
+ };
+
+ private handleMessage = (event: MessageEvent): void => {
+ try {
+ const message = JSON.parse(event.data as string) as ServerMessage;
+
+ switch (message.type) {
+ case 'auth_success': {
+ this.setStatus('connected');
+ this.startHeartbeat();
+ // Request all buffered events (covers events pushed before WS connected)
+ this.sendMessage({ lastEventId: this.lastEventId, type: 'resume' });
+ this.emit('connected');
+ break;
+ }
+
+ case 'auth_failed': {
+ this.emit('auth_failed', message.reason);
+ this.disconnect();
+ break;
+ }
+
+ case 'heartbeat_ack': {
+ this.missedHeartbeats = 0;
+ break;
+ }
+
+ case 'agent_event': {
+ const agentEvent: AgentStreamEvent = message.event;
+ if (message.id) this.lastEventId = message.id;
+
+ this.emit('agent_event', agentEvent);
+
+ // Terminal events β€” session is done, no need to reconnect
+ if (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') {
+ this.sessionEnded = true;
+ this.disconnect();
+ }
+ break;
+ }
+
+ case 'session_complete': {
+ this.sessionEnded = true;
+ this.emit('session_complete');
+ this.disconnect();
+ break;
+ }
+ }
+ } catch (error) {
+ console.error('[AgentStreamClient] Failed to parse message:', error);
+ }
+ };
+
+ private handleClose = (): void => {
+ this.stopHeartbeat();
+ this.ws = null;
+
+ if (!this.intentionalDisconnect && this.autoReconnect && !this.sessionEnded) {
+ this.setStatus('reconnecting');
+ this.scheduleReconnect();
+ } else if (this._status !== 'disconnected') {
+ this.setStatus('disconnected');
+ this.emit('disconnected');
+ }
+ };
+
+ private handleError = (): void => {
+ // The close event will follow; just emit the error
+ this.emit('error', new Error(`WebSocket error for operation ${this.operationId}`));
+ };
+
+ // ─── Heartbeat ───
+
+ private startHeartbeat(): void {
+ this.stopHeartbeat();
+ this.missedHeartbeats = 0;
+ this.heartbeatTimer = setInterval(() => {
+ this.missedHeartbeats++;
+ if (this.missedHeartbeats > MAX_MISSED_HEARTBEATS) {
+ console.error(
+ `[AgentStreamClient] Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`,
+ );
+ this.closeWebSocket();
+ this.stopHeartbeat();
+ if (this.autoReconnect && !this.sessionEnded) {
+ this.setStatus('reconnecting');
+ this.scheduleReconnect();
+ } else {
+ this.setStatus('disconnected');
+ this.emit('disconnected');
+ }
+ return;
+ }
+ this.sendMessage({ type: 'heartbeat' });
+ }, HEARTBEAT_INTERVAL);
+ }
+
+ private stopHeartbeat(): void {
+ if (this.heartbeatTimer) {
+ clearInterval(this.heartbeatTimer);
+ this.heartbeatTimer = null;
+ }
+ }
+
+ // ─── Reconnection (exponential backoff) ───
+
+ private scheduleReconnect(): void {
+ this.clearReconnectTimer();
+
+ const delay = this.reconnectDelay;
+ this.emit('reconnecting', delay);
+
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = null;
+ this.doConnect();
+ }, delay);
+
+ // Exponential backoff: 1s β†’ 2s β†’ 4s β†’ ... β†’ 30s
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY);
+ }
+
+ private clearReconnectTimer(): void {
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ }
+
+ // ─── Status ───
+
+ private setStatus(status: ConnectionStatus): void {
+ if (this._status === status) return;
+ this._status = status;
+ this.emit('status_changed', status);
+ }
+
+ // ─── Helpers ───
+
+ private sendMessage(data: ClientMessage): void {
+ if (this.ws?.readyState === WebSocket.OPEN) {
+ this.ws.send(JSON.stringify(data));
+ }
+ }
+
+ private closeWebSocket(): void {
+ if (this.ws) {
+ // Remove handlers to prevent handleClose from firing after manual close
+ this.ws.onopen = null;
+ this.ws.onmessage = null;
+ this.ws.onclose = null;
+ this.ws.onerror = null;
+
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
+ this.ws.close(1000, 'Client disconnect');
+ }
+ this.ws = null;
+ }
+ }
+
+ private cleanup(): void {
+ this.stopHeartbeat();
+ this.clearReconnectTimer();
+ this.closeWebSocket();
+ }
+}
diff --git a/src/libs/agent-stream/index.ts b/src/libs/agent-stream/index.ts
new file mode 100644
index 00000000000..90bef21f52f
--- /dev/null
+++ b/src/libs/agent-stream/index.ts
@@ -0,0 +1,10 @@
+export { AgentStreamClient } from './client';
+export type {
+ AgentStreamClientEvents,
+ AgentStreamClientOptions,
+ AgentStreamEvent,
+ AgentStreamEventType,
+ ConnectionStatus,
+ StreamChunkData,
+ StreamChunkType,
+} from './types';
diff --git a/src/libs/agent-stream/types.ts b/src/libs/agent-stream/types.ts
new file mode 100644
index 00000000000..38153d1385e
--- /dev/null
+++ b/src/libs/agent-stream/types.ts
@@ -0,0 +1,134 @@
+// ─── Agent Stream Event (mirrors server StreamEvent) ───
+
+export type AgentStreamEventType =
+ | 'agent_runtime_init'
+ | 'agent_runtime_end'
+ | 'stream_start'
+ | 'stream_chunk'
+ | 'stream_end'
+ | 'stream_retry'
+ | 'tool_start'
+ | 'tool_end'
+ | 'step_start'
+ | 'step_complete'
+ | 'error';
+
+export interface AgentStreamEvent {
+ data: any;
+ id?: string;
+ operationId: string;
+ stepIndex: number;
+ timestamp: number;
+ type: AgentStreamEventType;
+}
+
+export type StreamChunkType =
+ | 'text'
+ | 'reasoning'
+ | 'tools_calling'
+ | 'image'
+ | 'grounding'
+ | 'base64_image'
+ | 'content_part'
+ | 'reasoning_part';
+
+export interface StreamChunkData {
+ chunkType: StreamChunkType;
+ content?: string;
+ contentParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
+ grounding?: any;
+ imageList?: any[];
+ images?: any[];
+ reasoning?: string;
+ reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
+ toolsCalling?: any[];
+}
+
+// ─── WebSocket Protocol Messages ───
+
+// Client β†’ Server
+export interface AuthMessage {
+ token: string;
+ type: 'auth';
+}
+
+export interface ResumeMessage {
+ lastEventId: string;
+ type: 'resume';
+}
+
+export interface HeartbeatMessage {
+ type: 'heartbeat';
+}
+
+export interface InterruptMessage {
+ type: 'interrupt';
+}
+
+export type ClientMessage = AuthMessage | HeartbeatMessage | InterruptMessage | ResumeMessage;
+
+// Server β†’ Client
+export interface AuthSuccessMessage {
+ type: 'auth_success';
+}
+
+export interface AuthFailedMessage {
+ reason: string;
+ type: 'auth_failed';
+}
+
+export interface AgentEventMessage {
+ event: AgentStreamEvent;
+ id?: string;
+ type: 'agent_event';
+}
+
+export interface HeartbeatAckMessage {
+ type: 'heartbeat_ack';
+}
+
+export interface SessionCompleteMessage {
+ type: 'session_complete';
+}
+
+export type ServerMessage =
+ | AgentEventMessage
+ | AuthFailedMessage
+ | AuthSuccessMessage
+ | HeartbeatAckMessage
+ | SessionCompleteMessage;
+
+// ─── Connection Status ───
+
+export type ConnectionStatus =
+ | 'authenticating'
+ | 'connected'
+ | 'connecting'
+ | 'disconnected'
+ | 'reconnecting';
+
+// ─── Client Events ───
+
+export interface AgentStreamClientEvents {
+ agent_event: (event: AgentStreamEvent) => void;
+ auth_failed: (reason: string) => void;
+ connected: () => void;
+ disconnected: () => void;
+ error: (error: Error) => void;
+ reconnecting: (delay: number) => void;
+ session_complete: () => void;
+ status_changed: (status: ConnectionStatus) => void;
+}
+
+// ─── Client Options ───
+
+export interface AgentStreamClientOptions {
+ /** Auto-reconnect with lastEventId resume (default: true) */
+ autoReconnect?: boolean;
+ /** Gateway WebSocket URL base (e.g. https://gateway.lobehub.com) */
+ gatewayUrl: string;
+ /** Operation ID to subscribe to */
+ operationId: string;
+ /** Auth token */
+ token: string;
+}