Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

fix(ego-browser): toggle setChecked with a real click

0x06da0d9dbc1d0
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
index 826986a..5592c85 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
@@ -75,6 +75,24 @@ export function keyboardCase() {
assertEqual(await page.locator("#checkbox").isChecked(), false, "isChecked reads unchecked state");
await page.locator("#checkbox").setChecked(true);
await waitForJsValue("window.__fixtureState.checkboxChecked", true, "setChecked sets explicit state");
+ await page.locator("#checkbox").setChecked(true);
+ await waitForJsValue("window.__fixtureState.checkboxChecked", true, "setChecked is a no-op when the state already matches");
+
+ /* A controlled input only advances on a real click; a property write is dropped. */
+ await page.locator("#controlled-checkbox").check();
+ await waitForJsValue("window.__fixtureState.controlledChecked", true, "check drives a controlled checkbox");
+ await waitForJsValue("window.__fixtureState.controlledChanges", 1, "check fires exactly one controlled change");
+ await page.locator("#controlled-checkbox").uncheck();
+ await waitForJsValue("window.__fixtureState.controlledChecked", false, "uncheck clears a controlled checkbox");
+
+ await page.locator("#controlled-radio-pro").setChecked(true);
+ await waitForJsValue("window.__fixtureState.controlledPlan", "pro", "setChecked drives a controlled radio");
+ assertEqual(await page.locator("#controlled-radio-basic").isChecked(), false, "controlled radio group keeps a single selection");
+ await assertRejects(
+ () => page.locator("#controlled-radio-pro").uncheck(),
+ "cannot uncheck a radio",
+ "uncheck rejects radio inputs"
+ );
await page.locator("#text-input").fill("select me", { timeout: 3000 });
await page.keyboard.press("ControlOrMeta+a");
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index a3bc0c2..50a9be4 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -574,6 +574,13 @@ function pageHtml(kind) {
<div id="inner-scroll"><div id="inner-scroll-content">Inner scroll marker</div></div>
<section id="scroll-area"><div id="bottom-marker">Bottom marker</div></section>
+ <!-- Kept below #scroll-area: new nodes above it shift the page and break the wheel cases. -->
+ <div id="controlled-checkable">
+ <label><input type="checkbox" id="controlled-checkbox"> Nonstop only</label>
+ <label><input type="radio" name="controlled-plan" id="controlled-radio-basic" value="basic"> Plan basic</label>
+ <label><input type="radio" name="controlled-plan" id="controlled-radio-pro" value="pro"> Plan pro</label>
+ </div>
+
${kind === "frame" ? '<div id="iframe-marker" data-iframe="true" style="border:2px solid var(--accent);padding:4px 8px;margin-top:4px;border-radius:4px;font-size:0.8rem">iframe target</div>' : ""}
</main>
<script>
@@ -591,6 +598,10 @@ function pageHtml(kind) {
dynamicElementExists: false,
tabOrder: [],
checkboxChecked: false,
+ controlledChecked: false,
+ controlledChanges: 0,
+ controlledPlan: "",
+ controlledPlanChanges: 0,
dropdownValue: "alpha",
valueEvents: {},
canvasStrokes: 0,
@@ -692,6 +703,62 @@ function pageHtml(kind) {
render();
})();
+ /* ---- react-style controlled checkbox / radio ----
+ Mirrors React's input value tracker: writing the checked property runs the
+ instance setter, which records the new value, so the event that follows
+ looks like a no-op and the state never advances. A real click sets
+ checkedness internally and bypasses the setter, so the tracker still sees
+ a change. React derives checkbox/radio onChange from the click event, so
+ this listens there too. */
+ (function () {
+ const native = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked");
+ function track(node) {
+ let tracked = String(native.get.call(node));
+ Object.defineProperty(node, "checked", {
+ configurable: true,
+ get() { return native.get.call(this); },
+ set(value) { tracked = String(value); native.set.call(this, value); },
+ });
+ return {
+ changed() {
+ const next = String(native.get.call(node));
+ if (next === tracked) return false;
+ tracked = next;
+ return true;
+ },
+ sync(value) { tracked = String(value); native.set.call(node, value); },
+ };
+ }
+
+ const box = document.querySelector("#controlled-checkbox");
+ const boxTracker = track(box);
+ function renderBox(checked) {
+ window.__fixtureState.controlledChecked = checked;
+ boxTracker.sync(checked);
+ }
+ box.addEventListener("click", () => {
+ if (!boxTracker.changed()) return;
+ window.__fixtureState.controlledChanges += 1;
+ renderBox(native.get.call(box));
+ });
+ renderBox(false);
+
+ const radios = Array.from(document.querySelectorAll("input[name='controlled-plan']"));
+ const radioTrackers = new Map(radios.map((radio) => [radio, track(radio)]));
+ function renderPlan(plan) {
+ window.__fixtureState.controlledPlan = plan;
+ for (const radio of radios) radioTrackers.get(radio).sync(radio.value === plan);
+ }
+ for (const radio of radios) {
+ radio.addEventListener("click", () => {
+ if (!radioTrackers.get(radio).changed()) return;
+ window.__fixtureState.controlledPlanChanges += 1;
+ renderPlan(radio.value);
+ });
+ }
+ renderPlan("");
+ })();
+
/* ---- context menu ---- */
document.querySelector("#context-menu-zone").addEventListener("contextmenu", (event) => {
event.preventDefault();
diff --git a/package/ego-browser/src/driver/keyboard.test.mjs b/package/ego-browser/src/driver/keyboard.test.mjs
index 55d7c1a..c6c31fb 100644
--- a/package/ego-browser/src/driver/keyboard.test.mjs
+++ b/package/ego-browser/src/driver/keyboard.test.mjs
@@ -343,25 +343,110 @@ test("focus resolves a selector and focuses the element", async () => {
assert.match(call.params.functionDeclaration, /this\.focus\(\)/);
});
-test("setChecked, check, and uncheck use Playwright-style checked state", async () => {
- const { calls, restore } = selectorCallHarness();
+// setChecked toggles through a real click, so the harness has to answer the
+// whole click path: handle resolution, the visibility gate, the click point,
+// and the checked reads that bracket it. `states` is the queue of checked
+// values those reads return; the last entry answers every later read.
+function checkedStateHarness(states) {
+ const calls = [];
+ const reads = [];
+ const queue = [...states];
+ const restore = setOverrides({
+ cdpOverride(method, params, sessionId) {
+ calls.push({ method, params, sessionId });
+ if (
+ method === "Runtime.evaluate" &&
+ params.objectGroup === "ego-browser"
+ ) {
+ return { result: { objectId: "object-1" } };
+ }
+ if (method === "Runtime.evaluate") {
+ return { result: { value: { x: 40, y: 60 } } };
+ }
+ if (method === "Runtime.callFunctionOn") {
+ const source = params.functionDeclaration;
+ if (source.includes("setChecked target must be")) {
+ reads.push(params.arguments);
+ return {
+ result: { value: queue.length > 1 ? queue.shift() : queue[0] },
+ };
+ }
+ if (source.includes("checkVisibility")) {
+ return { result: { value: true } };
+ }
+ }
+ return {};
+ },
+ });
+ return { calls, reads, restore };
+}
+
+test("setChecked toggles a checkbox with a real click, not a property write", async () => {
+ const { calls, restore } = checkedStateHarness([false, true]);
try {
await setChecked("#agree", true);
- await check("#agree");
- await uncheck("#agree");
} finally {
restore();
}
- const callsOnElement = calls.filter(
- (entry) => entry.method === "Runtime.callFunctionOn",
- );
- assert.equal(callsOnElement.length, 3);
assert.deepEqual(
- callsOnElement.map((entry) => entry.params.arguments),
- [[{ value: true }], [{ value: true }], [{ value: false }]],
+ calls
+ .filter((entry) => entry.method === "Input.dispatchMouseEvent")
+ .map((entry) => entry.params.type),
+ ["mouseMoved", "mousePressed", "mouseReleased"],
+ );
+ assert.ok(
+ calls
+ .filter((entry) => entry.method === "Runtime.callFunctionOn")
+ .every(
+ (entry) => !/this\.checked\s*=/.test(entry.params.functionDeclaration),
+ ),
+ "never assigns the checked property page-side",
+ );
+});
+
+test("setChecked skips the click when the state already matches", async () => {
+ const { calls, restore } = checkedStateHarness([true]);
+ try {
+ await setChecked("#agree", true);
+ } finally {
+ restore();
+ }
+
+ assert.equal(
+ calls.filter((entry) => entry.method === "Input.dispatchMouseEvent").length,
+ 0,
);
- assert.match(callsOnElement[0].params.functionDeclaration, /this\.checked/);
+});
+
+test("setChecked throws when the click leaves the state unchanged", async () => {
+ const { restore } = checkedStateHarness([false]);
+ try {
+ await assert.rejects(
+ () => setChecked("#agree", true),
+ /did not make it checked/,
+ );
+ } finally {
+ restore();
+ }
+});
+
+test("check and uncheck request the matching target state", async () => {
+ const { reads, restore } = checkedStateHarness([false, true]);
+ try {
+ await check("#agree");
+ } finally {
+ restore();
+ }
+ assert.deepEqual(reads[0], [{ value: true }]);
+
+ const unchecking = checkedStateHarness([true, false]);
+ try {
+ await uncheck("#agree");
+ } finally {
+ unchecking.restore();
+ }
+ assert.deepEqual(unchecking.reads[0], [{ value: false }]);
});
test("selectOption returns selected values", async () => {
diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.ts
index 61bbb4e..772df4f 100644
--- a/package/ego-browser/src/driver/keyboard.ts
+++ b/package/ego-browser/src/driver/keyboard.ts
@@ -1,6 +1,7 @@
import { cdp } from "../cdp-eval.js";
import { browserCdp } from "../browser-runtime.js";
import { withHandle, resolveAndCall } from "./element-ops.js";
+import { click } from "./pointer.js";
import { waitForSelector } from "./waits.js";
import { state } from "../state.js";
@@ -390,29 +391,47 @@ export async function uncheck(selector) {
await setChecked(selector, false);
}
+// Page-side guard shared by the read before the click and the read after it:
+// rejects non checkbox/radio targets and radio unchecking, then reports the
+// current state. One source string so both reads validate identically.
+const CHECKED_STATE_SOURCE = `function(checked){
+ if (!(this instanceof HTMLInputElement) || (this.type !== "checkbox" && this.type !== "radio")) {
+ throw new Error("setChecked target must be a checkbox or radio input");
+ }
+ if (this.type === "radio" && !checked) {
+ throw new Error("setChecked cannot uncheck a radio input");
+ }
+ return this.checked;
+}`;
+
/**
* Set the checked state of a checkbox or radio, Playwright-style.
+ *
+ * Toggles through a real click rather than assigning `this.checked`: an
+ * assignment updates the DOM property without the activation behavior a click
+ * runs, so frameworks that track the property (React's controlled inputs) never
+ * see a change and silently drop the update. The state is read back afterwards
+ * and a click that did not take throws instead of reporting success.
* @param {string} selector CSS selector / @ref / loc= / xpath= for the input.
* @param {boolean} checked Desired checked state.
* @returns {Promise<void>}
*/
export async function setChecked(selector, checked) {
- await resolveAndCall(
- selector,
- `function(checked){
- if (!(this instanceof HTMLInputElement) || (this.type !== "checkbox" && this.type !== "radio")) {
- throw new Error("setChecked target must be a checkbox or radio input");
- }
- if (this.type === "radio" && !checked) {
- throw new Error("setChecked cannot uncheck a radio input");
- }
- if (this.checked === checked) return;
- this.checked = checked;
- this.dispatchEvent(new Event("input", { bubbles: true }));
- this.dispatchEvent(new Event("change", { bubbles: true }));
- }`,
- [Boolean(checked)],
- );
+ const target = Boolean(checked);
+ if ((await readCheckedState(selector, target)) === target) return;
+ await click(selector);
+ if ((await readCheckedState(selector, target)) !== target) {
+ throw new Error(
+ `setChecked: clicking ${JSON.stringify(selector)} did not make it ${target ? "checked" : "unchecked"}`,
+ );
+ }
+}
+
+async function readCheckedState(selector, target: boolean) {
+ const { result } = await resolveAndCall(selector, CHECKED_STATE_SOURCE, [
+ target,
+ ]);
+ return result.result?.value;
}
/**
diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.ts
index 53d1f05..ba7fccf 100644
--- a/package/ego-browser/src/driver/pointer.ts
+++ b/package/ego-browser/src/driver/pointer.ts
@@ -553,13 +553,32 @@ async function dispatchSyntheticWheel(
/**
* Scroll an element into view only if it is not already fully visible,
* mirroring Playwright's locator.scrollIntoViewIfNeeded.
+ *
+ * The scroll is forced to be instant: under CSS `scroll-behavior: smooth` it is
+ * animated instead, and callers that read the element's position right after
+ * this — click() resolving its point, for one — would aim at where the element
+ * used to be. The override covers nested scroll containers too and is removed
+ * before returning.
* @param {string} selector CSS selector or @ref of the element to reveal.
* @returns {Promise<void>}
*/
export async function scrollIntoViewIfNeeded(selector: string) {
await resolveAndCall(
selector,
- "function(){ if (typeof this.scrollIntoViewIfNeeded === 'function') { this.scrollIntoViewIfNeeded(true); } else { this.scrollIntoView({ block: 'center', inline: 'center' }); } }",
+ `function(){
+ const override = document.createElement("style");
+ override.textContent = "*{scroll-behavior:auto !important}";
+ (document.head || document.documentElement).appendChild(override);
+ try {
+ if (typeof this.scrollIntoViewIfNeeded === "function") {
+ this.scrollIntoViewIfNeeded(true);
+ } else {
+ this.scrollIntoView({ block: "center", inline: "center" });
+ }
+ } finally {
+ override.remove();
+ }
+ }`,
);
}