Skip to content

2026 11 18 tabs

Kelly Ferrone edited this page Nov 18, 2026 · 4 revisions

Tabs and popups Implementation Plan

History. Drafted 2026-11-18 for #178 from the tabs design. Built as written, in eight tasks: core/tabs.py and Actions.check_tabs, the tab action on every surface, the context's tabs, the skill and a live flow. Its requirements are ACT-45 to ACT-53, WS-76 and FLOW-59. Measured on the cluster Grid: Chrome 152.0.7977.82 and Firefox 155.0.1 both answer yes to handle-is-context, switch-fronts and switch-brings-back (also after a person's activate of the first tab), so FRONT_BY_ACTIVATE is False. The final review's fixes undid that: a switch to the window the session is on throws away its frame, and Chrome holds window_handles behind a loading popup, so the current tab comes to the front only by browsingContext.activate, the tabs are listed by getTree, and open_session numbers its tab.

For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: A session follows the popups its pages open, comes back when the current tab closes, and lists, opens, switches and closes tabs with one tab action on every surface.

Architecture: Tab state lives per browser in the store under the Grid session id, beside the workspace record and never in it. One method, Actions.check_tabs, reconciles the browser's window handles with that state, follows when it must and says what changed. Every host of a call (Workspaces._said, the bound write in secrets.perform_write, the flow engine) runs it before the call reads its origin and again after the call, and merges what changed into the result before the scrub notes the URL. tab is an ordinary capability row and Actions method.

Tech Stack: Python 3.11+, Selenium 4 classic WebDriver (window handles), WebDriver BiDi through bidi/ (browsingContext.getTree, script.evaluate, browsingContext.activate), FastMCP, pytest, ruff.

Spec: the tabs design; ACT-45 to ACT-53 (with ACT-12, ACT-42) in browser-actions.md, WS-76 (with WS-43, WS-64) in workspaces-and-sessions.md, FLOW-59 (with FLOW-7) in saved-flows.md, SEC-40 in secrets-and-scope.md.

