Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions packages/bcode-browser/src/browser-execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@
//
// Cancellation: JS Promises are not preemptively cancellable. A snippet
// without `await` yield-points (e.g. `for (let i = 0; i < 1e9; i++) {}`)
// runs to completion before our timeout fiber observes it. `Effect.timeoutOrElse`
// fails the surrounding fiber but the orphan Promise keeps running until it
// finishes. This matches the `uv run` subprocess case (SIGTERM only after
// the Python signal handler yields). Document, don't fix.
// runs to completion before our timeout fiber observes it. When a yielding
// snippet times out, its Promise may continue, so we permanently invalidate
// the Session object it received. Abandoned code can finish local work but
// cannot reconnect or send later CDP commands; the next tool call gets a
// fresh Session from SessionStore.
//
// Level 1 per decisions.md §1c — substantial implementation lives here. The
// Level-2 hook in packages/opencode is a thin adapter.
Expand Down Expand Up @@ -157,9 +158,9 @@ const serialize = (v: unknown): string => {
export const make = Effect.fn("BrowserExecute.make")(function* (dataDir: string) {
const skillsDir = yield* Effect.promise(() => Skills.resolveSkillsDir(dataDir))

const execute = (args: Parameters, ctx: ExecuteContext) =>
Effect.gen(function* () {
const session = SessionStore.get(ctx.sessionID)
const execute = (args: Parameters, ctx: ExecuteContext) => {
const session = SessionStore.get(ctx.sessionID)
return Effect.gen(function* () {
yield* Effect.promise(() => fs.mkdir(ctx.workspaceDir, { recursive: true }))

const wrapped = yield* Effect.try({
Expand Down Expand Up @@ -228,9 +229,15 @@ export const make = Effect.fn("BrowserExecute.make")(function* (dataDir: string)
Effect.scoped,
Effect.timeoutOrElse({
duration: Math.min(args.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS),
orElse: () => Effect.fail(new Error("browser_execute timed out")),
orElse: () =>
Effect.gen(function* () {
const error = new Error("browser_execute timed out; CDP session was reset")
yield* Effect.sync(() => SessionStore.invalidate(ctx.sessionID, session, error))

@cubic-dev-ai cubic-dev-ai Bot Jul 24, 2026

Copy link
Copy Markdown

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 new waitFor calls after invalidation) with the reset error.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/bcode-browser/src/browser-execute.ts, line 235:

<comment>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 new `waitFor` calls after invalidation) with the reset error.</comment>

<file context>
@@ -228,9 +229,15 @@ export const make = Effect.fn("BrowserExecute.make")(function* (dataDir: string)
+        orElse: () =>
+          Effect.gen(function* () {
+            const error = new Error("browser_execute timed out; CDP session was reset")
+            yield* Effect.sync(() => SessionStore.invalidate(ctx.sessionID, session, error))
+            return yield* Effect.fail(error)
+          }),
</file context>
Fix with cubic

return yield* Effect.fail(error)
}),
}),
)
}

return { parameters, execute, skillsDir }
})
Expand Down
83 changes: 78 additions & 5 deletions packages/bcode-browser/src/cdp/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> = [];

Expand Down Expand Up @@ -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();

@cubic-dev-ai cubic-dev-ai Bot Jul 24, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A timed-out snippet using { profileDir } can leave its connect() Promise polling for the entire profile-resolution timeout because invalidation is checked only after resolveWsUrl() returns. Making profile resolution cancellation-aware, or racing it with an invalidation signal, would release the abandoned operation immediately while retaining the post-resolution guard against a late socket.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/bcode-browser/src/cdp/session.ts, line 89:

<comment>A timed-out snippet using `{ profileDir }` can leave its `connect()` Promise polling for the entire profile-resolution timeout because invalidation is checked only after `resolveWsUrl()` returns. Making profile resolution cancellation-aware, or racing it with an invalidation signal, would release the abandoned operation immediately while retaining the post-resolution guard against a late socket.</comment>

<file context>
@@ -86,7 +86,7 @@ export class Session implements Transport {
    */
   async connect(opts: ConnectOptions = {}): Promise<void> {
-    if (this.invalidatedError) throw this.invalidatedError;
+    this.throwIfInvalidated();
 
     // No-argument connect is an ensure-connected operation. Reopening the
</file context>
Fix with cubic


// 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.
Expand All @@ -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(
Expand All @@ -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}`);
}
Expand All @@ -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);
Comment thread
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();
Expand All @@ -138,6 +157,10 @@ export class Session implements Transport {
try { ws.close(); } catch { /* ignore */ }
return;
}
if (this.invalidatedError) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
finish(this.invalidatedError);
return;
}
const previous = this.ws;
this.ws = ws;
this.activeSessionId = undefined;
Expand All @@ -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)'));
Comment thread
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).
Expand All @@ -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;
}
Expand Down Expand Up @@ -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);
});
});
Expand Down Expand Up @@ -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.'));
Expand Down
7 changes: 7 additions & 0 deletions packages/bcode-browser/src/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export const get = (sessionID: string): Session => {
return fresh
}

export const invalidate = (sessionID: string, expected: Session, error: Error): void => {
const entry = sessions.get(sessionID)
if (entry !== expected) return
sessions.delete(sessionID)
entry.invalidate(error)
}

export const evict = async (sessionID: string): Promise<void> => {
const entry = sessions.get(sessionID)
if (!entry) return
Expand Down
Loading