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): close a claimed space with finish after keeping its tabs

Zhuowei Wang69ebd7cb20d7
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 5ec1c23..ff22ccb 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
@@ -152,7 +152,12 @@ export function taskSpaceCase() {
!retainedTabs.some((tab) => tab.url.includes("v2-lifecycle=discard")),
"task.finish closes unlisted Agent Pages"
);
- await completeTaskSpace(finishSpaceId, { keep: false });
+ assert(
+ retainedTabs.some((tab) => tab.url.includes("v2-lifecycle=retain") && tab.openedBy === "agent"),
+ "a claimed space remembers the tab the agent kept"
+ );
+ const reclaimedReceipt = await reclaimedFinishedTask.finish({ keep: [] });
+ assertEqual(reclaimedReceipt.closedSpace, true, "empty keep closes a claimed space holding only kept tabs");
const anchorTask = await taskSpace(taskName + " v2 finish after last close");
const anchorSpaceId = anchorTask.spaceId;
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index 0a2d9e1..112d628 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -522,9 +522,7 @@ reply:
```js
const task = await taskSpace(7); // the taskSpaceId printed earlier in this reply
-// Default: close the space. Close its Pages first: tabs you kept and adopted after
-// a claim read openedBy "unknown", so `keep: []` alone would leave them open.
-for (const page of await task.pages()) await page.close();
+// Default: close the space, including tabs you kept in an earlier reply.
await task.finish({ keep: [] });
// Exception, instead of the default: keep only the result Page for the user.
@@ -563,11 +561,12 @@ asks; the space you finished for the current goal is claimed as in "Starting
and ending a reply".
User-created and unknown-origin tabs are protected; if any remain, `keep: []`
-does not close the whole space. Tabs you kept and adopted after a claim also
-read `openedBy: "unknown"` but are yours, which is why the default close above
-closes the Pages first. The blank tab that `page.close()` leaves when it closes
-the last Page is SDK-owned and never blocks closing. Do not call `finish()` when
-the task stops for user control or an error.
+does not close the whole space, and the script output says so. Tabs you kept in
+an earlier reply stay yours after a claim and do not block closing. 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. Do not call `finish()` when the task stops for user
+control or an error.
If the final output contains `[ego-browser:notice]`, finish the current browser
task, tell the user an Ego Lite update is available, and run
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index b615daf..7359589 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -139,6 +139,7 @@ test("a newly created space atomically replaces stale state with agent page p1",
initialized: true,
userControlPending: false,
unmanagedTargets: {},
+ retainedTargets: [],
pages: {
p1: { targetId: "target-initial", openedBy: "agent" },
},
@@ -353,6 +354,7 @@ test("writes use a complete ledger document", async () => {
initialized: true,
userControlPending: false,
unmanagedTargets: {},
+ retainedTargets: [],
pages: {
p1: {
targetId: "target-a",
@@ -828,3 +830,23 @@ test("an explicitly unmanaged anchor is not adopted during reconciliation", asyn
assert.equal(reconciled.unmanagedTargets["target-anchor"], "agent");
});
});
+
+test("retained targets default to empty for ledgers from earlier runtimes", async () => {
+ const rootDir = await mkdtemp(join(tmpdir(), "ego-ledger-retained-test-"));
+ try {
+ const store = new PageLedgerStore({ rootDir });
+ await store.retainForUser(5, ["target-kept"]);
+ const retained = await store.read(5);
+ assert.deepEqual(retained.retainedTargets, ["target-kept"]);
+ assert.deepEqual(retained.unmanagedTargets, { "target-kept": "agent" });
+ assert.equal(retained.initialized, false);
+
+ const [file] = await readdir(rootDir);
+ const stored = JSON.parse(await readFile(join(rootDir, file), "utf8"));
+ delete stored.retainedTargets;
+ await writeFile(join(rootDir, file), JSON.stringify(stored));
+ assert.deepEqual((await store.read(5)).retainedTargets, []);
+ } finally {
+ await rm(rootDir, { recursive: true, force: true });
+ }
+});
diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.ts
index 8981271..0f956a9 100644
--- a/package/ego-browser/src/page-ledger.ts
+++ b/package/ego-browser/src/page-ledger.ts
@@ -35,6 +35,8 @@ export type PageLedger = {
initialized: boolean;
userControlPending: boolean;
unmanagedTargets: Record<string, PageOrigin>;
+ /** Agent tabs an earlier finish() left open for the user. */
+ retainedTargets: string[];
pages: Record<string, PageLedgerEntry>;
};
@@ -180,6 +182,23 @@ export class PageLedgerStore {
await this.#removeAll(await this.#listVersions(spaceId, browserInstanceId));
}
+ /**
+ * End a task whose space stays open for the user. Labels end with the task,
+ * but the origin of the tabs the agent left open survives so a later claim
+ * does not mistake them for user tabs. The ledger stays uninitialized: every
+ * other tab found at the claim is still treated as unknown.
+ */
+ async retainForUser(spaceId: number, targetIds: string[]): Promise<void> {
+ assertSpaceId(spaceId);
+ targetIds.forEach(assertTargetId);
+ const ledger = emptyLedger(spaceId, await this.#currentBrowserInstanceId());
+ for (const targetId of targetIds) {
+ ledger.unmanagedTargets[targetId] = "agent";
+ }
+ ledger.retainedTargets = [...targetIds];
+ await this.#writeLatest(spaceId, ledger);
+ }
+
async getPage(spaceId: number, label: string): Promise<ManagedPage> {
assertLabel(label);
const ledger = await this.read(spaceId);
@@ -363,6 +382,9 @@ export class PageLedgerStore {
for (const targetId of Object.keys(ledger.unmanagedTargets)) {
if (!live.has(targetId)) delete ledger.unmanagedTargets[targetId];
}
+ ledger.retainedTargets = ledger.retainedTargets.filter((targetId) =>
+ live.has(targetId),
+ );
const managedTargets = new Set(
Object.values(ledger.pages).map((page) => page.targetId),
@@ -712,6 +734,7 @@ function emptyLedger(spaceId: number, browserInstanceId?: string): PageLedger {
initialized: false,
userControlPending: false,
unmanagedTargets: {},
+ retainedTargets: [],
pages: {},
};
}
@@ -757,6 +780,7 @@ function validateLedger(
stored.userControlPending ??
(legacyHandoffBaseline !== undefined && legacyHandoffBaseline !== null);
const unmanagedTargets = stored.unmanagedTargets ?? {};
+ const retainedTargets = stored.retainedTargets ?? [];
if (
(stored.browserInstanceId !== undefined &&
(typeof stored.browserInstanceId !== "string" ||
@@ -789,6 +813,10 @@ function validateLedger(
targetId.length === 0 ||
!["agent", "user", "unknown"].includes(openedBy),
) ||
+ !Array.isArray(retainedTargets) ||
+ retainedTargets.some(
+ (targetId) => typeof targetId !== "string" || targetId.length === 0,
+ ) ||
!stored.pages ||
typeof stored.pages !== "object" ||
Array.isArray(stored.pages)
@@ -835,6 +863,7 @@ function validateLedger(
initialized,
userControlPending,
unmanagedTargets: normalizedUnmanagedTargets,
+ retainedTargets: [...retainedTargets],
pages,
};
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index e3a1b3c..9083f1d 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -18,6 +18,7 @@ import {
PageUnresponsiveError,
} from "../dist/src/browser-runtime.js";
import { PageLedgerStore } from "../dist/src/page-ledger.js";
+import { flushSink, resetSink } from "../dist/src/output-sink.js";
import {
captureTaskSpaceUserBoundary,
createTaskSpaceHandle,
@@ -1703,6 +1704,132 @@ test("TaskSpace finish closes the space when a new Page follows the last close",
});
});
+async function finishKeepingFirstPage(fixture, lifecycleCalls) {
+ const { task } = finishFixtureTask(fixture, lifecycleCalls);
+ const kept = await openTestPage(task, "https://example.test/kept");
+ await task.finish({ keep: [kept.label] });
+ lifecycleCalls.length = 0;
+ return kept.targetId;
+}
+
+function capturedRoundOutput() {
+ let output = "";
+ flushSink(
+ {
+ write(chunk) {
+ output += chunk;
+ },
+ },
+ false,
+ );
+ return output;
+}
+
+test("TaskSpace finish closes a claimed space holding only tabs the agent kept", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const keptTarget = await finishKeepingFirstPage(fixture, lifecycleCalls);
+
+ const { task: claimed } = finishFixtureTask(fixture, lifecycleCalls);
+ assert.equal(
+ (await claimed.pages()).length,
+ 0,
+ "labels ended with the task",
+ );
+ const receipt = await claimed.finish({ keep: [] });
+
+ assert.deepEqual(receipt, {
+ spaceId: 7,
+ closedSpace: true,
+ keptManagedLabels: [],
+ closedManagedLabels: [],
+ preservedUnmanagedCount: 0,
+ });
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ assert.ok(keptTarget);
+ });
+});
+
+test("TaskSpace finish protects a tab opened while the user owned the space", async () => {
+ await withFixture(async (fixture) => {
+ resetSink();
+ const lifecycleCalls = [];
+ const keptTarget = await finishKeepingFirstPage(fixture, lifecycleCalls);
+ fixture.addExternalTab("target-user", "https://example.test/user");
+
+ const { task: claimed } = finishFixtureTask(fixture, lifecycleCalls);
+ const origins = Object.fromEntries(
+ (await claimed.tabs()).map((tab) => [tab.targetId, tab.openedBy]),
+ );
+ assert.deepEqual(origins, {
+ [keptTarget]: "agent",
+ "target-user": "unknown",
+ });
+ const receipt = await claimed.finish({ keep: [] });
+
+ assert.equal(receipt.closedSpace, false);
+ assert.equal(receipt.preservedUnmanagedCount, 1);
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.equal(fixture.tabs.has(keptTarget), false, "the kept tab is closed");
+ assert.equal(fixture.tabs.has("target-user"), true, "the user tab remains");
+ assert.match(
+ capturedRoundOutput(),
+ /did not close task space 7: 1 tab\(s\) of user or unknown origin/,
+ );
+ resetSink();
+ });
+});
+
+test("TaskSpace finish leaves earlier kept tabs open unless it keeps nothing", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const keptTarget = await finishKeepingFirstPage(fixture, lifecycleCalls);
+
+ const { task: second } = finishFixtureTask(fixture, lifecycleCalls);
+ const secondPage = await openTestPage(second, "https://example.test/two");
+ const receipt = await second.finish({ keep: [secondPage.label] });
+ assert.equal(receipt.closedSpace, false);
+ assert.equal(
+ fixture.tabs.has(keptTarget),
+ true,
+ "named keep does not close it",
+ );
+
+ const { task: third } = finishFixtureTask(fixture, lifecycleCalls);
+ const keepAll = await third.finish({ keep: "all" });
+ assert.equal(keepAll.closedSpace, false);
+ assert.equal(
+ fixture.tabs.has(keptTarget),
+ true,
+ "keep all does not close it",
+ );
+
+ lifecycleCalls.length = 0;
+ const { task: last } = finishFixtureTask(fixture, lifecycleCalls);
+ const closing = await last.finish({ keep: [] });
+ assert.equal(closing.closedSpace, true, "origin survives repeated rounds");
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ });
+});
+
+test("TaskSpace finish closes a claimed space after its kept tab is adopted", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const keptTarget = await finishKeepingFirstPage(fixture, lifecycleCalls);
+
+ const { task: claimed } = finishFixtureTask(fixture, lifecycleCalls);
+ const [tab] = await claimed.tabs();
+ assert.equal(tab.targetId, keptTarget);
+ const adopted = await claimed.adopt(tab.page);
+ assert.equal(adopted.openedBy, "agent");
+
+ const receipt = await claimed.finish({ keep: [] });
+ assert.equal(receipt.closedSpace, true);
+ assert.deepEqual(receipt.closedManagedLabels, [adopted.label]);
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ });
+});
+
test("TaskSpace finish closes the SDK anchor tab when a Page is kept", 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 eca79d9..f2b321f 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -120,6 +120,7 @@ import {
subscribeUnhandledPageNotices,
type UnhandledPageNotice,
} from "./page-discovery.js";
+import { bufferOutput } from "./output-sink.js";
import {
publicApiEntry,
validatePublicApiOptions,
@@ -447,6 +448,7 @@ type OperationGate = {
type LedgerPort = {
read(spaceId: number): Promise<PageLedger>;
discard(spaceId: number): Promise<void>;
+ retainForUser(spaceId: number, targetIds: string[]): Promise<void>;
initializeCreatedSpace(
spaceId: number,
targetId: string,
@@ -1296,17 +1298,14 @@ class TaskSpace {
!managedByTarget.has(tab.targetId) &&
!agentUnmanagedSet.has(tab.targetId),
).length;
- const hasProtectedTabs = tabs.some((tab) => {
+ const protectedTabCount = tabs.filter((tab) => {
const managed = managedByTarget.get(tab.targetId);
if (managed) return managed.openedBy === "unknown";
return !agentUnmanagedSet.has(tab.targetId);
- });
+ }).length;
+ const keepsNothing = options.keep !== "all" && options.keep.length === 0;
- if (
- options.keep !== "all" &&
- options.keep.length === 0 &&
- !hasProtectedTabs
- ) {
+ if (keepsNothing && protectedTabCount === 0) {
await this.#services.closeTaskSpace();
await this.#discardTerminalState();
return {
@@ -1321,9 +1320,30 @@ class TaskSpace {
for (const label of labelsToClose) {
await this.page(label).close();
}
- await this.#closeAgentUnmanagedTabs(agentUnmanagedTargets);
+ // Tabs an earlier finish() left for the user go only when this finish
+ // keeps nothing; a keep list can only name labels, so it cannot cover them.
+ const retainedEarlier = new Set(
+ keepsNothing ? [] : ledger.retainedTargets,
+ );
+ const anchorsLeftOpen = await this.#closeAgentUnmanagedTabs(
+ agentUnmanagedTargets.filter((id) => !retainedEarlier.has(id)),
+ );
await this.#services.completeTaskSpace();
- await this.#discardTerminalState();
+ await this.#discardTerminalState([
+ ...keptManagedLabels
+ .map((label) => ledger.pages[label])
+ .filter((page) => page.openedBy === "agent")
+ .map((page) => page.targetId),
+ ...agentUnmanagedTargets.filter((id) => retainedEarlier.has(id)),
+ ...anchorsLeftOpen,
+ ]);
+ if (keepsNothing) {
+ bufferOutput(
+ `[ego-browser] finish({ keep: [] }) did not close task space ${this.spaceId}: ` +
+ `${protectedTabCount} tab(s) of user or unknown origin stayed open, ` +
+ "and the space now belongs to the user.\n",
+ );
+ }
return {
spaceId: this.spaceId,
closedSpace: false,
@@ -1337,15 +1357,20 @@ 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.
+ * destroy the space the caller chose to keep. Returns the tabs left open.
*/
- async #closeAgentUnmanagedTabs(targetIds: string[]): Promise<void> {
- if (targetIds.length === 0) return;
+ async #closeAgentUnmanagedTabs(targetIds: string[]): Promise<string[]> {
+ if (targetIds.length === 0) return [];
+ const leftOpen: string[] = [];
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;
+ if (!live.has(targetId)) continue;
+ if (live.size <= 1) {
+ leftOpen.push(targetId);
+ continue;
+ }
const result = await this.#services.cdp("Target.closeTarget", {
targetId,
});
@@ -1368,6 +1393,7 @@ class TaskSpace {
(await this.#services.listTabs()).map((tab) => tab.targetId),
);
}
+ return leftOpen;
}
async [rollbackCreatedTaskSpaceToken](): Promise<void> {
@@ -1377,9 +1403,13 @@ class TaskSpace {
});
}
- async #discardTerminalState(): Promise<void> {
+ async #discardTerminalState(retainedTargets: string[] = []): Promise<void> {
this.#finished = true;
- await this.#services.ledger.discard(this.spaceId);
+ if (retainedTargets.length > 0) {
+ await this.#services.ledger.retainForUser(this.spaceId, retainedTargets);
+ } else {
+ await this.#services.ledger.discard(this.spaceId);
+ }
this.#stopBackgroundPageDiscovery();
clearSpacePageNotices(this.spaceId);
}