Global Constraints

  • Python 3.11+: from __future__ import annotations in every new module; ruff check . clean (target py311).
  • Tests: pytest -q tests/<file>.py for the task, then pytest -q (the unit suite) before each commit. The integration suite needs GRID_URL and ADMIN_ORIGIN and runs in CI.
  • Commits: stage exact paths, never git commit -a. Every message ends with the line Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>.
  • The spec and the wiki are docs/, the wiki's own repository, on its branch feat/tabs. A task that edits docs/ commits there first (never on master), then commits the docs pointer in the repo in the same task.
  • When a requirement is built, its (proposed) tag comes off in the same task. Spec text is statements only, no dates or issue numbers.
  • No personal names, emails or hostnames in code, tests, docs or commits. Examples use example.com; tests use example.test as the suite does.
  • A golden is regenerated only for a meant contract change, in a commit of its own: GOLDEN_UPDATE=1 pytest -q tests/test_golden.py, then read the diff.
  • Generated wiki pages (one per tool, Actions.md, Configuration.md) come from python scripts/generate_wiki.py, never by hand.
  • In mcp/tools.py only tab's declaration and docstring are new; no other tool description changes.
  • Layers hold (tests/test_boundaries.py): Selenium calls stay in core/actions.py and core/browser.py; core/tabs.py imports no Selenium and no protocol layer.
  • A failure's status comes from errors.status_for alone. No log line carries a Grid id, a URL or a title; log a failure by type(exc).__name__.
  • Use the shared doubles in tests/fakes.py and tests/conftest.py; extend them, never copy them.
  • Never edit .github/.
  • Values: a tab id is t<n>, from t1, never reused while that browser lives. The store key is <REDIS_PREFIX>tabs:<grid session id> (default selenium-flow:workspace:tabs:<id>), with the workspace store's ttl (WORKSPACE_TTL, default 86400). A title read waits at most bidi.REPLY_TIMEOUT (5.0 s).
  • Out of scope: the admin UI, separate windows (open makes a tab), the BiDi action layer and transport setting (#177), filtering capture by tab.

Review Focus

  1. A secret echoed in another tab's URL or title leaks: a call is scrubbed only with the origins before and after it, and tab list and opened carry other tabs' pages. Pinned by test_tab_list_is_scrubbed_with_every_leashed_secret (Task 5) and test_an_opened_popups_url_is_scrubbed_with_every_leashed_secret (Task 4), and for flows by test_a_steps_opened_url_is_scrubbed_with_every_leashed_secret (Task 6).
  2. A secret typed into the opener instead of the sign-in popup: the bound write is a third host that bypasses _said. Pinned by test_a_bound_write_after_a_popup_opened_types_into_the_popup (Task 4).
  3. The noted frame goes wrong after a move: a move before a frame call overrides that call's own in_frame: true, or a move never clears the noted frame and every later call is scrubbed as framed. Pinned by test_a_frame_results_own_in_frame_wins_over_a_move_before_it (Task 2) and test_a_move_clears_the_noted_frame (Task 4).
  4. Following while a person holds the browser pulls their view to another tab. Pinned by test_no_tab_is_brought_to_front_while_a_person_holds_the_browser (Task 3).
  5. Server-made tabs read as popups: a spare tab from a site-data save, or every existing tab on the first check of a browser opened before this release. Pinned by test_a_tab_opened_and_closed_inside_one_call_is_never_reported (Task 3) and test_the_first_sight_of_a_browser_numbers_its_tabs_and_reports_nothing (Task 2).

File Structure

File Responsibility
kubed/selenium_flow/core/tabs.py (new) Tab state, its two stores, reconcile (the following rules), merged (a call's result plus both checks), FRONT_BY_ACTIVATE
kubed/selenium_flow/workspace/store.py TABS_NAMESPACE; RedisStore.records skips it
kubed/selenium_flow/core/actions.py Actions(tabs=…), check_tabs, _front, _contexts, _listed, tab, tabs_listed, TAB_ACTIONS; end_browser forgets the state
kubed/selenium_flow/core/capabilities.py TAB_HINTS in every page response; the tab row
kubed/selenium_flow/faults.py, spec/builder.py TabClosed (409), window_gone; the actions' 409 description
kubed/selenium_flow/workspace/workspaces.py followed; the bracket in _said; scrub origins in _scrubbed and in_scope; tabs in the context
kubed/selenium_flow/secrets.py the bracket in perform_write
kubed/selenium_flow/flows/engine.py, flows/api.py Hooks.tabs, called around each step; wired to Workspaces.followed
kubed/selenium_flow/flows/document.py concerns reads tab's url as a page only for open
kubed/selenium_flow/mcp/tools.py, server.py the tab declaration; the tab store wired to the workspace store's backend
kubed/selenium_flow/spec/schemas.py tabs in the context's schema
plugin/skills/selenium-flow/…, docs/…, CHANGELOG.md the skill, the wiki, the spec tags, the release line
tests/test_tabs.py (new), tests/test_tabs_following.py (new) the rules and Actions over a ScriptedDriver; the hosts over TabbedActions
tests/integration/flows/follow-a-popup.yaml (new) a real browser's popup, followed and left

Requirements to tasks: ACT-46 → 2, 3; ACT-49 → 3, 4, 6; ACT-50, ACT-51, ACT-52, ACT-53, SEC-40 → 4; ACT-45, ACT-47, ACT-48 → 5; FLOW-59 → 6; WS-76 → 7; the skill and the tool description → 5, 8.


Task 1: Measure the Grid's browsers

Two facts the design leaves to the builder: whether a classic window handle is its BiDi context id, and whether switch_to.window brings a tab to the front, also back from a tab a person brought forward. The code maps handles to contexts at run time either way (Task 3, Task 5); this task fixes FRONT_BY_ACTIVATE.

Files:

  • Create (scratch, never committed): stuff/tabs_spike.py
  • Modify: docs/superpowers/plans/2026-11-18-tabs.md (the History header only)

Interfaces:

  • Produces: the value of core.tabs.FRONT_BY_ACTIVATE: bool for Task 3; a History sentence with the measurements.

  • Step 1: Write the script. It builds Grid(os.environ["GRID_URL"]), Actions(grid) with actions.channels = Channels(grid.bidi_url), and for browser in ("chrome", "firefox"): opened = actions.open_session(browser=browser); driver = grid.reconnect(opened["session_id"]); driver.execute_script("window.open('about:blank#two')"); then over one channel:

    • handle_is_context: set(driver.window_handles) == {c["context"] for c in getTree({"maxDepth": 0})["contexts"]};
    • switch_fronts: after driver.switch_to.window(second), script.evaluate of document.visibilityState is "visible" in the second context and "hidden" in the first;
    • switch_brings_back: after browsingContext.activate on the first context (a person's click), driver.switch_to.window(second) makes the second "visible" again.

    It prints one JSON line per browser with those three booleans and opened["ran"]["version"], and ends each browser with actions.end_browser in a finally.

  • Step 2: Run it. Run: GRID_URL=<the Grid this pod reaches> python stuff/tabs_spike.py. Expected: two JSON lines. Grid nodes may scale from zero, so allow minutes for the first open. If no node takes a session (NoNodeTook, or no answer in 10 minutes), the result is "not measured".

  • Step 3: Decide. FRONT_BY_ACTIVATE = not (switch_fronts and switch_brings_back) on both browsers. Not measured: True. Activation is harmless when redundant.

  • Step 4: Record. Add one sentence to this plan's History header: each browser's version and three answers, and the value chosen. If handle_is_context is false anywhere, add that ACT-47's nulls are what list answers there.

  • Step 5: Commit the plan in docs/ (docs: tabs plan, Grid measurements), then the docs pointer in the repo.

Task 2: Tab state, its store and the following rules

Files:

  • Create: kubed/selenium_flow/core/tabs.py
  • Modify: kubed/selenium_flow/workspace/store.py (TABS_NAMESPACE, RedisStore.records)
  • Test: tests/test_tabs.py

Interfaces:

  • Produces:

    • Known(tab: str, handle: str, from_: str | None) (frozen; JSON key from), and TabState(next: int, current: str, known: tuple[Known, ...]) with to_json() -> str, TabState.from_json(raw: str | bytes) -> TabState | None (None when unreadable), by_id(tab: str) -> Known | None, by_handle(handle: str) -> Known | None and newest() -> Known (highest id).
    • Reconciled(NamedTuple): state: TabState, opened: list[str], closed: list[str], moved: bool, handle: str (the current tab's handle).
    • reconcile(state: TabState | None, handles: list[str], current_handle: str | None = None) -> Reconciled.
    • merged(result, before: dict, after: dict): result, with both checks' changes in place.
    • MemoryTabs(ttl: int = DEFAULT_TTL_SECONDS, clock=time.time) and RedisTabs(client, prefix: str, ttl: int), each with get(session_id) -> TabState | None, set(session_id, state) -> None, forget(session_id) -> None; matching(store) builds one on the workspace store's backend, as pointer.matching does. Redis failures raise; nothing swallows them.
    • store.TABS_NAMESPACE = "tabs:".
  • Step 1: Write the failing tests in tests/test_tabs.py:

    def test_the_first_sight_of_a_browser_numbers_its_tabs_and_reports_nothing():
        r = reconcile(None, ["h1", "h2"], "h2")
        assert [k.tab for k in r.state.known] == ["t1", "t2"] and r.state.next == 3
        assert r.state.current == "t2" and (r.opened, r.closed, r.moved) == ([], [], False)
    
    def test_a_seed_whose_current_window_is_gone_moves_to_the_newest():
        r = reconcile(None, ["h1", "h2"], "gone")
        assert (r.state.current, r.moved, r.handle) == ("t2", True, "h2")
    
    def test_a_new_handle_gets_the_next_id_and_becomes_current():  # t1/h1 current, next 2
        r = reconcile(ONE, ["h1", "h9"])
        assert r.opened == ["t2"] and r.state.by_id("t2").from_ == "t1"
        assert (r.state.current, r.moved, r.handle) == ("t2", True, "h9")
    
    def test_handles_first_seen_together_are_numbered_in_listed_order(): ...
        # ONE + ["h1", "hB", "hA"]: t2 is hB, t3 is hA, current t3
    def test_ids_are_never_reused(): ...
        # t1, t2 (next 3); t2 closes; a new handle is t3
    def test_when_the_current_tab_closes_the_session_goes_back_to_where_it_came_from(): ...
        # t1; t2 from t1; t3 from t2, current; t3 closes: current t2, closed ["t3"]
    def test_when_that_tab_is_gone_too_the_newest_left_is_current(): ...
        # t1; t2 from t1; t3 from t2, current; t4 from t1; t2 and t3 close: current t4
    def test_a_new_tab_wins_over_a_closed_current(): ...
    def test_nothing_changed_is_no_move(): ...

    merged:

    def test_merged_adds_nothing_when_nothing_changed():
        assert merged({"url": A}, {}, {}) == {"url": A}
    
    def test_a_move_after_the_call_replaces_url_and_title_and_clears_the_frame():
        after = {"opened": [{"tab": "t2", "url": P}], "tab": "t2", "url": P,
                 "title": "Sign in", "in_frame": False}
        assert merged({"url": A, "title": "Shop", "in_frame": True}, {}, after) == {
            "url": P, "title": "Sign in", "in_frame": False, "tab": "t2",
            "opened": [{"tab": "t2", "url": P}]}
    
    def test_a_frame_results_own_in_frame_wins_over_a_move_before_it():
        before = {"tab": "t2", "url": P, "title": "Sign in", "in_frame": False}
        out = merged({"url": P, "in_frame": True}, before, {})
        assert out["in_frame"] is True and out["tab"] == "t2"
    
    def test_a_move_before_the_call_says_in_frame_false_when_the_call_did_not(): ...
        # result {"url": P}, before as above -> in_frame False; url stays the result's
    def test_opened_and_closed_join_both_checks_in_order(): ...
    def test_a_result_that_is_not_a_dict_is_left_alone(): ...

    Stores:

    @pytest.mark.parametrize("kind", ["memory", "redis"])
    def test_tab_state_round_trips(kind): ...          # set, get equal; forget -> None
    def test_memory_tab_state_expires_with_the_ttl(): ...  # Clock advanced past ttl -> None
    def test_redis_tab_state_is_kept_under_the_workspace_prefix():
        fake = FakeRedis(); tabs = matching(RedisStore(fake))
        tabs.set("abc", STATE)
        assert fake.expiries["selenium-flow:workspace:tabs:abc"] == 86400
    def test_records_skip_tab_state(): ...  # RedisStore(fake).records() has no "tabs:abc"
  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_tabs.py. Expected: FAIL with ModuleNotFoundError: kubed.selenium_flow.core.tabs.

  • Step 3: Implement core/tabs.py. reconcile's rules, in order:

    1. No state: number handles in their order t1…tn, from None, next n+1. Current is current_handle's tab, else the newest, which is a move. Nothing is opened or closed.
    2. Closed: the known tabs whose handle is not in handles, in id order. They leave known.
    3. Opened: each handle not known, in the order listed, takes t{next} and from = the state's current (even when that one just closed).
    4. Current: the newest opened tab when any opened. Else, when the current one closed, its from if still open, else the newest left. Else unchanged. moved is whether it changed.

    merged: opened and closed concatenate before's then after's, and are set only when non-empty. When after moved, tab, url, title come from after and in_frame is False. When only before moved, tab comes from it and in_frame is False unless the result carries its own. tab is absent when neither moved. The stores copy pointer.MemoryPointers/RedisPointers (JSON value, ex=ttl on every set), except that failures raise. In store.py, records() skips prefix + TABS_NAMESPACE as it skips POINTER_NAMESPACE.

  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_tabs.py && pytest -q && ruff check .

  • Step 5: Commit core/tabs.py, workspace/store.py, tests/test_tabs.py: tabs: per-browser tab state and the following rules.

Task 3: Actions.check_tabs, and the current tab in front

Files:

  • Modify: kubed/selenium_flow/core/actions.py (Actions.__init__, check_tabs, _front, _contexts, end_browser), kubed/selenium_flow/core/tabs.py (FRONT_BY_ACTIVATE), kubed/selenium_flow/server.py (tabs=tabs.matching(self.store) beside pointers)
  • Modify (doubles): tests/fakes.py (ScriptedDriver, _ScriptedSwitch, ScriptedElement, FakeChannel, FakeActions, WorkspaceActions, new TabbedActions), tests/conftest.py (RecordingActions), tests/test_capture_open.py (FakeActions), tests/test_recording_open.py (Actions)
  • Test: tests/test_tabs.py
  • Spec: ACT-46 drops (proposed)

Interfaces:

  • Consumes: Task 2's reconcile, TabState, matching, MemoryTabs.

  • Produces:

    • Actions(grid, keep=None, pointers=None, read_file=None, tabs=None); self.tabs defaults to MemoryTabs().
    • Actions.check_tabs(session_id: str) -> dict, with keys only when they hold something: opened: list[{"tab", "url"}], closed: list[str], and on a move tab, url, title, in_frame: False.
    • Actions._front(session_id: str, driver, handle: str) -> None and Actions._contexts(session_id: str) -> dict[str, str] | None (context id → URL from one getTree, None when BiDi cannot answer).
    • check_tabs(self, session_id) -> dict returning {} on every Actions double listed above. TabbedActions(RecordingActions) in tests/fakes.py: checks: list[dict], popped by each check_tabs ({} when empty, raised when an exception), calls: list[str] naming each method in order, result, do(session_id), page, write, tab, tabs_listed.
    • ScriptedDriver: pages: dict[handle, (url, title)] (default {"w1": (url, title)}) and current: str; window_handles, current_window_handle, close(), switch_to.window(h) and switch_to.new_window("tab") (adds w<n>), each logged. current_url/title read the current handle's page and raise NoSuchWindowException once it is closed. element.on_click, run after a click, lets a click open or close a tab. FakeChannel: tree (a list of {"context", "url"} answered by getTree), titles (context → title for a script.evaluate of document.title) and _browsingContext_activate.
  • Step 1: Write the failing tests (tests/test_tabs.py, using the scripted fixture and site_data_fakes.channels_for(FakeChannel(...))):

    def test_a_check_on_one_tab_asks_the_browser_once(actions, scripted):
        driver = scripted()
        assert actions.check_tabs("abc") == {} and actions.check_tabs("abc") == {}
        assert driver.names().count("window_handles") == 2
        assert ("switch_to", "window", "w1") not in driver.log
    
    def test_a_popup_is_followed_and_reported(actions, scripted):
        driver = scripted(); actions.check_tabs("abc")
        driver.pages["w2"] = ("https://sso.example/login", "Sign in")
        assert actions.check_tabs("abc") == {
            "opened": [{"tab": "t2", "url": "https://sso.example/login"}],
            "tab": "t2", "url": "https://sso.example/login", "title": "Sign in",
            "in_frame": False}
        assert ("switch_to", "window", "w2") in driver.log
    
    def test_a_closed_current_tab_moves_back_to_its_opener(...): ...
        # after the popup, w2 closes -> {"closed": ["t2"], "tab": "t1", "url": ..., "title": ..., "in_frame": False}
    def test_the_moved_to_tab_is_brought_to_front(..., monkeypatch): ...
        # FRONT_BY_ACTIVATE True: channel.params("browsingContext.activate") == {"context": "w2"}
        # False: a second ("switch_to", "window", "w2") and no activate
    def test_with_several_tabs_every_check_brings_the_current_one_back_to_front(...): ...  # ACT-52
    def test_no_tab_is_brought_to_front_while_a_person_holds_the_browser(...): ...
        # actions.control.refusal(...) answers a Controlled: the popup is still followed
        # (switch_to.window w2), and no activate is sent
    def test_a_tab_opened_and_closed_inside_one_call_is_never_reported(...): ...
        # a save_site_data whose spare context opens and closes between two checks -> {}
    def test_a_bidi_failure_never_fails_a_check(...): ...
        # getTree and activate down; two popups at once: the followed one's url from
        # classic, the other's None
    def test_ending_a_browser_forgets_its_tabs(actions, scripted): ...  # tabs.get("abc") is None
    def test_a_browser_with_no_tab_left_is_a_404(actions, scripted): ...  # NotFound, status_for 404
  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_tabs.py. Expected: FAIL with AttributeError: 'Actions' object has no attribute 'check_tabs'.

  • Step 3: Implement.

    • check_tabs, under node_answering(): reconnect, then read driver.window_handles. Empty means faults.NotFound("the browser has no tab left: end_browser ends it"). current_window_handle is read only when there is no state. Call reconcile. On a move: driver.switch_to.window(r.handle), read the page with browser.page_state, then _front. With no move and more than one handle, _front the current handle anyway (ACT-52). self.tabs.set on every check, which slides the TTL. The followed tab's URL comes from that page; any other opened tab's comes from _contexts, which is asked only then, else None.
    • _front: nothing when self.control refuses "tab" for the session. With FRONT_BY_ACTIVATE, send browsingContext.activate with {"context": handle} when handle is a context in _contexts; else driver.switch_to.window(handle). Any BiDi failure is logged at debug by type and never raised.
    • end_browser calls self.tabs.forget(session_id) beside _moved(session_id, None). FRONT_BY_ACTIVATE takes Task 1's value, with a one-line comment naming the measurement.
  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_tabs.py tests/test_actions_contract.py && pytest -q && ruff check .

  • Step 5: Spec. In docs/superpowers/specs/browser-actions.md, ACT-46 drops (proposed).

  • Step 6: Commit the code, the doubles and the test, then docs/ and its pointer: tabs: check_tabs follows popups and keeps the current tab in front.

Task 4: Every call is bracketed: MCP, REST and the bound write

Files:

  • Modify: kubed/selenium_flow/workspace/workspaces.py (followed, _said, _scrubbed), kubed/selenium_flow/secrets.py (perform_write), kubed/selenium_flow/faults.py (TabClosed, window_gone), kubed/selenium_flow/spec/builder.py (the actions' 409 description), kubed/selenium_flow/core/capabilities.py (TAB_HINTS in _page)
  • Test: tests/test_tabs_following.py (new), tests/test_tabs.py (ACT-53)
  • Golden: tests/golden/openapi.json, tests/golden/tools-on.json, tests/golden/tools-off.json (regenerated, own commit)
  • Spec: ACT-50, ACT-51, ACT-52 and ACT-53 drop (proposed). SEC-40 gains a sentence (Step 6).

Interfaces:

  • Consumes: Actions.check_tabs (Task 3), core.tabs.merged (Task 2).

  • Produces:

    • Workspaces.followed(name: str, session_id: str, failure: BaseException | None = None, *, after: bool = False) -> dict. It runs self.actions.check_tabs(session_id). On a move it notes origins.framed(name, session_id, False) and origins.arrived(name, session_id, change["url"]). With failure true of faults.window_gone, it raises faults.TabClosed(change.get("tab"), change.get("url")) from None. With after=True, a failing check is logged by type and answers {}, so the call's own result or failure stands.
    • faults.window_gone(exc) -> bool: the class is named NoSuchWindowException, or the driver's msg starts with "no such window". class TabClosed(Conflict), a 409: "the tab this call was to act on closed before it could act; the session is now on {tab} ({url}): call again to act there".
    • capabilities.TAB_HINTS: tab (string), opened (array of {tab, url}), closed (array of string), in_frame (boolean), each described as present only when it happened. Merged into _page before **extra, so frame's own in_frame and tab's own tab win.
  • Step 1: Write the failing tests in tests/test_tabs_following.py, over Workspaces(TabbedActions(), MemoryStore(), catalogue=…) opened on A = "https://shop.example.test" (the scoped pattern of tests/test_secret_scope.py), with P = "https://sso.example.test/login" and MOVE_TO_P = {"tab": "t2", "url": P, "title": "Sign in", "in_frame": False}:

    def test_a_call_after_a_popup_opened_acts_on_the_popup_and_says_so(ws):
        ws.actions.checks = [{"opened": [{"tab": "t2", "url": P}], **MOVE_TO_P}, {}]
        result = ws.act(CALLER, ws.actions.do, tool="interact")
        assert result["tab"] == "t2" and result["opened"] == [{"tab": "t2", "url": P}]
        assert ws.actions.calls == ["check_tabs", "do", "check_tabs"]
    
    def test_the_before_check_is_noted_before_the_call_reads_its_origin(ws): ...
        # do() reads ws.origins.current: it is P's origin
    def test_a_popup_the_call_opened_moves_the_results_page(ws): ...
        # checks [{}, {"opened": [...], **MOVE_TO_P}]: url P, title "Sign in", tab "t2",
        # in_frame False; the record's url is P
    def test_a_result_where_nothing_moved_carries_no_tab_keys(ws): ...
        # no "tab", "opened", "closed" or "in_frame" key
    def test_a_move_clears_the_noted_frame(ws): ...
        # origins.framed("w", sid, True) first; after a moved call it answers False
    def test_a_call_whose_tab_closed_before_it_acted_is_a_409_naming_the_new_tab(ws): ...
        # do raises NoSuchWindowException("no such window"); after-check
        # {"closed": ["t2"], "tab": "t1", "url": f"{A}/", ...}: TabClosed, status_for 409,
        # "t1" in its message
    def test_a_call_whose_own_tab_closed_after_it_acted_succeeds(ws): ...  # ACT-51
        # after-check closed ["t2"] and moved to t1: the result's url is A's and closed == ["t2"]
    def test_an_after_check_that_fails_never_fails_a_call_that_acted(ws, caplog): ...
        # the second check raises WebDriverException(P): result returned, P in no log line
    def test_a_before_check_that_fails_fails_the_call_before_it_begins(ws): ...
        # "do" not in calls; the error is scrubbed as a failed call's
    def test_an_opened_popups_url_is_scrubbed_with_every_leashed_secret(): ...
        # a secret allowed only on C = "https://c.example.test"; an opened url carrying
        # its value, the session on A before and after: the value is masked
    def test_a_bound_write_after_a_popup_opened_types_into_the_popup(ws): ...
        # perform_write with checks [MOVE_TO_P, {}]: calls start
        # ["check_tabs", "page", "write", "check_tabs"]; the result's tab is "t2"

    And in tests/test_tabs.py, over Actions and a ScriptedDriver:

    def test_a_screenshot_after_a_popup_is_the_popup(actions, scripted): ...  # ACT-53
        # check_tabs follows w2; actions.screenshot("abc", save=False)["url"] is w2's
  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_tabs_following.py. Expected: FAIL. calls is ["do"], and there is no TabClosed.

  • Step 3: Implement.

    • _said, inside locks.driving: moved = self.followed(name, session_id) comes first. A failure there goes through self.scrubber.error(name, session_id, exc, [None]) and is raised, and the call never begins. Then before = self.origins.current(…), calls.begin and the call as now.
    • After the call: after = self.followed(name, session_id, failure, after=True). A TabClosed raised there replaces failure and is scrubbed with [before, None]. On success, result = tabs.merged(result, moved, after) comes before _scrubbed.
    • _scrubbed appends None to the origins (every usable secret) when tool == "tab" or the result carries opened, as it does for network_body.
    • perform_write: the same two checks around the page read and the write. The page it landed on is noted with workspaces._arrived(name, resolved, merged) in place of origins.arrived(…), so a move's in_frame: false is heard.
    • The 409 description in spec/builder.py for browser actions gains: "or the tab the call was to act on closed before it could act (call again)".
  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_tabs_following.py tests/test_tabs.py tests/test_secret_scope.py tests/test_secrets.py && pytest -q && ruff check .. Expected: the goldens fail on the new response keys and the 409 text, and nothing else.

  • Step 5: Regenerate the goldens. Run: GOLDEN_UPDATE=1 pytest -q tests/test_golden.py. Read the diff: only tab, opened, closed, in_frame in the page responses and the 409 description. Commit the goldens alone: goldens: tab hints in every page result.

  • Step 6: Spec. ACT-50, ACT-51, ACT-52 and ACT-53 drop (proposed). SEC-40 gains: "A tab result, and any result that carries opened, is scrubbed with every usable secret too, because it carries the pages of tabs the call was not on."

  • Step 7: Commit the code and tests (tabs: every call follows popups before and after it acts), then docs/ and its pointer.

Task 5: The tab action

Files:

  • Modify: kubed/selenium_flow/core/actions.py (TAB_ACTIONS, tab, _listed), kubed/selenium_flow/core/capabilities.py (the row, after frame), kubed/selenium_flow/mcp/tools.py (TabAction, the declaration), kubed/selenium_flow/flows/document.py (concerns)
  • Test: tests/test_tabs.py, tests/test_tabs_following.py, tests/test_actions_contract.py (EVERY_ACTION, REFUSED), tests/test_discoverability.py (CLOSED_SETS, the description), tests/test_scrub_coverage.py (the tool's arguments), tests/test_flowdoc.py
  • Golden: as Task 4, own commit. Wiki: python scripts/generate_wiki.py (docs/tab.md, docs/Actions.md); docs/_Sidebar.md gains [`tab`](tab) after frame.
  • Spec: ACT-45, ACT-47 and ACT-48 drop (proposed)

Interfaces:

  • Consumes: Tasks 2 and 3 (TabState, reconcile, _front, _contexts, self.tabs).

  • Produces:

    • TAB_ACTIONS = ("list", "open", "switch", "close").
    • Actions.tab(session_id: str, action="list", id=None, url=None) -> dict. A blank id or url is unset. It goes through self._reattached().run(session_id, body), never _recipe/_at, so its url is never a navigation the recipe makes. list answers {"tabs", "tab"}; open and switch answer {"tab", "in_frame": False}; close answers {"tab", "closed": [id], "in_frame": False}; each with the page state.
    • Actions._listed(session_id: str, driver, state: TabState) -> list[dict]: in id order, {"tab", "url", "title", "current"}. The current tab is read over classic (browser.page_state, so null with a dialog open). The others come from one getTree and one script.evaluate of document.title each (awaitPromise false, REPLY_TIMEOUT). A handle that is not a context, or any BiDi failure, gives null url and title.
    • Row: Capability(name="tab", method="tab", route="tab", http_method="POST", annotations=hints("Open, switch, close or list tabs", destructive=True), response=_page(tabs=…, tab=…, closed=…, in_frame=…)), refused under control (the default).
    • def tab(action: TabAction = "list", id: str | None = None, url: str | None = None) -> dict: ... with the description:

      List the browser's tabs (the default), open one (loading url in it), switch to one (by id; by url, the newest tab whose URL contains that text; or, with neither, the newest), or close one (id, or the current tab).

      Every other tool acts on the current tab. A popup a page opens becomes the current tab by itself, and when the current tab closes the session goes back to the tab it came from; a result says so with tab, opened and closed. Only the current tab is in front: Chrome does not render a tab that is not, and Firefox slows its timers.

  • Step 1: Write the failing tests. In tests/test_tabs.py, with state t1/w1 (current) and t2/w2, tree = [{"context": "w1", "url": A}, {"context": "w2", "url": B}] and titles = {"w2": "Bee"}:

    def test_list_names_each_tab_in_opening_order_without_switching(actions, scripted):
        result = actions.tab("abc")
        assert result["tabs"] == [
            {"tab": "t1", "url": A, "title": "Example", "current": True},
            {"tab": "t2", "url": B, "title": "Bee", "current": False}]
        assert result["tab"] == "t1" and "in_frame" not in result
        assert not [e for e in driver.log if e[:2] == ("switch_to", "window")]
    
    def test_a_tab_bidi_cannot_read_has_null_url_and_title(...): ...  # getTree down
    def test_a_handle_that_is_not_a_context_id_reads_as_null(...): ...  # tree names other ids
    def test_open_makes_a_new_tab_current_and_loads_url(...): ...
        # {"tab": "t3", "url": H, "in_frame": False}; ("switch_to", "new_window", "tab") and ("get", H)
    def test_switch_by_id(...): ...
    def test_switch_by_url_takes_the_newest_match(...): ...   # t1 and t3 both match: t3
    def test_switch_with_neither_takes_the_newest(...): ...
    def test_close_with_no_id_closes_the_current_and_returns_to_its_opener(...): ...
        # on t2 (from t1): {"tab": "t1", "closed": ["t2"], "in_frame": False}
    def test_closing_another_tab_keeps_the_current_one(...): ...
        # on t2, close t1: tab "t2", closed ["t1"]; log switch w1, close, switch w2
    def test_closing_the_last_tab_is_refused_naming_end_browser(...): ...
        # ValueError, "end_browser" in it, status_for 400, no ("close",) in the log
    def test_an_unknown_id_is_a_400_listing_every_tab(...): ...  # "t1", A, "t2", B in the message
    def test_no_tab_matching_url_is_a_400_listing_every_tab(...): ...

    In tests/test_actions_contract.py, EVERY_ACTION["tab"] = lambda a: a.tab("abc"), and these REFUSED cases, refused before the browser is touched: "tab: unknown action" ("bogus"), "tab: id and url both" (switch, id="t1", url="x"), "tab: open takes no id", "tab: close takes no url", "tab: list takes neither", "tab: an id is t<n>" (id="2"), "tab: open url scheme" (url="javascript:alert(1)"). In tests/test_discoverability.py, CLOSED_SETS gains ("tab", "action", "TAB_ACTIONS", TAB_ACTIONS), plus test_tab_says_a_background_tab_is_not_rendered: the description contains "Chrome does not render" and "Firefox slows its timers". In tests/test_scrub_coverage.py, the tool's arguments are "tab": {"action": "list"}. In tests/test_tabs_following.py, test_tab_list_is_scrubbed_with_every_leashed_secret: TabbedActions.tab answers a list whose t2 title carries a value allowed only on C, the session on A: masked. In tests/test_flowdoc.py, test_a_flow_starting_with_a_tab_switch_is_warned_it_names_no_page: concerns warns for tab switch with url, and not for tab open with url.

  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_tabs.py tests/test_actions_contract.py tests/test_surfaces.py. Expected: FAIL with AttributeError: … 'tab'.

  • Step 3: Implement.

    • The checks, before any reconnect: the action is in TAB_ACTIONS; id matches ^t[1-9][0-9]*$; no id and url together; open takes no id; close no url; list neither; open's url passes allowed_navigation.
    • The body reads the state (seeding it when there is none).
    • open: switch_to.new_window("tab"), then browser.go when a url is given. The new tab is known with from = the current tab and becomes current.
    • switch: switch_to.window, the state's current moves, then _front.
    • close of the current tab: driver.close(), then reconcile over the handles left, a switch and _front. close of another tab: switch to it, close it, switch back, _front.
    • Unknown id or no match: ValueError(f"no tab {x}; the tabs are " + ", ".join(f"{t} ({url or 'unknown'})" …)). One tab open: ValueError(f"{id} is the last tab: end_browser ends the browser"). self.tabs.set after each change.
    • concerns reads url as arranging a page for tab only when action is open.
  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_tabs.py tests/test_tabs_following.py tests/test_actions_contract.py tests/test_discoverability.py tests/test_scrub_coverage.py tests/test_surfaces.py tests/test_flowdoc.py && pytest -q && ruff check .. Expected: only the goldens and test_wiki fail.

  • Step 5: Goldens and wiki. GOLDEN_UPDATE=1 pytest -q tests/test_golden.py. The diff is the tab tool and the POST /browser/tab route; commit the goldens alone (goldens: the tab tool). Run python scripts/generate_wiki.py, add the sidebar line, then pytest -q tests/test_wiki.py.

  • Step 6: Spec. ACT-45, ACT-47 and ACT-48 drop (proposed).

  • Step 7: Commit the code and tests (tabs: the tab action lists, opens, switches and closes tabs), then docs/ (the generated pages, the sidebar, the spec) and its pointer.

Task 6: Flows follow popups

Files:

  • Modify: kubed/selenium_flow/flows/engine.py (Hooks.tabs, _drive), kubed/selenium_flow/flows/api.py (run_for wires it), kubed/selenium_flow/workspace/workspaces.py (in_scope)
  • Test: tests/test_flowrun.py, tests/test_flowapi.py
  • Spec: ACT-49 and FLOW-59 drop (proposed)

Interfaces:

  • Consumes: Workspaces.followed (Task 4), core.tabs.merged (Task 2), the tab step (Task 5).

  • Produces: Hooks.tabs: Callable[[bool, BaseException | None], dict], default _no_tabs (answers {}). It is called as tabs(False, None) first in _drive, before resolve_step reads the page for a secret, and as tabs(True, failure) right after the method returns or raises, before after_step. run_for wires tabs=lambda after, failure: workspaces.followed(workspace, resolved, failure, after=after). Workspaces.in_scope appends None to the origins when the result carries opened or tabs.

  • Step 1: Write the failing tests. In tests/test_flowrun.py, over FakeActions and hooks that record:

    def test_each_step_checks_the_tabs_before_and_after_it_acts(): ...
        # order == ["tabs:before", "navigate", "tabs:after", "tabs:before", "extract", "tabs:after"]
    def test_the_before_check_runs_before_a_secret_is_checked_against_the_page(): ...
        # a write step with args.secret: "tabs:before" precedes the page read
    def test_a_step_whose_tab_closed_fails_and_its_on_error_applies(): ...
        # tabs(True, failure) raises TabClosed("t1", A); onError: continue -> step 2 runs,
        # step 1's error contains "now on t1"
    def test_a_steps_result_carries_what_the_tabs_did(): ...
        # verbose run: step 1's returned result has tab "t2" and opened [...]

    In tests/test_flowapi.py, over Workspaces(TabbedActions(), …):

    def test_a_run_reaches_a_popup_its_step_opened_and_leaves_the_session_there(): ...
        # step 1's after-check moves to P; step 2 sees origins.current == P's origin;
        # after the run the record's url is P
    def test_a_steps_opened_url_is_scrubbed_with_every_leashed_secret(): ...
  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_flowrun.py tests/test_flowapi.py. Expected: FAIL with TypeError: Hooks.__init__() got an unexpected keyword argument 'tabs'.

  • Step 3: Implement. A failing before-check fails the step as its action would (_failed, onError applies, never past an assert). The after-check's TabClosed replaces the step's failure. On success, raw = merged(raw, before, after) before after_step and in_scope.

  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_flowrun.py tests/test_flowapi.py tests/test_golden.py && pytest -q && ruff check .. The flow-reports golden must not change: step lines keep their keys.

  • Step 5: Spec. ACT-49 and FLOW-59 drop (proposed).

  • Step 6: Commit the code and tests (tabs: a flow step follows popups like a call), then docs/ and its pointer.

Task 7: The context shows the tabs

Files:

  • Modify: kubed/selenium_flow/core/actions.py (tabs_listed), kubed/selenium_flow/workspace/workspaces.py (CONTEXT_KEYS, _described), kubed/selenium_flow/spec/schemas.py (tabs in the context)
  • Test: tests/test_tabs.py, tests/test_workspaces.py
  • Golden: tests/golden/openapi.json, own commit
  • Spec: WS-76 drops (proposed)

Interfaces:

  • Consumes: Actions._listed (Task 5).

  • Produces: Actions.tabs_listed(session_id: str) -> list[dict]. It reconnects, reads the state (seeding it when there is none) and answers _listed. It never follows, never switches and never writes a known state. A handle no call has seen yet is left out until the next call follows it. "tabs" joins CONTEXT_KEYS after "window". _described starts with "tabs": [] and, while live, fills it in its own try, separate from in_frame and window.

  • Step 1: Write the failing tests.

    # tests/test_workspaces.py, over a manager whose actions answer tabs_listed
    def test_the_context_lists_the_tabs_while_the_browser_is_live(): ...
        # describe(caller)["tabs"] == TABS; describe_part(caller, "tabs") == {"workspace": "w", "tabs": TABS}
    def test_with_no_live_browser_the_tabs_are_an_empty_list(): ...
    def test_a_failed_tabs_read_leaves_an_empty_list_and_never_fails_the_read(): ...
        # tabs_listed raises: tabs == [] and in_frame is still read
    # tests/test_tabs.py
    def test_reading_the_tabs_never_follows_a_popup(actions, scripted): ...
        # a new unseen w2: not listed, no ("switch_to", "window", "w2"), the next check_tabs still opens t2
  • Step 2: Run tests to verify they fail. Run: pytest -q tests/test_workspaces.py tests/test_tabs.py -k tabs. Expected: FAIL with KeyError: 'tabs'.

  • Step 3: Implement. schemas.py: "tabs": {"type": "array", "items": {tab, url, title, current}, "description": "The session's tabs as tab list answers them, read live; empty with no live browser."}.

  • Step 4: Run tests to verify they pass. Run: pytest -q tests/test_workspaces.py tests/test_tabs.py tests/test_resources.py tests/test_scrub_coverage.py && pytest -q && ruff check .. Expected: only the openapi golden fails. Regenerate it, read the diff (the tabs property), and commit it alone: goldens: tabs in the context.

  • Step 5: Spec. WS-76 drops (proposed).

  • Step 6: Commit the code and tests (tabs: workspace://current carries the tabs), then docs/ and its pointer.

Task 8: The skill, the wiki, a live flow and the release line

Files:

  • Modify: plugin/skills/selenium-flow/SKILL.md, plugin/skills/selenium-flow/references/INTERACTION.md, references/FLOWS.md, references/WORKSPACES.md, CHANGELOG.md
  • Create: tests/integration/flows/follow-a-popup.yaml
  • Docs: docs/Workspaces.md, docs/superpowers/specs/browser-actions.md (the section heading), docs/superpowers/plans/2026-11-18-tabs-design.md and this plan (History), docs/superpowers/plans/Ledger.md

Interfaces:

  • Consumes: everything above. Produces: nothing code relies on.

  • Step 1: The skill.

    • SKILL.md: the tools table gains | `tab` | list, open, switch or close tabs; a popup becomes the current tab by itself | after frame, and the workspace://current row names tabs.
    • INTERACTION.md: a "Tabs and popups" section after "Iframes", with the design's "What a call sees" example cut to five lines; switch with url or with nothing for a popup whose id you do not know; a switch leaves any frame; only the current tab is in front.
    • FLOWS.md: one paragraph saying a flow reaches the popup its step opened with tab(action="switch") or url, and starts and ends on the session's current tab.
    • WORKSPACES.md: tabs in the example and the field table.
  • Step 2: Run the skill tests. Run: pytest -q tests/test_skill.py tests/test_wiki.py tests/test_readme.py. Expected: PASS (test_every_tool_and_resource_has_a_row_on_the_page_it_always_reads needs the tab row).

  • Step 3: The live flow. follow-a-popup.yaml covers what no fake can show: a real browser's popup is followed, is in front, and is left when it closes.

    • Steps: navigate to ${admin}/; execute_script window.open(location.origin + '/health').
    • assert return location.pathname.endsWith('/health'), which the before-check made true.
    • assert return document.visibilityState === 'visible' (ACT-52).
    • tab with action: close; assert return !location.pathname.endsWith('/health').

    Each assert carries a message saying what broke. Run it with the suite when GRID_URL and ADMIN_ORIGIN are set; CI's Integration job runs it otherwise.

  • Step 4: The release line and the docs.

    • CHANGELOG.md [Unreleased] → Added: - **Tabs and popups**: a popup a page opens is followed, the session comes back when it closes, and \tab` lists, opens, switches and closes tabs.`
    • docs/Workspaces.md: one sentence on tabs.
    • browser-actions.md: ## Proposed: tabs becomes ## Tabs, and its "Not built." line goes.
    • The design's and this plan's History headers say what shipped and which ids hold it now.
    • Ledger.md gains the round's entry.
  • Step 5: Verify. Run: ruff check . && pytest -q. Expected: PASS.

  • Step 6: Commit the skill, the flow and the changelog (tabs: skill, live flow and changelog), then docs/ and its pointer.

Clone this wiki locally