-
Notifications
You must be signed in to change notification settings - Fork 35
fix(browser): isolate timed-out snippets #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: session-recovery
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -50,6 +50,9 @@ export class Session implements Transport { | |
| private activeTargetId: string | undefined; | ||
| private reattachPromise?: Promise<void>; | ||
| private enabledDomains = new Map<string, Map<string, unknown>>(); | ||
| private invalidatedError?: Error; | ||
| private openingSockets = new Set<WebSocket>(); | ||
| private pendingWaiters = new Set<(error: Error) => void>(); | ||
| private eventListeners: Array<(method: string, params: unknown, sessionId?: string) => void> = []; | ||
| private callResultListeners: Array<(method: string, params: unknown, result: unknown) => void> = []; | ||
|
|
||
|
|
@@ -83,6 +86,8 @@ export class Session implements Transport { | |
| * and we connect directly to the supplied endpoint. | ||
| */ | ||
| async connect(opts: ConnectOptions = {}): Promise<void> { | ||
| this.throwIfInvalidated(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: A timed-out snippet using Prompt for AI agents |
||
|
|
||
| // No-argument connect is an ensure-connected operation. Reopening the | ||
| // same configured endpoint would discard the active target session and | ||
| // make the next page command run against the browser-level socket. | ||
|
|
@@ -91,15 +96,19 @@ export class Session implements Transport { | |
| const timeoutMs = opts.timeoutMs ?? 5_000; | ||
| if (opts.wsUrl || opts.profileDir) { | ||
| const wsUrl = await resolveWsUrl(opts, timeoutMs); | ||
| this.throwIfInvalidated(); | ||
| await this.openWs(wsUrl, timeoutMs); | ||
| this.throwIfInvalidated(); | ||
| return; | ||
| } | ||
| const envWsUrl = process.env.BU_CDP_WS ?? process.env.BU_CDP_URL; | ||
| if (envWsUrl) { | ||
| await this.openWs(envWsUrl, timeoutMs); | ||
| this.throwIfInvalidated(); | ||
| return; | ||
| } | ||
| const browsers = await detectBrowsers(); | ||
| this.throwIfInvalidated(); | ||
| if (browsers.length === 0) { | ||
| const scanned = getBrowserCandidates().map(c => c.name).join(', '); | ||
| throw new Error( | ||
|
|
@@ -108,10 +117,13 @@ export class Session implements Transport { | |
| } | ||
| const errors: string[] = []; | ||
| for (const b of browsers) { | ||
| this.throwIfInvalidated(); | ||
| try { | ||
| await this.openWs(b.wsUrl, timeoutMs); | ||
| this.throwIfInvalidated(); | ||
| return; | ||
| } catch (e) { | ||
| this.throwIfInvalidated(); | ||
| const msg = e instanceof Error ? e.message : String(e); | ||
| errors.push(` ${b.name} @ ${b.wsUrl}: ${msg}`); | ||
| } | ||
|
|
@@ -122,12 +134,19 @@ export class Session implements Transport { | |
| } | ||
|
|
||
| private openWs(wsUrl: string, timeoutMs: number): Promise<void> { | ||
| this.throwIfInvalidated(); | ||
| return new Promise<void>((res, rej) => { | ||
| if (this.invalidatedError) { | ||
| rej(this.invalidatedError); | ||
| return; | ||
| } | ||
| const ws = new WebSocket(wsUrl); | ||
| this.openingSockets.add(ws); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| let done = false; | ||
| const finish = (err?: Error) => { | ||
| if (done) return; | ||
| done = true; | ||
| this.openingSockets.delete(ws); | ||
| clearTimeout(timer); | ||
| if (err) { try { ws.close(); } catch { /* ignore */ } rej(err); } | ||
| else res(); | ||
|
|
@@ -138,6 +157,10 @@ export class Session implements Transport { | |
| try { ws.close(); } catch { /* ignore */ } | ||
| return; | ||
| } | ||
| if (this.invalidatedError) { | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| finish(this.invalidatedError); | ||
| return; | ||
| } | ||
| const previous = this.ws; | ||
| this.ws = ws; | ||
| this.activeSessionId = undefined; | ||
|
|
@@ -158,19 +181,54 @@ export class Session implements Transport { | |
| this.activeTargetId = undefined; | ||
| this.enabledDomains.clear(); | ||
| } | ||
| finish(new Error('WS closed before open (likely 403 or port closed)')); | ||
| finish(this.invalidatedError ?? new Error('WS closed before open (likely 403 or port closed)')); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| }); | ||
| }); | ||
| } | ||
|
|
||
| private throwIfInvalidated(): void { | ||
| if (this.invalidatedError) throw this.invalidatedError; | ||
| } | ||
|
|
||
| isConnected(): boolean { | ||
| return this.ws?.readyState === WebSocket.OPEN; | ||
| return !this.invalidatedError && this.ws?.readyState === WebSocket.OPEN; | ||
| } | ||
|
|
||
| close(): void { | ||
| this.ws?.close(); | ||
| } | ||
|
|
||
| /** | ||
| * Permanently retire this Session object. | ||
| * | ||
| * Used when an in-process snippet outlives its tool timeout. The Promise | ||
| * itself cannot be preempted, so closing alone is insufficient: abandoned | ||
| * code could call connect() again later. Invalidated sessions reject every | ||
| * future transport operation, while SessionStore gives the next tool call | ||
| * a fresh Session object. | ||
| */ | ||
| invalidate(error: Error): void { | ||
| if (this.invalidatedError) return; | ||
| this.invalidatedError = error; | ||
| const ws = this.ws; | ||
| this.ws = undefined; | ||
| this.activeSessionId = undefined; | ||
| this.activeTargetId = undefined; | ||
| this.enabledDomains.clear(); | ||
| this.eventListeners = []; | ||
| this.callResultListeners = []; | ||
| for (const reject of this.pendingWaiters) reject(error); | ||
| this.pendingWaiters.clear(); | ||
| for (const opening of this.openingSockets) { | ||
| try { opening.close(); } catch { /* ignore */ } | ||
| } | ||
| this.openingSockets.clear(); | ||
| if (ws) { | ||
| this.rejectPending(ws, error); | ||
| try { ws.close(); } catch { /* ignore */ } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Pick a target and make subsequent calls auto-route to it. | ||
| * Uses Target.attachToTarget with flatten:true (single-WS, sessionId-on-message). | ||
|
|
@@ -184,6 +242,7 @@ export class Session implements Transport { | |
|
|
||
| /** Set the active sessionId directly (e.g. one you already attached). */ | ||
| setActiveSession(sessionId: string | undefined): void { | ||
| if (this.invalidatedError) throw this.invalidatedError; | ||
| this.activeSessionId = sessionId; | ||
| this.activeTargetId = undefined; | ||
| } | ||
|
|
@@ -219,16 +278,29 @@ export class Session implements Transport { | |
|
|
||
| /** Wait for the next event matching `method` (and optional predicate). */ | ||
| waitFor<T = unknown>(method: string, predicate?: (params: T) => boolean, timeoutMs = 30_000): Promise<T> { | ||
| if (this.invalidatedError) return Promise.reject(this.invalidatedError); | ||
| return new Promise((resolve, reject) => { | ||
| const timer = setTimeout(() => { | ||
| let settled = false; | ||
| let unsub = () => {}; | ||
| const fail = (error: Error) => { | ||
| if (settled) return; | ||
| settled = true; | ||
| clearTimeout(timer); | ||
| unsub(); | ||
| reject(new Error(`Timeout waiting for ${method}`)); | ||
| this.pendingWaiters.delete(fail); | ||
| reject(error); | ||
| }; | ||
| const timer = setTimeout(() => { | ||
| fail(new Error(`Timeout waiting for ${method}`)); | ||
| }, timeoutMs); | ||
| const unsub = this.onEvent((m, params) => { | ||
| this.pendingWaiters.add(fail); | ||
| unsub = this.onEvent((m, params) => { | ||
| if (m !== method) return; | ||
| if (predicate && !predicate(params as T)) return; | ||
| settled = true; | ||
| clearTimeout(timer); | ||
| unsub(); | ||
| this.pendingWaiters.delete(fail); | ||
| resolve(params as T); | ||
| }); | ||
| }); | ||
|
|
@@ -257,6 +329,7 @@ export class Session implements Transport { | |
| } | ||
|
|
||
| private send(method: string, params: unknown, sessionId?: string): Promise<unknown> { | ||
| if (this.invalidatedError) return Promise.reject(this.invalidatedError); | ||
| const ws = this.ws; | ||
| if (!ws || ws.readyState !== WebSocket.OPEN) { | ||
| return Promise.reject(new Error('Not connected. Call session.connect(...) first.')); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Timed-out snippets awaiting
session.waitFor()remain pending until their own timeout (30s by default), rather than failing when the tool expires.invalidate()clears their listener without rejecting the promise; track and reject these waiters (and reject newwaitForcalls after invalidation) with the reset error.Prompt for AI agents