"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(browser): split type_text safety chain into 4 separate calls (PR #308 round 6.1)
apirenob897659ddb3a
diff --git a/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py b/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.pyindex ee947edfc..38cea51d6 100644--- a/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py+++ b/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py@@ -216,6 +216,24 @@ def test_is_error_detects_error_prefixed_text():assert backend._is_error(_make_result("✓ Focused\n[lane: 1]")) is False+def test_is_error_strips_ansi_red_wrapper():+ """DOMShell colours errors red — strip ANSI before prefix-matching.++ Without this, a coloured error like `\\x1b[31mError: ...\\x1b[0m`+ would be misread as success (its first chars are `\\x1b[31m`, not+ `error`), letting downstream safety chains proceed.+ """+ assert backend._is_error(+ _make_result("\x1b[31mError: focus: No such element\x1b[0m")+ ) is True+ # Plain `Error:` still detected.+ assert backend._is_error(_make_result("Error: oops")) is True+ # Mixed ANSI prefix without "Error" stays False.+ assert backend._is_error(+ _make_result("\x1b[32m✓ All good\x1b[0m")+ ) is False++def test_is_error_handles_missing_content():assert backend._is_error(SimpleNamespace()) is False@@ -347,38 +365,92 @@ def test_type_text_emits_focus_then_type_with_session(mock_call):@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_type_text_absolute_path_wraps_focus(mock_call):- """Absolute focus path is anchored at %here% and restores wd."""+def test_type_text_absolute_path_uses_four_separate_calls(mock_call):+ """Absolute focus path: anchor → focus → type → restore, all distinct.++ type_text is a safety chain, NOT a cleanup-line idiom: it must HALT+ on focus failure rather than continue past it. Wrapping focus in a+ multi-line ``cd %here%\\nfocus\\ncd <restore>`` would re-introduce+ the continue-on-error trap (the anchor's leading "✓" masks the+ focus error in the combined response). Split into four separate+ _call_execute calls, all sharing the persisted lane via session.+ """sess = _make_session(working_dir="/main")mock_call.return_value = _make_result("✓\n[lane: 1]")- backend.type_text("/main/input", "text", session=sess)+ backend.type_text("/main/input", "hello", session=sess)- assert mock_call.call_count == 2- assert (- mock_call.call_args_list[0].args[0]- == "cd %here%\nfocus main/input\ncd %here%/main"+ assert mock_call.call_count == 4+ assert mock_call.call_args_list[0].args[0] == "cd %here%"+ assert mock_call.call_args_list[1].args[0] == "focus main/input"+ assert mock_call.call_args_list[2].args[0] == "type hello"+ assert mock_call.call_args_list[3].args[0] == "cd %here%/main"++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_type_text_absolute_path_focus_failure_skips_type_and_restores(mock_call):+ """The Codex P2 safety case: a stale absolute focus path must halt+ before type can dispatch keys into whatever was previously focused.+ The restore still runs so the lane cwd ends up where the harness+ expects.+ """+ sess = _make_session(working_dir="/main")+ mock_call.side_effect = [+ _make_result("✓ Entered tab 123\n[lane: 1]"), # cd anchor ok+ _make_result("\x1b[31mError: focus: No such element\x1b[0m"), # focus fails+ _make_result("✓ Typed\n[lane: 1]"), # MUST NOT be reached+ _make_result("✓\n[lane: 1]"), # restore+ ]++ backend.type_text("/main/missing", "secret_password", session=sess)++ # Three calls: anchor, focus, restore. Type is skipped because the+ # focus error halts the safety chain before keys are dispatched.+ assert mock_call.call_count == 3+ assert mock_call.call_args_list[0].args[0] == "cd %here%"+ assert mock_call.call_args_list[1].args[0] == "focus main/missing"+ assert mock_call.call_args_list[2].args[0] == "cd %here%/main"+ # Critically — the "type secret_password" command was never sent.+ for call_args in mock_call.call_args_list:+ assert "type" not in call_args.args[0].split("\n")[0]++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_type_text_anchor_failure_does_not_attempt_focus(mock_call):+ """If even the anchor cd fails (e.g. chrome:// not debuggable),+ neither focus nor type runs. No restore needed because we never+ moved off the original cwd.+ """+ sess = _make_session(working_dir="/")+ mock_call.return_value = _make_result(+ "\x1b[31mError: chrome:// not debuggable\x1b[0m")- assert mock_call.call_args_list[1].args[0] == "type text"++ backend.type_text("/some/path", "text", session=sess)++ assert mock_call.call_count == 1+ assert mock_call.call_args_list[0].args[0] == "cd %here%"@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_type_text_skips_type_on_focus_error(mock_call):- """If focus errors, type MUST NOT run — would land in stale focus."""+def test_type_text_relative_path_focus_failure_skips_type(mock_call):+ """Relative path focus failure: no anchor (no drift to restore), so+ just `focus`, then halt. Type MUST NOT run.++ The absolute-path equivalent (with anchor + restore) is covered by+ test_type_text_absolute_path_focus_failure_skips_type_and_restores.+ """sess = _make_session(working_dir="/")mock_call.side_effect = [_make_result("Error: focus: No such element"),_make_result("✓ Typed"), # should NOT be reached]- result = backend.type_text("/stale/path", "secret_password", session=sess)+ result = backend.type_text("stale_input", "secret_password", session=sess)# Only the focus call was made; the focus result was returned.assert mock_call.call_count == 1- # Absolute path → wrapped in anchor + restore.- assert mock_call.call_args_list[0].args[0] == (- "cd %here%\nfocus stale/path\ncd %here%"- )+ assert mock_call.call_args_list[0].args[0] == "focus stale_input"# The focus result is returned verbatim so callers see the error.assert result.content[0].text == "Error: focus: No such element"diff --git a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.pyindex 41fca7fa0..fcaf2f6d1 100644--- a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py+++ b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py@@ -269,7 +269,19 @@ def _restore_cwd_cmd(session: Any) -> str:def _wrap_absolute(operation: str, session: Any, *, deeper: str = "") -> str:- """Build a ``cd %here%[/deeper]\\n<operation>\\n<restore>`` triplet.+ """Build a ``cd %here%[/deeper]\\n<operation>\\n<restore>`` triplet for+ absolute harness paths, so the operation runs against the tab root+ regardless of lane cwd drift.++ USE FOR cleanup-line idioms ONLY — operations whose error doesn't gate+ further wrapper-side action (``ls``, ``cat``, ``click``, ``grep``).+ DOMShell's multi-line semantics continue past per-line errors, which+ is the correct property for "always run the restore" but the WRONG+ property for **safety chains** where the second step depends on the+ first step's success. For safety chains (e.g. ``type_text``'s+ ``focus → type``), issue anchor / operation / restore as SEPARATE+ ``_call_execute`` calls and ``_is_error``-check between them. See+ ``type_text``'s absolute-path branch for the pattern.``deeper`` is the optional tab-root-relative subdir to ``cd`` intoBEFORE the operation. Used for ``ls /main`` where the operation is@@ -284,14 +296,22 @@ def _wrap_absolute(operation: str, session: Any, *, deeper: str = "") -> str:return f"cd {_here_path(deeper)}\n{operation}\n{_restore_cwd_cmd(session)}"+# CSI (ANSI) escape sequences DOMShell wraps error text in (typically red).+# Strip them before prefix-matching "error" so an ANSI-coloured error line+# isn't misread as success.+_ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")++def _is_error(result: Any) -> bool:"""Best-effort check that a ``domshell_execute`` result represents an error.Inspects ``isError`` if the MCP SDK populated it, then ``isError`` /``error`` keys on dict-shaped test fixtures, and finally scans the- concatenated text content for a leading "error". Robust to the raw- ``CallToolResult`` and to the ``SimpleNamespace(content=[...])``- fixtures used in tests.+ concatenated text content for a leading "error" — with ANSI escape+ sequences stripped first, since DOMShell colours error lines red+ (``\\x1b[31mError: ...\\x1b[0m``). Robust to the raw+ ``CallToolResult`` and to ``SimpleNamespace(content=[...])`` test+ fixtures."""if hasattr(result, "isError") and result.isError:return True@@ -307,6 +327,7 @@ def _is_error(result: Any) -> bool:piece = getattr(c, "text", None)if piece:text += piece+ text = _ANSI_CSI_RE.sub("", text)return text.strip().lower().startswith("error")@@ -775,26 +796,55 @@ def type_text("type_text: an input path is required — cannot focus the tab root.")- # Relies on DOMShell serializing commands within a lane: the `type`- # call below cannot be preempted by another agent's `focus` on the- # same lane between these two _call_execute boundaries. If that- # contract ever changes upstream, this needs to revert to a single- # multi-line call with an alternative safety story.+ # type_text is a safety chain (focus → type), NOT a cleanup-line+ # idiom (cd → op → cd back). Cleanup-line patterns want continue-on-+ # error so the restore always runs. Safety chains want the opposite:+ # halt on the first step's error so the second step doesn't dispatch+ # against stale state. Wrapping focus inside `_wrap_absolute` (a+ # multi-line continue-on-error script) re-introduces the trap the+ # round-4 split was designed to prevent — the anchor's leading "✓"+ # text in the combined response masks the focus error, and `type`+ # would land in whatever was previously focused.+ #+ # So for absolute paths we anchor with a SEPARATE _call_execute+ # (one-line `cd %here%`), check for error, focus as a separate call+ # we can _is_error-check, then type, then restore as a separate+ # best-effort call. All four share the persisted lane via session.if is_absolute:- # Anchor + focus + restore as one multi-line call, so the focus- # lands against the tab root regardless of lane cwd drift.- focus_cmd = _wrap_absolute(f"focus {_q(translated_path)}", session)- else:- focus_cmd = f"focus {_q(translated_path)}"+ anchor_result = asyncio.run(_call_execute(+ f"cd {_here_path('')}", use_daemon, session=session,+ ))+ if _is_error(anchor_result):+ # Anchor failed — we never moved, so no restore is needed.+ return anchor_result+focus_result = asyncio.run(_call_execute(- focus_cmd, use_daemon, session=session,+ f"focus {_q(translated_path)}", use_daemon, session=session,))if _is_error(focus_result):- return focus_result # don't type — focus didn't land- return asyncio.run(_call_execute(+ # Focus failed — restore cwd before returning so the lane+ # doesn't stay parked at the anchor (only relevant when we+ # actually moved, i.e. the absolute path branch).+ if is_absolute:+ asyncio.run(_call_execute(+ _restore_cwd_cmd(session), use_daemon, session=session,+ ))+ return focus_result++ type_result = asyncio.run(_call_execute(f"type {_q(text)}", use_daemon, session=session,))+ if is_absolute:+ # Best-effort restore — type already succeeded, so a restore+ # failure is cosmetic. The next harness cd will correct any+ # drift.+ asyncio.run(_call_execute(+ _restore_cwd_cmd(session), use_daemon, session=session,+ ))++ return type_result+# ── Daemon control functions ───────────────────────────────────────────