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): let finish() close the blank anchor tab left by the last Page close

Zhuowei Wang4989ca382e4f
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
index d49a841..5ec1c23 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
@@ -153,6 +153,27 @@ export function taskSpaceCase() {
"task.finish closes unlisted Agent Pages"
);
await completeTaskSpace(finishSpaceId, { keep: false });
+
+ const anchorTask = await taskSpace(taskName + " v2 finish after last close");
+ const anchorSpaceId = anchorTask.spaceId;
+ await anchorTask.page("p1").goto(baseUrl + "/secondary?v2-lifecycle=last-close");
+ await anchorTask.page("p1").close();
+ const anchorTabs = await anchorTask.tabs();
+ assertEqual(anchorTabs.length, 1, "closing the last Page leaves one anchor tab");
+ assertEqual(anchorTabs[0].openedBy, "agent", "the anchor tab is SDK-owned");
+ const afterAnchorPage = await anchorTask.newPage();
+ await afterAnchorPage.goto(baseUrl + "/secondary?v2-lifecycle=after-anchor");
+ const anchorReceipt = await anchorTask.finish({ keep: [] });
+ assertEqual(anchorReceipt.closedSpace, true, "finish closes a space that only holds the anchor and Agent Pages");
+ assertEqual(anchorReceipt.preservedUnmanagedCount, 0, "the anchor tab is not reported as protected");
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ if (!(await listTaskSpaces()).some((space) => space.id === anchorSpaceId)) break;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ assert(
+ !(await listTaskSpaces()).some((space) => space.id === anchorSpaceId),
+ "task.finish removes the space after the last Page was closed and reopened"
+ );
`;
}
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index 5e711d1..7d549e9 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -562,9 +562,10 @@ await task.finish({ keep: [] }); // Default: keep no Agent-managed Pages.
await task.finish({ keep: ["p2"] }); // Exception: keep only the result Page for the user.
```
-User-created and unmanaged tabs are protected; if any remain, `keep: []` does
-not close the whole space. Do not close unwanted Pages one by one at completion;
-list the Pages to keep instead.
+User-created and unknown-origin tabs are protected; if any remain, `keep: []`
+does not close the whole space. The blank tab that `page.close()` leaves when it
+closes the last Page is SDK-owned and never blocks closing. Do not close
+unwanted Pages one by one at completion; list the Pages to keep instead.
Use `page.close()` only while the task is still in progress. Do not call
`finish()` when the task stops for user control or an error.
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index 6e086a5..22799d6 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -719,13 +719,13 @@ test("an explicitly unmanaged anchor is not adopted during reconciliation", asyn
await withTempLedger(async (rootDir) => {
const store = new PageLedgerStore({ rootDir });
await store.reconcile(10, [], { autoAdoptNew: true });
- await store.keepUnmanaged(10, "target-anchor", "unknown");
+ await store.keepUnmanaged(10, "target-anchor", "agent");
const reconciled = await store.reconcile(10, ["target-anchor"], {
autoAdoptNew: true,
});
assert.deepEqual(reconciled.pages, {});
- assert.equal(reconciled.unmanagedTargets["target-anchor"], "unknown");
+ assert.equal(reconciled.unmanagedTargets["target-anchor"], "agent");
});
});
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 10e7eba..1905c86 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -1599,6 +1599,158 @@ test("TaskSpace finish closes the whole space when no Pages are retained", async
});
});
+function finishFixtureTask(fixture, lifecycleCalls) {
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", {
+ ledger,
+ async completeTaskSpace() {
+ lifecycleCalls.push("finish");
+ },
+ async closeTaskSpace() {
+ lifecycleCalls.push("close");
+ },
+ });
+ return { ledger, task };
+}
+
+test("TaskSpace finish closes the space after the only Page was closed", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const { ledger, task } = finishFixtureTask(fixture, lifecycleCalls);
+ const p1 = await openTestPage(task, "https://example.test/one");
+ await p1.close();
+
+ const tabs = await task.tabs();
+ assert.equal(tabs.length, 1, "page.close leaves a blank anchor tab");
+ assert.equal(tabs[0].label, undefined, "the anchor stays unmanaged");
+ assert.equal(tabs[0].openedBy, "agent", "the anchor is SDK-owned");
+
+ const receipt = await task.finish({ keep: [] });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: true,
+ keptManagedLabels: [],
+ closedManagedLabels: [],
+ preservedUnmanagedCount: 0,
+ });
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ assert.deepEqual((await ledger.read(7)).pages, {});
+ });
+});
+
+test("TaskSpace finish closes the space when a new Page follows the last close", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const { task } = finishFixtureTask(fixture, lifecycleCalls);
+ const p1 = await openTestPage(task, "https://example.test/one");
+ await p1.close();
+ const p2 = await openTestPage(task, "https://example.test/two");
+ assert.equal(p2.label, "p2");
+ assert.equal((await task.tabs()).length, 2, "anchor and p2 are live");
+
+ const receipt = await task.finish({ keep: [] });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: true,
+ keptManagedLabels: [],
+ closedManagedLabels: ["p2"],
+ preservedUnmanagedCount: 0,
+ });
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ });
+});
+
+test("TaskSpace finish closes the SDK anchor tab when a Page is kept", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const { task } = finishFixtureTask(fixture, lifecycleCalls);
+ const p1 = await openTestPage(task, "https://example.test/one");
+ await p1.close();
+ const anchorTargetId = (await task.tabs())[0].targetId;
+ const p2 = await openTestPage(task, "https://example.test/two");
+
+ const receipt = await task.finish({ keep: ["p2"] });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: false,
+ keptManagedLabels: ["p2"],
+ closedManagedLabels: [],
+ preservedUnmanagedCount: 0,
+ });
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.equal(
+ fixture.tabs.has(anchorTargetId),
+ false,
+ "the anchor is closed",
+ );
+ assert.equal(fixture.tabs.has(p2.targetId), true, "the kept Page remains");
+ });
+});
+
+test("TaskSpace finish closes the SDK anchor tab but keeps user tabs", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const { ledger, task } = finishFixtureTask(fixture, lifecycleCalls);
+ const p1 = await openTestPage(task, "https://example.test/one");
+ await p1.close();
+ const anchorTargetId = (await task.tabs())[0].targetId;
+ fixture.addExternalTab("target-user", "https://example.test/user");
+ await ledger.keepUnmanaged(7, "target-user", "unknown");
+ const p2 = await openTestPage(task, "https://example.test/two");
+
+ const receipt = await task.finish({ keep: [] });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: false,
+ keptManagedLabels: [],
+ closedManagedLabels: ["p2"],
+ preservedUnmanagedCount: 1,
+ });
+ assert.equal(
+ fixture.tabs.has(p2.targetId),
+ false,
+ "the Agent Page is closed",
+ );
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.equal(
+ fixture.tabs.has(anchorTargetId),
+ false,
+ "the anchor is closed",
+ );
+ assert.equal(fixture.tabs.has("target-user"), true, "the user tab remains");
+ });
+});
+
+test("TaskSpace finish keeps an SDK anchor that is the last tab of a kept space", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const { task } = finishFixtureTask(fixture, lifecycleCalls);
+ const p1 = await openTestPage(task, "https://example.test/one");
+ await p1.close();
+ const anchorTargetId = (await task.tabs())[0].targetId;
+
+ const receipt = await task.finish({ keep: "all" });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: false,
+ keptManagedLabels: [],
+ closedManagedLabels: [],
+ preservedUnmanagedCount: 0,
+ });
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.equal(
+ fixture.tabs.has(anchorTargetId),
+ true,
+ "closing the last tab would destroy the space the caller kept",
+ );
+ });
+});
+
test("TaskSpace finish keeps protected unmanaged tabs even with an empty keep list", async () => {
await withFixture(async (fixture) => {
const lifecycleCalls = [];
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index b1fcdad..5a3157e 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1255,12 +1255,25 @@ class TaskSpace {
const keptManagedLabels = Object.keys(ledger.pages).filter(
(label) => !closedManagedLabelSet.has(label),
);
+ // Unmanaged tabs the SDK opened itself (the blank anchor page.close()
+ // leaves behind) belong to the agent: they are closed, not protected.
+ const agentUnmanagedTargets = tabs
+ .filter(
+ (tab) =>
+ !managedByTarget.has(tab.targetId) &&
+ ledger.unmanagedTargets[tab.targetId] === "agent",
+ )
+ .map((tab) => tab.targetId);
+ const agentUnmanagedSet = new Set(agentUnmanagedTargets);
const preservedUnmanagedCount = tabs.filter(
- (tab) => !managedByTarget.has(tab.targetId),
+ (tab) =>
+ !managedByTarget.has(tab.targetId) &&
+ !agentUnmanagedSet.has(tab.targetId),
).length;
const hasProtectedTabs = tabs.some((tab) => {
const managed = managedByTarget.get(tab.targetId);
- return !managed || managed.openedBy === "unknown";
+ if (managed) return managed.openedBy === "unknown";
+ return !agentUnmanagedSet.has(tab.targetId);
});
if (
@@ -1282,6 +1295,7 @@ class TaskSpace {
for (const label of labelsToClose) {
await this.page(label).close();
}
+ await this.#closeAgentUnmanagedTabs(agentUnmanagedTargets);
await this.#services.completeTaskSpace();
await this.#discardTerminalState();
return {
@@ -1294,6 +1308,42 @@ class TaskSpace {
});
}
+ /**
+ * Close SDK-opened unmanaged tabs (blank anchors) that the space no longer
+ * needs. A tab that is the last one in the space stays: closing it would
+ * destroy the space the caller chose to keep.
+ */
+ async #closeAgentUnmanagedTabs(targetIds: string[]): Promise<void> {
+ if (targetIds.length === 0) return;
+ let live = new Set(
+ (await this.#services.listTabs()).map((tab) => tab.targetId),
+ );
+ for (const targetId of targetIds) {
+ if (!live.has(targetId) || live.size <= 1) continue;
+ const result = await this.#services.cdp("Target.closeTarget", {
+ targetId,
+ });
+ if (result?.success !== true) {
+ throw new Error(`failed to close anchor tab ${targetId}`);
+ }
+ const disappeared = await waitForTargetToDisappear(
+ this.#services,
+ targetId,
+ PAGE_CLOSE_CONFIRM_TIMEOUT_MS,
+ );
+ if (!disappeared) {
+ throw new Error(
+ `anchor tab ${targetId} did not close within ${PAGE_CLOSE_CONFIRM_TIMEOUT_MS}ms`,
+ );
+ }
+ this.#services.invalidateSession(targetId);
+ this.#services.pageRefs.clear(targetId);
+ live = new Set(
+ (await this.#services.listTabs()).map((tab) => tab.targetId),
+ );
+ }
+ }
+
async [rollbackCreatedTaskSpaceToken](): Promise<void> {
await this.#services.gate.withSpace(this.spaceId, async () => {
await this.#services.closeTaskSpace();
@@ -2682,12 +2732,16 @@ class Page {
throw new Error(`page ${this.label} was closed`);
}
if (tabs.length <= 1) {
+ // Ego Lite destroys a task space when its last tab closes, so open a
+ // blank anchor first. It is SDK-owned: recording it as an agent-origin
+ // unmanaged tab keeps reconcile from adopting it as a managed Page and
+ // lets finish() close it instead of protecting it as a user tab.
const anchorTargetId = await this.#services.createTab("about:blank");
try {
await this.#services.ledger.keepUnmanaged(
this.spaceId,
anchorTargetId,
- "unknown",
+ "agent",
);
} catch (error) {
// The original page is still live, so a failed anchor bookkeeping