Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(browser): clean up commands when CDP dispatch throws

Afloat780faf821893
diff --git a/server/browser/cdp/connection.test.ts b/server/browser/cdp/connection.test.ts
index dc85c7680e..9ca7f04dbc 100644
--- a/server/browser/cdp/connection.test.ts
+++ b/server/browser/cdp/connection.test.ts
@@ -2,7 +2,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { PassThrough } from "node:stream";
import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { CdpConnection } from "./connection.ts";
import { CdpProtocolError, DriverError } from "./errors.ts";
@@ -92,6 +92,43 @@ describe("the quiet rule", () => {
});
describe("CdpConnection", () => {
+ it("cleans up a command whose transport throws and allows the next command", async () => {
+ vi.useFakeTimers();
+ const browser = fakeBrowser();
+ const send = browser.transport.send;
+ const failure = new Error("pipe write failed");
+ browser.transport.send = () => { throw failure; };
+ const connection = new CdpConnection(browser.transport);
+ try {
+ await expect(connection.root.send("Browser.getVersion")).rejects.toBe(failure);
+ expect(vi.getTimerCount()).toBe(0);
+ browser.transport.send = send;
+ const next = connection.root.send("Browser.getVersion");
+ browser.reply({ id: browser.sent[0].id, result: { product: "Chrome/1" } });
+ await expect(next).resolves.toEqual({ product: "Chrome/1" });
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ connection.close();
+ vi.useRealTimers();
+ }
+ });
+
+ it("cleans up a command that cannot be serialized", async () => {
+ vi.useFakeTimers();
+ const browser = fakeBrowser();
+ const connection = new CdpConnection(browser.transport);
+ const params: Record<string, unknown> = {};
+ params.cycle = params;
+ try {
+ await expect(connection.root.send("Browser.getVersion", params)).rejects.toBeInstanceOf(TypeError);
+ expect(browser.sent).toEqual([]);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ connection.close();
+ vi.useRealTimers();
+ }
+ });
+
it("matches answers to calls and errors to their method", async () => {
const browser = fakeBrowser();
const connection = new CdpConnection(browser.transport);
diff --git a/server/browser/cdp/connection.ts b/server/browser/cdp/connection.ts
index 38d9e99796..92f17ae3ca 100644
--- a/server/browser/cdp/connection.ts
+++ b/server/browser/cdp/connection.ts
@@ -97,7 +97,13 @@ export class CdpConnection {
}, timeoutMs)
: undefined;
this.#pending.set(id, { method, session, resolve, reject, timer });
- this.#transport.send(JSON.stringify(message));
+ try {
+ this.#transport.send(JSON.stringify(message));
+ } catch (error) {
+ this.#pending.delete(id);
+ if (timer) clearTimeout(timer);
+ reject(error);
+ }
});
}