import type { HumanInterventionCredential, HumanInterventionEvent, } from '../../humanIntervention.js'; import { BrowserControlCoordinator, type BrowserControlState, type BrowserHumanReason, } from './browserControl.js'; import { getStreamPort, waitForStreamPort } from './browserDaemon.js'; export type BrowserMode = 'browse' | 'assist' | 'auto'; export type PickedBrowserElement = { ref: string; pageTitle?: string; tag: string; role?: string; accessibleName?: string; text?: string; boundingBox?: { x: number; y: number; width: number; height: number }; attributes?: Record; }; export type MarkedBrowserElement = PickedBrowserElement & { label?: string; color?: string; }; export type BrowserStreamEvent = Record & { type: string }; export interface BrowserStream { connect(): Promise; disconnect(): void; send(frame: unknown): void; dispose(): void; subscribe(listener: (event: BrowserStreamEvent) => void): () => void; /** Publish a local engine event to Desktop observers (downloads/CDP lifecycle). */ publish(event: BrowserStreamEvent): void; getStatus(): Record; getPort(): number | null; isConnected(): boolean; setMode(mode: BrowserMode): void; getMode(): BrowserMode; getCurrentUrl(): string; setCurrentUrl(url: string): void; pickElement(x: number, y: number): Promise; setPicker( picker: (x: number, y: number) => Promise, ): void; markElement(element: MarkedBrowserElement): void; clearMarkedElements(): void; /** Remove a single marked element by ref (does not affect other marks). */ unmarkElement(ref: string): void; setAgentActing(acting: boolean, action?: string, target?: string): void; /** * 把「这次没找到目标,最像的是这几个」推给可见面板。 * * 候选只进对话的话,盯着浏览器的人看到的是 AI 忽然停住;推到面板上他可以一眼看出 * AI 卡在哪,并点一下把正确的那个喂回去 —— 人的判断比模型再猜一轮便宜得多。 */ setAgentCandidates( candidates: Array<{ ref: string; line: string }>, selector?: string, ): void; /** * 发布一次动作**做完之后**的生效结论(只在结论不是「变了」时调用)。 * * 与 `setAgentActing` 分开是必须的:acting 在 `finally` 里被无条件置回 false, * 把结论挂上去等于发完立刻抹掉。结论要活到下一次动作开始或页面切换。 */ setAgentOutcome(outcome: { action: string; effect: 'unchanged' | 'unknown'; selector?: string; maskedLines?: number; }): void; /** C4:发布 AI 指针语义终点给可见面板(宿主用 CSS 过渡平滑移动 + 渲染点击动效)。 */ setAgentPointer(pointer: { x: number; y: number; visible: boolean; action?: 'move' | 'click' | 'type' | 'hover' | 'scroll' | 'idle'; elementRef?: string; }): void; getControlState(): BrowserControlState; /** 订阅控制权状态变化(立即以当前状态回调一次);供工具即时感知「用户接管 / 进入 waiting_human」以掐断在跑动作。 */ subscribeControl(listener: (state: BrowserControlState) => void): () => void; subscribeInterventions( listener: (event: HumanInterventionEvent) => void, ): () => void; beginAgentAction(input: { runId: string; conversationKey?: string; action?: string; }): void; finishAgentAction(runId: string): void; requestHuman( reason: BrowserHumanReason, input?: { runId?: string; conversationKey?: string; ownerId?: string; summary?: string; }, ): string; takeControl(input?: { runId?: string; conversationKey?: string }): void; resumeControl(token?: string): boolean; stopControl(token?: string): boolean; resumeIntervention(credential: HumanInterventionCredential): boolean; cancelIntervention(credential: HumanInterventionCredential): boolean; waitForHuman(signal?: AbortSignal): Promise<'resumed' | 'stopped'>; } class SessionBrowserStream implements BrowserStream { private socket: WebSocket | null = null; private connecting: Promise | null = null; private listeners = new Set<(event: BrowserStreamEvent) => void>(); private port: number | null = null; private mode: BrowserMode = 'browse'; private currentUrl = 'about:blank'; private status: Record = { connected: false, screencasting: false, }; private reconnectTimer: ReturnType | null = null; private reconnectAttempt = 0; private disposed = false; private picker?: ( x: number, y: number, ) => Promise; private marked: MarkedBrowserElement[] = []; private control: BrowserControlCoordinator; constructor(private readonly sessionName: string) { this.control = new BrowserControlCoordinator({ conversationKey: `browser:${sessionName}`, }); this.control.subscribe((state) => this.emit({ type: 'control_state', state }), ); this.control.subscribeInterventions((event) => this.emit({ type: event.type === 'started' ? 'human_intervention_started' : 'human_intervention_resolved', event, }), ); } async connect(): Promise { this.disposed = false; if (this.socket?.readyState === WebSocket.OPEN) return; if (this.connecting) return this.connecting; this.connecting = (async () => { this.port = (await getStreamPort(this.sessionName)) ?? (await waitForStreamPort(this.sessionName)); await new Promise((resolve, reject) => { const socket = new WebSocket(`ws://127.0.0.1:${this.port}`); const timer = setTimeout(() => { socket.close(); reject(new Error('连接浏览器实时画面超时')); }, 8_000); socket.onopen = () => { clearTimeout(timer); this.socket = socket; this.reconnectAttempt = 0; this.status = { ...this.status, connected: true }; this.emit({ type: 'status', ...this.status }); resolve(); }; socket.onerror = () => { clearTimeout(timer); reject(new Error('无法连接浏览器实时画面')); }; socket.onclose = () => { if (this.socket === socket) this.socket = null; this.status = { ...this.status, connected: false, screencasting: false, }; this.emit({ type: 'status', ...this.status }); this.scheduleReconnect(); }; socket.onmessage = (event) => this.onMessage(event.data); }); })().finally(() => { this.connecting = null; }); return this.connecting; } disconnect(): void { this.disposed = true; if (this.reconnectTimer) clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.socket?.close(); this.socket = null; } dispose(): void { this.disconnect(); this.listeners.clear(); } send(frame: unknown): void { if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(frame)); } subscribe(listener: (event: BrowserStreamEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } publish(event: BrowserStreamEvent): void { this.emit(event); } getStatus(): Record { return this.status; } getPort(): number | null { return this.port; } isConnected(): boolean { return this.socket?.readyState === WebSocket.OPEN; } setMode(mode: BrowserMode): void { this.mode = mode; this.emit({ type: 'mode', mode }); } getMode(): BrowserMode { return this.mode; } getCurrentUrl(): string { return this.currentUrl; } setCurrentUrl(url: string): void { this.currentUrl = url; this.emit({ type: 'url', url }); } setPicker( picker: (x: number, y: number) => Promise, ): void { this.picker = picker; } pickElement(x: number, y: number): Promise { return this.picker ? this.picker(x, y) : Promise.resolve(null); } markElement(element: MarkedBrowserElement): void { this.marked = [ ...this.marked.filter((item) => item.ref !== element.ref), element, ]; this.emit({ type: 'marked_elements', elements: this.marked }); } clearMarkedElements(): void { this.marked = []; this.emit({ type: 'marked_elements', elements: [] }); } unmarkElement(ref: string): void { const next = this.marked.filter((item) => item.ref !== ref); if (next.length !== this.marked.length) { this.marked = next; this.emit({ type: 'marked_elements', elements: this.marked }); } } setAgentActing(acting: boolean, action?: string, target?: string): void { this.emit({ type: 'agent_acting', acting, action, target }); } setAgentCandidates( candidates: Array<{ ref: string; line: string }>, selector?: string, ): void { this.emit({ type: 'agent_candidates', candidates, selector }); } setAgentOutcome(outcome: { action: string; effect: 'unchanged' | 'unknown'; selector?: string; maskedLines?: number; }): void { this.emit({ type: 'agent_outcome', ...outcome }); } setAgentPointer(pointer: { x: number; y: number; visible: boolean; action?: 'move' | 'click' | 'type' | 'hover' | 'scroll' | 'idle'; elementRef?: string; }): void { // 只发语义终点(目标元素中心 + 动作类型);平滑移动交给面板 CSS 过渡,内核不做逐帧插值(避免 WS 洪泛 + 双层缓动打架)。 this.emit({ type: 'agent_pointer', ...pointer }); } getControlState(): BrowserControlState { return this.control.getState(); } subscribeControl(listener: (state: BrowserControlState) => void): () => void { return this.control.subscribe(listener); } subscribeInterventions( listener: (event: HumanInterventionEvent) => void, ): () => void { return this.control.subscribeInterventions(listener); } beginAgentAction(input: { runId: string; conversationKey?: string; action?: string; }): void { this.control.beginAgent(input); } finishAgentAction(runId: string): void { this.control.finishAgent(runId); } requestHuman( reason: BrowserHumanReason, input?: { runId?: string; conversationKey?: string; ownerId?: string; summary?: string; }, ): string { return this.control.requestHuman(reason, input); } takeControl(input?: { runId?: string; conversationKey?: string }): void { this.control.takeInteractive(input); } resumeControl(token?: string): boolean { return this.control.resume(token); } stopControl(token?: string): boolean { return this.control.stop(token); } resumeIntervention(credential: HumanInterventionCredential): boolean { return this.control.resumeIntervention(credential); } cancelIntervention(credential: HumanInterventionCredential): boolean { return this.control.cancelIntervention(credential); } waitForHuman(signal?: AbortSignal): Promise<'resumed' | 'stopped'> { return this.control.waitForHuman(signal); } private emit(event: BrowserStreamEvent): void { for (const listener of this.listeners) { try { listener(event); } catch { // A disconnected/failed UI observer must not break browser control or // prevent the remaining observers from receiving the event. } } } private scheduleReconnect(): void { if (this.disposed || !this.listeners.size || this.reconnectTimer) return; const delay = Math.min(10_000, 250 * 2 ** this.reconnectAttempt++); this.reconnectTimer = setTimeout(() => { this.reconnectTimer = null; void this.connect().catch(() => this.scheduleReconnect()); }, delay); } private onMessage(data: unknown): void { try { const text = typeof data === 'string' ? data : Buffer.from(data as ArrayBuffer).toString('utf8'); const event = JSON.parse(text) as BrowserStreamEvent; if (event.type === 'url' && typeof event.url === 'string') this.currentUrl = event.url; if (event.type === 'status') this.status = { ...this.status, ...event }; this.emit(event); } catch (error) { this.emit({ type: 'error', message: error instanceof Error ? error.message : String(error), }); } } } const streams = new Map(); export function getBrowserStream(sessionName = 'minimal-agent'): BrowserStream { let stream = streams.get(sessionName); if (!stream) { stream = new SessionBrowserStream(sessionName); streams.set(sessionName, stream); } return stream; }