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): validate tab target lifecycles

0x0cecdd5e26e46
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index 37b56d8..f7c3aa6 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -28,6 +28,7 @@ import { playwrightUrlWaitCases } from "./playwright-url-waits.mjs";
import { playwrightPageUrlCases } from "./playwright-page-url.mjs";
import { playwrightPageInfoCases } from "./playwright-page-info.mjs";
import { playwrightLocatorCases } from "./playwright-locators.mjs";
+import { playwrightTargetCases } from "./playwright-targets.mjs";
export const e2eCases = [
{ name: "environment initialization", body: environmentCase },
@@ -62,4 +63,5 @@ export const e2eCases = [
...playwrightPageUrlCases,
...playwrightPageInfoCases,
...playwrightLocatorCases,
+ ...playwrightTargetCases,
];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/playwright-targets.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/playwright-targets.mjs
new file mode 100644
index 0000000..64a1118
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/playwright-targets.mjs
@@ -0,0 +1,48 @@
+import { homeCase } from "./shared.mjs";
+
+export const playwrightTargetCases = [
+ {
+ name: "regression PWB-07 stale target guard",
+ body: homeCase(`
+ const scratch = await browser.openOrReuseTab(
+ baseUrl + "/secondary?scratch=" + Date.now(),
+ { wait: true, timeout: 5000 }
+ );
+ assert(scratch?.targetId, "PWB-07 new tab returns targetId");
+ await browser.closeTab(scratch.targetId);
+ const refreshed = await browser.listTabs();
+ assert(
+ !refreshed.some((tab) => tab.targetId === scratch.targetId),
+ "PWB-07 closed target is absent from refreshed tabs"
+ );
+ await assertRejects(
+ () => browser.switchTab(scratch.targetId),
+ "switchTab target not found",
+ "PWB-07 stale target fails at the validated boundary"
+ );
+ `),
+ },
+ {
+ name: "regression PWB-08 target field guard",
+ body: homeCase(`
+ const tabs = await browser.listTabs();
+ assert(
+ tabs.every((tab) => typeof tab.targetId === "string" && tab.targetId.length > 0),
+ "PWB-08 listTabs exposes targetId"
+ );
+ const missing = tabs.find((tab) => tab.url.includes("/never-created-target"));
+ assertEqual(missing, undefined, "PWB-08 missing lookup is checked before dereference");
+ await assertRejects(
+ () => browser.switchTab({ id: tabs[0].targetId }),
+ "switchTab requires a targetId",
+ "PWB-08 id/targetId mismatch fails with an owned error"
+ );
+ const missingFrameTarget = await browser.iframeTarget("/never-created-frame");
+ assertEqual(
+ missingFrameTarget,
+ null,
+ "PWB-08 missing iframe target is an explicit nullable result"
+ );
+ `),
+ },
+];
diff --git a/package/ego-browser/src/driver/nav.test.mjs b/package/ego-browser/src/driver/nav.test.mjs
index 4deefa4..3a86286 100644
--- a/package/ego-browser/src/driver/nav.test.mjs
+++ b/package/ego-browser/src/driver/nav.test.mjs
@@ -13,6 +13,7 @@ import {
openOrReuseTab,
pageInfo,
closeTab,
+ switchTab,
} from "../../dist/src/driver/nav.js";
import { setOverrides, state } from "../../dist/src/state.js";
@@ -176,19 +177,140 @@ test("openOrReuseTab settles a newly opened tab in milliseconds, not seconds", a
assert.deepEqual(sleeps, [500]);
});
-test("closeTab closes an explicit target and returns its id", async () => {
+test("switchTab refreshes the target list and caches the selected URL", async () => {
const calls = [];
- const restore = setOverrides({
- cdpOverride(method, params, sessionId) {
- calls.push({ method, params, sessionId });
- return { success: true };
+ await withEgo(
+ {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "target-1",
+ active: true,
+ title: "Home",
+ url: "https://example.com/",
+ },
+ {
+ targetId: "target-2",
+ active: false,
+ title: "Docs",
+ url: "https://example.com/docs",
+ },
+ ],
+ };
+ },
},
- });
- try {
- assert.equal(await closeTab("target-2"), "target-2");
- } finally {
- restore();
- }
+ async () => {
+ const restore = setOverrides({
+ cdpOverride(method, params, sessionId) {
+ calls.push({ method, params, sessionId });
+ return { success: true };
+ },
+ });
+ try {
+ assert.equal(await switchTab({ targetId: "target-2" }), "target-2");
+ assert.equal(state.pageUrl, "https://example.com/docs");
+ assert.equal(state.pageUrlTargetId, "target-2");
+ } finally {
+ restore();
+ }
+ },
+ );
+
+ assert.deepEqual(calls, [
+ {
+ method: "Target.activateTarget",
+ params: { targetId: "target-2" },
+ sessionId: undefined,
+ },
+ ]);
+});
+
+test("switchTab rejects a stale target with the refreshed tab list", async () => {
+ let cdpCalled = false;
+ await withEgo(
+ {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "target-current",
+ active: true,
+ title: "Current",
+ url: "https://example.com/current",
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ const restore = setOverrides({
+ cdpOverride() {
+ cdpCalled = true;
+ return {};
+ },
+ });
+ try {
+ await assert.rejects(
+ () => switchTab("target-stale"),
+ (error) => {
+ assert.match(error.message, /switchTab target not found/);
+ assert.match(error.message, /target-stale/);
+ assert.match(error.message, /target-current/);
+ assert.match(error.message, /https:\/\/example\.com\/current/);
+ return true;
+ },
+ );
+ } finally {
+ restore();
+ }
+ },
+ );
+ assert.equal(cdpCalled, false);
+});
+
+test("switchTab rejects tab objects without targetId at the boundary", async () => {
+ await assert.rejects(
+ () => switchTab({ id: "target-2" }),
+ /switchTab requires a targetId.*received.*id/,
+ );
+});
+
+test("closeTab closes an explicit current target and returns its id", async () => {
+ const calls = [];
+ await withEgo(
+ {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "target-2",
+ active: true,
+ title: "Example",
+ url: "https://example.com/",
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ const restore = setOverrides({
+ cdpOverride(method, params, sessionId) {
+ calls.push({ method, params, sessionId });
+ return { success: true };
+ },
+ pageUrl: "https://example.com/",
+ pageUrlTargetId: "target-2",
+ });
+ try {
+ assert.equal(await closeTab("target-2"), "target-2");
+ assert.equal(state.pageUrl, "");
+ assert.equal(state.pageUrlTargetId, null);
+ } finally {
+ restore();
+ }
+ },
+ );
assert.deepEqual(calls, [
{
@@ -199,6 +321,97 @@ test("closeTab closes an explicit target and returns its id", async () => {
]);
});
+test("closeTab rejects a stale explicit target before CDP dispatch", async () => {
+ let cdpCalled = false;
+ await withEgo(
+ {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "target-current",
+ active: true,
+ title: "Current",
+ url: "https://example.com/current",
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ const restore = setOverrides({
+ cdpOverride() {
+ cdpCalled = true;
+ return {};
+ },
+ });
+ try {
+ await assert.rejects(
+ () => closeTab("target-stale"),
+ /closeTab target not found.*target-stale.*target-current/,
+ );
+ } finally {
+ restore();
+ }
+ },
+ );
+ assert.equal(cdpCalled, false);
+});
+
+test("closeTab waits for a closed target to disappear from listTabs", async () => {
+ let listCount = 0;
+ let now = 0;
+ const sleeps = [];
+ await withEgo(
+ {
+ async listTabs() {
+ listCount += 1;
+ const scratchStillListed = listCount < 3;
+ return {
+ tabs: [
+ {
+ targetId: "target-current",
+ active: !scratchStillListed,
+ title: "Current",
+ url: "https://example.com/current",
+ },
+ ...(scratchStillListed
+ ? [
+ {
+ targetId: "target-scratch",
+ active: true,
+ title: "Scratch",
+ url: "https://example.com/scratch",
+ },
+ ]
+ : []),
+ ],
+ };
+ },
+ },
+ async () => {
+ const restore = setOverrides({
+ cdpOverride: async () => ({ success: true }),
+ now: () => now,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ now += ms;
+ },
+ pageUrl: "https://example.com/scratch",
+ pageUrlTargetId: "target-scratch",
+ });
+ try {
+ assert.equal(await closeTab("target-scratch"), "target-scratch");
+ assert.deepEqual(sleeps, [50]);
+ assert.equal(state.pageUrl, "https://example.com/current");
+ assert.equal(state.pageUrlTargetId, "target-current");
+ } finally {
+ restore();
+ }
+ },
+ );
+});
+
test("closeTab closes the current tab and invalidates matching session state", async () => {
const calls = [];
await withEgo(
diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.ts
index 36b3d39..88c5f2e 100644
--- a/package/ego-browser/src/driver/nav.ts
+++ b/package/ego-browser/src/driver/nav.ts
@@ -9,7 +9,7 @@ import {
} from "../browser-runtime.js";
import { cdp, evaluate } from "../cdp-eval.js";
import { assertNoEgoError } from "../ego-errors.js";
-import { cachePageUrl, state } from "../state.js";
+import { cachePageUrl, clearPageUrl, state } from "../state.js";
import { waitForDocumentLoad } from "./load.js";
export const INTERNAL_URL_PREFIXES = [
@@ -155,10 +155,13 @@ export async function currentTab() {
* @returns {Promise<string>} Target id.
*/
export async function switchTab(target: string | { targetId: string }) {
- const targetId = typeof target === "object" ? target.targetId : target;
+ const targetId = targetIdFrom(target, "switchTab");
+ const tabs = await listTabs();
+ const tab = currentTargetFrom(tabs, targetId, "switchTab");
await cdp("Target.activateTarget", { targetId });
invalidateSession();
setPreferredTarget(targetId);
+ cachePageUrl(tab.url, targetId);
return targetId;
}
@@ -217,20 +220,24 @@ export async function openOrReuseTab(
* @returns {Promise<string>} Closed target id.
*/
export async function closeTab(target: TabTarget | undefined = undefined) {
+ const tabs = await listTabs();
const targetId =
target === undefined
- ? (await currentTab()).targetId
- : typeof target === "object"
- ? target.targetId
- : target;
- if (!targetId) {
- throw new Error("closeTab requires a targetId");
- }
+ ? (tabs.find((tab) => tab.active) || tabs[0])?.targetId
+ : targetIdFrom(target, "closeTab");
+ if (!targetId) throw new Error("closeTab requires a targetId");
+ currentTargetFrom(tabs, targetId, "closeTab");
await cdp("Target.closeTarget", { targetId });
invalidateSession();
if (state.preferredTargetId === targetId) {
clearPreferredTarget();
}
+ clearPageUrl(targetId);
+ if (tabs.length > 1) {
+ const remaining = await waitForClosedTarget(targetId);
+ const active = remaining.find((tab) => tab.active) || remaining[0];
+ if (active) cachePageUrl(active.url, active.targetId);
+ }
return targetId;
}
@@ -299,3 +306,51 @@ function tabMatchesUrl(tabUrl: string, wantedUrl: string, match: UrlMatchMode) {
function trimSlash(pathname: string) {
return pathname.replace(/\/+$/, "") || "/";
}
+
+function targetIdFrom(target: TabTarget, operation: string) {
+ const targetId =
+ typeof target === "string"
+ ? target
+ : target && typeof target === "object"
+ ? target.targetId
+ : undefined;
+ if (typeof targetId !== "string" || !targetId) {
+ throw new Error(
+ `${operation} requires a targetId; received ${JSON.stringify(target)}`,
+ );
+ }
+ return targetId;
+}
+
+function currentTargetFrom(
+ tabs: TabInfo[],
+ targetId: string,
+ operation: string,
+) {
+ const tab = tabs.find((candidate) => candidate.targetId === targetId);
+ if (tab) return tab;
+ const available = tabs.map(({ targetId, title, url }) => ({
+ targetId,
+ title,
+ url,
+ }));
+ throw new Error(
+ `${operation} target not found: ${JSON.stringify(targetId)}. ` +
+ `Refresh browser.listTabs() and select a current targetId. ` +
+ `Available tabs: ${JSON.stringify(available)}`,
+ );
+}
+
+async function waitForClosedTarget(targetId: string) {
+ const deadline = state.now() + 2000;
+ while (true) {
+ const tabs = await listTabs();
+ if (!tabs.some((tab) => tab.targetId === targetId)) return tabs;
+ if (state.now() >= deadline) {
+ throw new Error(
+ `closeTab timed out waiting for target to close: ${JSON.stringify(targetId)}`,
+ );
+ }
+ await state.sleep(50);
+ }
+}
diff --git a/package/ego-browser/src/format.ts b/package/ego-browser/src/format.ts
index 77f9fe2..730c728 100644
--- a/package/ego-browser/src/format.ts
+++ b/package/ego-browser/src/format.ts
@@ -582,8 +582,9 @@ const FUNCTION_DOCS: Record<string, FunctionDoc> = {
example: "console.log(await browser.currentTab())",
},
"browser.switchTab": {
- signature: "browser.switchTab(target) => Promise<object>",
- description: "Switch to a tab by target id or tab object.",
+ signature: "browser.switchTab(target) => Promise<string>",
+ description:
+ "Refresh the current tab list, validate a target id/tab object, then switch to that tab.",
params: [
{
name: "target",
@@ -592,8 +593,9 @@ const FUNCTION_DOCS: Record<string, FunctionDoc> = {
description: "Target id or tab object.",
},
],
- returns: "Promise<object>",
- example: "await browser.switchTab(targetId)",
+ returns: "Promise<string>",
+ example:
+ "const tab = (await browser.listTabs()).find(t => t.url.includes('/docs')); if (!tab) throw new Error('docs tab not found'); await browser.switchTab(tab.targetId)",
},
"browser.openOrReuseTab": {
signature: "browser.openOrReuseTab(url, options?) => Promise<object>",
@@ -618,7 +620,7 @@ const FUNCTION_DOCS: Record<string, FunctionDoc> = {
"browser.closeTab": {
signature: "browser.closeTab(target?) => Promise<string>",
description:
- "Close a tab by target id/object, or the current tab when omitted.",
+ "Refresh the current tab list, validate, and close a tab by target id/object, or close the current tab when omitted.",
params: [
{
name: "target",
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index ca437d4..a0814d7 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -805,7 +805,7 @@ const FACADE_HELP: Record<string, string> = {
locator:
"page.locator(selector): returns a strict, auto-waiting locator facade with locator(), getByRole(), getByText(), filter(), first(), nth(index), last(), click(), fill(value), clear(), press(key), check(), selectOption(value), textContent(), innerText(), innerHTML(), isVisible(), isEnabled(), getAttribute(name), screenshot(), count(), evaluate(fn, arg), evaluateAll(fn, arg), and waitFor(options). Narrow multiple matches; use first()/nth() only for confirmed legitimate duplicates.",
browser:
- "browser: tab facade. Use browser.listTabs(), browser.currentTab(), browser.switchTab(target), browser.openOrReuseTab(url, options), and browser.closeTab(target).",
+ "browser: tab facade. Use browser.listTabs(), browser.currentTab(), browser.switchTab(target), browser.openOrReuseTab(url, options), and browser.closeTab(target). Treat targetId as short-lived: obtain and validate it in the current script; switchTab/closeTab refresh the tab list before acting.",
taskSpaces:
"taskSpaces: task-space facade. Use taskSpaces.useOrCreate(nameOrId), taskSpaces.claim(nameOrId), taskSpaces.switch(nameOrId), taskSpaces.complete(nameOrId, options), taskSpaces.handOff(nameOrId), taskSpaces.takeOver(nameOrId), and taskSpaces.waitForAgentControl(nameOrId, options).",
site: "site: learned site-skill facade. Use site.skills(url), site.skillsForUrl(url), site.runTool(siteId, toolName, args), site.runBrowserTool(siteId, toolName, args), and site.learnContext(url).",
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 860cabe..910045f 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -118,6 +118,17 @@ When passing a string that may create a new task space, the string should reflec
**If the task space needs to be preserved after the task ends, keep only the tabs that need to be shown to the user.** Keep loose awareness of how many tabs are open — a quick `(await browser.listTabs()).length` is enough; there's no need to spend a dedicated round just to check. When scratch tabs (search-result pages, cross-check pages, and other one-off pages) pile up, close them as you go rather than letting them all accumulate for the end. When finishing with `{ keep: true }` to leave pages for the user, clear out the remaining scratch tabs so only the pages worth showing stay open. Close a single tab with `await browser.closeTab(targetId)` (`targetId` comes from `browser.listTabs()` or a `browser.openOrReuseTab` return value).
+Treat `targetId` as a short-lived handle. Obtain it from `browser.listTabs()`, `browser.currentTab()`, or `browser.openOrReuseTab()` in the current heredoc; never hardcode it, copy it by hand, rename it to `id`, or carry it across heredoc rounds. Before dereferencing a `find(...)` result, check that it exists. `browser.iframeTarget(...)` returns a target-id string or `null`, so validate the result directly instead of reading `.targetId` from it. `browser.switchTab(...)` and `browser.closeTab(...)` refresh and validate the tab list themselves, and their stale-target errors include the currently available tabs.
+
+```js
+const tabs = await browser.listTabs();
+const reportTab = tabs.find((tab) => tab.url.includes('/reports/'));
+if (!reportTab?.targetId) {
+ throw new Error('Report tab not found: ' + JSON.stringify(tabs));
+}
+await browser.switchTab(reportTab.targetId);
+```
+
### Control handoff
Only one side — agent or user — holds control of a task space at any time. While the user holds control, any browser operation by the agent fails with a "user is controlling" message — do not retry it; follow the steps below to resume.