Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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))
Comment thread
MagMueller marked this conversation as resolved.
return yield* Effect.fail(error)
}),
}),
)
}

return { parameters, execute, skillsDir }
})
Expand Down
35 changes: 34 additions & 1 deletion packages/bcode-browser/src/cdp/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ 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 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 +84,8 @@ export class Session implements Transport {
* and we connect directly to the supplied endpoint.
*/
async connect(opts: ConnectOptions = {}): Promise<void> {
if (this.invalidatedError) throw this.invalidatedError;

// 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 Down Expand Up @@ -138,6 +141,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 @@ -164,13 +171,37 @@ export class Session implements Transport {
}

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 = [];
if (!ws) return;
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 +215,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 @@ -257,6 +289,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
58 changes: 58 additions & 0 deletions packages/bcode-browser/test/browser-execute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,61 @@ test("overlapping execute calls do not clobber each other's console capture", as
[aWorkspace, bWorkspace, aData, bData].map((d) => fs.rm(d, { recursive: true, force: true })),
)
})

test("a timed-out snippet cannot send later CDP commands or reconnect", async () => {
const timedOutSessionID = "timeout-" + Math.random().toString(36).slice(2, 8)
const timedOutWorkspace = await fs.mkdtemp(path.join(os.tmpdir(), "bcode-timeout-ws-"))
const timedOutData = await fs.mkdtemp(path.join(os.tmpdir(), "bcode-timeout-data-"))
let lateCommandCount = 0
const server = Bun.serve({
port: 0,
fetch(req, bunServer) {
return bunServer.upgrade(req) ? undefined : new Response("nope", { status: 400 })
},
websocket: {
message(socket, raw) {
const message = JSON.parse(String(raw))
if (message.method !== "Runtime.evaluate") return
lateCommandCount++
socket.send(JSON.stringify({ id: message.id, result: { result: { type: "boolean", value: true } } }))
},
close() {},
},
})
if (server.port === undefined) throw new Error("test server has no port")
const wsUrl = `ws://127.0.0.1:${server.port}/`
const timedOutSession = SessionStore.get(timedOutSessionID)

try {
await timedOutSession.connect({ wsUrl })
await expect(
Effect.runPromise(
Effect.scoped(
Effect.gen(function* () {
const impl = yield* BrowserExecute.make(timedOutData)
return yield* impl.execute(
{
description: "Attempt command after timeout",
code: `await new Promise((resolve) => setTimeout(resolve, 50));
return session.Runtime.evaluate({ expression: "true" });`,
timeout: 10,
},
{ sessionID: timedOutSessionID, workspaceDir: timedOutWorkspace },
)
}),
),
),
).rejects.toThrow("browser_execute timed out; CDP session was reset")

await Bun.sleep(80)
expect(lateCommandCount).toBe(0)
expect(SessionStore.get(timedOutSessionID)).not.toBe(timedOutSession)
await expect(timedOutSession.connect({ wsUrl })).rejects.toThrow("CDP session was reset")
} finally {
await SessionStore.evict(timedOutSessionID)
server.stop(true)
await Promise.all(
[timedOutWorkspace, timedOutData].map((d) => fs.rm(d, { recursive: true, force: true })),
)
}
})