Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

fix(browser): split-and-check pattern + CLI parse layer (PR #308 round 7)

apireno0f2efbab63cc
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.py
index ce2e7dc7a..349c40a12 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
@@ -46,25 +46,32 @@ def test_translate_path_preserves_relative():
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
-def test_ls_absolute_path_wraps_with_cd_anchor_and_restore(mock_call):
- """`ls /main` from a `/main` session: cd-anchor + bare ls + restore."""
+def test_ls_absolute_path_uses_three_separate_calls(mock_call):
+ """Split-and-check: anchor → bare ls → restore, three distinct calls.
+
+ Anchor success is load-bearing — if the cd fails, ls would run in
+ the wrong cwd. Tested separately by
+ test_ls_anchor_failure_short_circuits.
+ """
mock_call.return_value = _make_result("[lane: 1]")
sess = _make_session(working_dir="/main")
backend.ls("/main", session=sess)
- cmd = mock_call.call_args.args[0]
- assert "cd %here%/main" in cmd
- assert "\nls\n" in cmd
- assert cmd.endswith("cd %here%/main")
+ assert mock_call.call_count == 3
+ assert mock_call.call_args_list[0].args[0] == "cd %here%/main" # anchor
+ assert mock_call.call_args_list[1].args[0] == "ls" # op
+ assert mock_call.call_args_list[2].args[0] == "cd %here%/main" # restore
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
def test_ls_root_from_drifted_cwd_anchors_at_here(mock_call):
- """The Codex P1 case: `ls /` from a drifted `/main` cwd anchors at tab root."""
+ """The Codex P1 case: `ls /` from a drifted `/main` cwd."""
mock_call.return_value = _make_result("[lane: 1]")
sess = _make_session(working_dir="/main")
backend.ls("/", session=sess)
- cmd = mock_call.call_args.args[0]
- assert cmd == "cd %here%\nls\ncd %here%/main"
+ assert mock_call.call_count == 3
+ assert mock_call.call_args_list[0].args[0] == "cd %here%" # anchor at tab root
+ assert mock_call.call_args_list[1].args[0] == "ls" # bare ls
+ assert mock_call.call_args_list[2].args[0] == "cd %here%/main" # back to /main
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
@@ -84,8 +91,8 @@ def test_ls_absolute_path_with_spaces_quoted(mock_call):
"""
mock_call.return_value = _make_result("[lane: 1]")
backend.ls("/path with spaces", session=_make_session(working_dir="/"))
- cmd = mock_call.call_args.args[0]
- assert "cd '%here%/path with spaces'" in cmd
+ # Anchor (first call) is the quoted form.
+ assert mock_call.call_args_list[0].args[0] == "cd '%here%/path with spaces'"
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
@@ -121,12 +128,15 @@ def test_cd_relative_quoted(mock_call):
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
-def test_cat_absolute_path_wraps(mock_call):
- """`cat /main/btn`: anchor at tab root, run relative cat, restore."""
+def test_cat_absolute_path_uses_three_separate_calls(mock_call):
+ """`cat /main/btn`: anchor at tab root → cat main/btn → restore."""
mock_call.return_value = _make_result("[lane: 1]")
sess = _make_session(working_dir="/")
backend.cat("/main/btn", session=sess)
- assert mock_call.call_args.args[0] == "cd %here%\ncat main/btn\ncd %here%"
+ 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] == "cat main/btn"
+ assert mock_call.call_args_list[2].args[0] == "cd %here%"
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
@@ -144,14 +154,14 @@ def test_cat_root_raises_value_error():
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
-def test_click_absolute_path_wraps(mock_call):
+def test_click_absolute_path_uses_three_separate_calls(mock_call):
mock_call.return_value = _make_result("[lane: 1]")
sess = _make_session(working_dir="/main")
backend.click("/main/button[0]", session=sess)
- assert (
- mock_call.call_args.args[0]
- == "cd %here%\nclick 'main/button[0]'\ncd %here%/main"
- )
+ 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] == "click 'main/button[0]'"
+ assert mock_call.call_args_list[2].args[0] == "cd %here%/main"
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
@@ -172,28 +182,193 @@ def test_click_root_raises_value_error():
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
-def test_grep_rooted_absolute_anchors_at_here(mock_call):
- """Rooted grep with absolute path anchors at tab root + restores wd."""
+def test_grep_rooted_absolute_uses_three_separate_calls(mock_call):
+ """Rooted grep (absolute): anchor → grep → restore, three distinct calls."""
mock_call.return_value = _make_result("[lane: 1]")
backend.grep(
"Login", path="/main", prev="/", session=_make_session(working_dir="/"),
)
- assert (
- mock_call.call_args.args[0]
- == "cd %here%/main\ngrep Login\ncd %here%"
- )
+ assert mock_call.call_count == 3
+ assert mock_call.call_args_list[0].args[0] == "cd %here%/main"
+ assert mock_call.call_args_list[1].args[0] == "grep Login"
+ assert mock_call.call_args_list[2].args[0] == "cd %here%"
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
def test_grep_rooted_absolute_restores_to_session_wd(mock_call):
- """Restore line follows session.working_dir, not the `prev` kwarg, when
- the path is absolute — the lane cwd needs to end up where the harness
- thinks it is, regardless of what `prev` was originally."""
+ """Restore (third call) follows session.working_dir, not the `prev`
+ kwarg, when the path is absolute — the lane cwd needs to end up
+ where the harness thinks it is."""
mock_call.return_value = _make_result("[lane: 1]")
backend.grep(
"Login", path="/main", prev="/", session=_make_session(working_dir="/main"),
)
- assert mock_call.call_args.args[0].endswith("cd %here%/main")
+ assert mock_call.call_args_list[2].args[0] == "cd %here%/main"
+
+
+# ── Anchor-failure short-circuit (the Codex P2 case per-wrapper) ─────
+#
+# If the anchor `cd` fails, the operation must NOT run — it would
+# resolve against the wrong cwd and produce wrong-target results. Each
+# wrapper that uses split-and-check mirrors `type_text`'s
+# anchor-failure pattern.
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_ls_anchor_failure_short_circuits(mock_call):
+ """ls absolute-path anchor failure → only the anchor call ran."""
+ mock_call.return_value = _make_result(
+ "\x1b[31mError: chrome:// not debuggable\x1b[0m"
+ )
+ sess = _make_session(working_dir="/")
+ result = backend.ls("/main", session=sess)
+ assert mock_call.call_count == 1
+ assert mock_call.call_args_list[0].args[0] == "cd %here%/main"
+ assert "error" in result
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_cat_anchor_failure_short_circuits(mock_call):
+ mock_call.return_value = _make_result(
+ "\x1b[31mError: no such path\x1b[0m"
+ )
+ sess = _make_session(working_dir="/")
+ result = backend.cat("/main/btn", session=sess)
+ assert mock_call.call_count == 1
+ assert mock_call.call_args_list[0].args[0] == "cd %here%"
+ assert "error" in result
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_click_anchor_failure_short_circuits(mock_call):
+ """Critical for click: a misdirected click could trigger an
+ unintended action. Anchor must halt before the click runs.
+ """
+ mock_call.return_value = _make_result(
+ "\x1b[31mError: chrome:// not debuggable\x1b[0m"
+ )
+ sess = _make_session(working_dir="/")
+ result = backend.click("/main/button[0]", session=sess)
+ assert mock_call.call_count == 1
+ assert mock_call.call_args_list[0].args[0] == "cd %here%"
+ assert "error" in result
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_grep_rooted_anchor_failure_short_circuits(mock_call):
+ """Rooted grep with anchor failure → grep doesn't run (wrong-scope
+ matches would be misleading). Restore also skipped because we
+ never moved off the original cwd.
+ """
+ mock_call.return_value = _make_result(
+ "\x1b[31mError: no such path /missing\x1b[0m"
+ )
+ sess = _make_session(working_dir="/")
+ result = backend.grep("Login", path="/missing", prev="/", session=sess)
+ assert mock_call.call_count == 1
+ assert mock_call.call_args_list[0].args[0] == "cd %here%/missing"
+ assert "error" in result
+
+
+# ── _parse_execute_result: dict shapes per command ───────────────────
+#
+# DOMShell 2.x returns text content; the CLI was written for the
+# pre-2.0 per-command tools that returned dicts. These tests lock in
+# the translator's per-command shape contract so the CLI doesn't break
+# on `result.get(...)` calls.
+
+
+def test_parse_execute_result_ls_extracts_entries():
+ result = _make_result("button[0]\nlink[1]\nimg[2]\n[lane: 7]")
+ parsed = backend._parse_execute_result(result, "ls")
+ assert parsed["entries"] == [
+ {"name": "button[0]", "role": "", "path": "button[0]"},
+ {"name": "link[1]", "role": "", "path": "link[1]"},
+ {"name": "img[2]", "role": "", "path": "img[2]"},
+ ]
+ # Lane marker is stripped from the raw text.
+ assert "[lane:" not in parsed["raw"]
+
+
+def test_parse_execute_result_ls_empty_text_returns_empty_entries():
+ parsed = backend._parse_execute_result(_make_result("[lane: 7]"), "ls")
+ assert parsed == {"entries": [], "raw": ""}
+
+
+def test_parse_execute_result_grep_extracts_matches():
+ result = _make_result(
+ "/main/button[0]\n/main/link[1]\n[lane: 7]"
+ )
+ parsed = backend._parse_execute_result(result, "grep")
+ assert parsed["matches"] == ["/main/button[0]", "/main/link[1]"]
+ assert "[lane:" not in parsed["raw"]
+
+
+def test_parse_execute_result_error_returns_error_dict():
+ """Errors get `error` AND `output` keys — the CLI checks `"error" in
+ result` for cd-style guards but also pretty-prints `output`."""
+ result = _make_result(
+ "\x1b[31mError: no such element\x1b[0m\n[lane: 7]"
+ )
+ parsed = backend._parse_execute_result(result, "ls")
+ assert "error" in parsed
+ assert parsed["error"].startswith("\x1b[31mError")
+ assert parsed["output"] == parsed["error"]
+
+
+def test_parse_execute_result_default_for_other_commands():
+ """cat/click/focus/type/open/refresh/back/forward all fall through
+ to the generic ``{"output": text}`` shape."""
+ for cmd in ("cat", "click", "focus", "type", "open", "refresh", "back", "forward"):
+ parsed = backend._parse_execute_result(
+ _make_result("done\n[lane: 1]"), cmd,
+ )
+ assert parsed == {"output": "done"}
+
+
+# ── End-to-end: wrappers return parsed dicts (not CallToolResult) ────
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_ls_returns_entries_dict(mock_call):
+ """`backend.ls(...)` must return ``{"entries": [...]}`` so the CLI
+ doesn't AttributeError on `result.get("entries", [])`. This is the
+ Codex P1 shipped regression."""
+ mock_call.return_value = _make_result("button[0]\n[lane: 1]")
+ result = backend.ls("main")
+ assert "entries" in result
+ assert isinstance(result["entries"], list)
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_grep_returns_matches_dict(mock_call):
+ mock_call.return_value = _make_result("/main/btn[0]\n[lane: 1]")
+ result = backend.grep("Login")
+ assert "matches" in result
+ assert result["matches"] == ["/main/btn[0]"]
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_cd_returns_dict_with_output(mock_call):
+ """`backend.cd(...)` returns a dict so `isinstance(result, dict)`
+ in fs.change_directory works and `result.get("path", path)` falls
+ back cleanly."""
+ mock_call.return_value = _make_result("✓ Entered main\n[lane: 1]")
+ result = backend.cd("/main")
+ assert isinstance(result, dict)
+ assert "error" not in result
+
+
[email protected](backend, "_call_execute", new_callable=AsyncMock)
+def test_cd_error_returns_error_dict(mock_call):
+ """`fs.change_directory` checks `"error" not in result` — make sure
+ error paths surface the error key so the harness's working-dir
+ update is correctly skipped."""
+ mock_call.return_value = _make_result(
+ "\x1b[31mError: no such path\x1b[0m"
+ )
+ result = backend.cd("/missing")
+ assert "error" in result
# ── _is_error helper ─────────────────────────────────────────────────
@@ -253,56 +428,42 @@ def test_grep_unrooted_produces_single_grep_call(mock_call):
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
-def test_grep_rooted_emits_single_multiline_call(mock_call):
- """Rooted grep is ONE multi-line ``cd / grep / cd back`` execute call.
+def test_grep_rooted_emits_three_call_sequence(mock_call):
+ """Rooted grep is THREE separate ``_call_execute`` calls: anchor →
+ grep → restore. Anchor success is load-bearing (would search the
+ wrong subtree on cwd drift), so we can't fold this into a single
+ multi-line continue-on-error call.
- Each ``_call_execute`` in non-daemon mode opens a fresh MCP session
- that lands in its own DOMShell 2.x lane, so splitting cd / grep /
- restore across separate calls would lose the cwd between them. The
- three lines must travel in one ``domshell_execute`` call to share
- a lane.
+ Lane sharing across the three calls is preserved via
+ ``session.domshell_lane_id`` — see round-4 lane-persistence tests.
"""
- mock_call.return_value = {}
+ mock_call.return_value = _make_result("[lane: 1]")
backend.grep("Login", path="/main", prev="/")
- # Absolute path anchors at %here%/main; restore comes from
- # _restore_cwd_cmd(session=None) → `cd %here%` (defaults to harness `/`).
assert mock_call.call_args_list == [
- call("cd %here%/main\ngrep Login\ncd %here%", False, session=None),
+ call("cd %here%/main", False, session=None),
+ call("grep Login", False, session=None),
+ call("cd %here%", False, session=None),
]
[email protected](backend, "_call_execute", new_callable=AsyncMock)
-def test_grep_rooted_uses_single_call_for_lane_isolation(mock_call):
- """Documents the lane-isolation contract: ONE call, not three.
-
- The trailing ``cd prev`` is delivered as the final line of the same
- multi-line command and runs even if ``grep`` errors, per DOMShell's
- documented continue-on-error semantics
- (`apireno/DOMShell#46 <https://github.com/apireno/DOMShell/issues/46>`_).
- """
- mock_call.return_value = {}
-
- backend.grep("Login", path="/main", prev="/")
-
- assert mock_call.call_count == 1
-
-
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
def test_grep_rooted_quotes_path_with_spaces(mock_call):
"""Absolute paths with whitespace are quoted as `cd '%here%/path with spaces'`.
Upstream-smoked: DOMShell's `cd` accepts the quoted form cleanly.
"""
- mock_call.return_value = {}
+ mock_call.return_value = _make_result("[lane: 1]")
backend.grep("Login", path="/path with spaces", prev="/")
- cmd = mock_call.call_args.args[0]
- assert cmd.startswith("cd '%here%/path with spaces'\n")
- assert "\ngrep Login\n" in cmd
- assert cmd.endswith("\ncd %here%")
+ # Three-call sequence — quoting applies to the anchor (first call).
+ assert mock_call.call_args_list == [
+ call("cd '%here%/path with spaces'", False, session=None),
+ call("grep Login", False, session=None),
+ call("cd %here%", False, session=None),
+ ]
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
@@ -451,8 +612,11 @@ def test_type_text_relative_path_focus_failure_skips_type(mock_call):
# Only the focus call was made; the focus result was returned.
assert mock_call.call_count == 1
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"
+ # The focus result is parsed (CLI consumes dicts, not CallToolResult).
+ assert result == {
+ "error": "Error: focus: No such element",
+ "output": "Error: focus: No such element",
+ }
def test_type_text_raises_without_session_in_non_daemon_mode():
@@ -799,11 +963,13 @@ def test_session_is_keyword_only_on_open_url():
def test_use_daemon_positional_on_ls(mock_call):
mock_call.return_value = _make_result("[lane: 1]")
backend.ls("/", True) # use_daemon=True positionally
- # Absolute `/` with no session → anchor at %here%, bare ls, restore
- # to %here% (the default for session=None).
- assert mock_call.call_args == call(
- "cd %here%\nls\ncd %here%", True, session=None,
- )
+ # Absolute `/` with no session → 3-call sequence, use_daemon=True
+ # flows through all three calls.
+ assert mock_call.call_args_list == [
+ call("cd %here%", True, session=None),
+ call("ls", True, session=None),
+ call("cd %here%", True, session=None),
+ ]
@patch.object(backend, "_call_execute", new_callable=AsyncMock)
diff --git a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py
index bab51b208..8cd3ab067 100644
--- a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py
+++ b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py
@@ -278,32 +278,16 @@ def _restore_cwd_cmd(session: Any) -> str:
return f"cd {_q(stripped)}" if stripped else f"cd {_here_path('')}"
-def _wrap_absolute(operation: str, session: Any, *, deeper: str = "") -> str:
- """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`` into
- BEFORE the operation. Used for ``ls /main`` where the operation is
- bare ``ls`` (and the ``/main`` needs to become the anchored cwd) as
- opposed to ``cat /main/btn`` where the operation already carries the
- relative path and we just anchor at the tab root.
-
- The ``%here%/<deeper>`` token is shell-quoted as a single unit via
- ``_here_path``, so paths containing whitespace or other shell
- metacharacters survive the wrap correctly.
+def _anchor_path_cmd(deeper: str = "") -> str:
+ """Build a single ``cd %here%[/<deeper>]`` command line, shell-quoted.
+
+ The reusable anchor primitive for split-and-check wrapper patterns.
+ Every absolute-path wrapper (ls/cat/click/grep) issues this as its
+ first ``_call_execute``, then ``_is_error``-checks the result before
+ running the operation. Used for the anchor and restore positions in
+ the split-and-check pattern.
"""
- return f"cd {_here_path(deeper)}\n{operation}\n{_restore_cwd_cmd(session)}"
+ return f"cd {_here_path(deeper)}"
# CSI (ANSI) escape sequences DOMShell wraps error text in (typically red).
@@ -341,6 +325,68 @@ def _is_error(result: Any) -> bool:
return text.strip().lower().startswith("error")
+def _extract_text(result: Any) -> str:
+ """Concatenate ``content[*].text`` from a CallToolResult-like object."""
+ text = ""
+ content = getattr(result, "content", None)
+ if content:
+ for c in content:
+ piece = getattr(c, "text", None)
+ if piece:
+ text += piece
+ return text
+
+
+def _parse_execute_result(result: Any, command: str) -> dict:
+ """Translate a ``domshell_execute`` text response into the dict shape
+ ``browser_cli.py`` and friends consume.
+
+ DOMShell 2.x returns text content over MCP (plus a trailing
+ ``[lane: <id>]`` marker). The CLI was written for the pre-2.0
+ per-command tools, which returned structured dicts — so without
+ this translator the harness throws ``AttributeError`` on
+ ``result.get("entries")`` / ``result.get("matches")`` etc.
+
+ The shape contract per command (read off the CLI callers):
+
+ * ``ls`` → ``{"entries": [{"name", "role", "path"}, ...], "raw"}``
+ * ``grep``→ ``{"matches": [...], "raw"}``
+ * error → ``{"error": text, "output": text}`` (caller checks
+ ``"error" in result`` before normal handling)
+ * other → ``{"output": text}`` (CLI's ``output()`` / ``_print_dict``
+ handles arbitrary dicts; ``page.go_back/forward`` skip the
+ ``set_url`` step if ``"url"`` is absent, matching today's behavior)
+
+ This is a minimum-viable parser that satisfies the dict-key
+ contract. Finer-grained parsing of element name / role / path
+ columns can land as a follow-up once DOMShell's exact text format
+ stabilizes — for now every line is plumbed through as the ``name``
+ field (and the ``path`` field) so the CLI's table view still
+ renders rather than crashing.
+ """
+ text = _LANE_LINE.sub("", _extract_text(result)).strip()
+
+ if _is_error(result):
+ return {"error": text, "output": text}
+
+ if command == "ls":
+ lines = [ln for ln in text.splitlines() if ln.strip()]
+ entries = [
+ {"name": ln.strip(), "role": "", "path": ln.strip()}
+ for ln in lines
+ ]
+ return {"entries": entries, "raw": text}
+
+ if command == "grep":
+ matches = [ln for ln in text.splitlines() if ln.strip()]
+ return {"matches": matches, "raw": text}
+
+ # cd / cat / click / focus / type / open / refresh / back / forward
+ # all funnel through the CLI's generic dict pretty-printer; an
+ # ``{"output": text}`` shape is enough.
+ return {"output": text}
+
+
def _assert_single_line(field: str, value: str) -> None:
"""Reject newline characters in a user-supplied string.
@@ -520,14 +566,30 @@ def ls(path: str = "/", use_daemon: bool = False, *, session: Any = None) -> dic
"""
translated, is_absolute = _translate_path(path)
if is_absolute:
- # `ls /main`: cd to %here%/main, run bare ls, restore.
- # `ls /`: cd to %here%, run bare ls, restore.
- command = _wrap_absolute("ls", session, deeper=translated)
- elif translated:
- command = f"ls {_q(translated)}"
+ # Split-and-check: the anchor's success is load-bearing — if
+ # cd fails, ls would run in the wrong cwd and produce
+ # wrong-target results. Three separate _call_execute calls so
+ # we can _is_error-gate after the anchor and skip the operation
+ # cleanly. All share the persisted lane via session.
+ anchor = asyncio.run(_call_execute(
+ _anchor_path_cmd(translated), use_daemon, session=session,
+ ))
+ if _is_error(anchor):
+ return _parse_execute_result(anchor, "ls")
+ op = asyncio.run(_call_execute("ls", use_daemon, session=session))
+ # Best-effort restore — ls already ran; restore failure is
+ # cosmetic (next harness cd corrects any drift).
+ asyncio.run(_call_execute(
+ _restore_cwd_cmd(session), use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "ls")
+ if translated:
+ op = asyncio.run(_call_execute(
+ f"ls {_q(translated)}", use_daemon, session=session,
+ ))
else:
- command = "ls"
- return asyncio.run(_call_execute(command, use_daemon, session=session))
+ op = asyncio.run(_call_execute("ls", use_daemon, session=session))
+ return _parse_execute_result(op, "ls")
def cd(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -546,17 +608,19 @@ def cd(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
{"path": "/main/div[0]", "element": {...}}
"""
translated, is_absolute = _translate_path(path)
- # cd is the rare case where the operation IS the new state — no
- # restore needed. Absolute targets anchor via `cd %here%/<rest>` so
+ # cd is the one wrapper where the operation IS the new state — no
+ # following operation needs the anchored cwd, so no split-and-check
+ # and no restore. Absolute targets anchor via `cd %here%/<rest>` so
# the result is independent of the lane's current cwd.
if is_absolute:
- command = f"cd {_here_path(translated)}"
+ command = _anchor_path_cmd(translated)
elif translated:
command = f"cd {_q(translated)}"
else:
# Bare/empty `cd` → back to tab root.
- command = f"cd {_here_path('')}"
- return asyncio.run(_call_execute(command, use_daemon, session=session))
+ command = _anchor_path_cmd("")
+ result = asyncio.run(_call_execute(command, use_daemon, session=session))
+ return _parse_execute_result(result, "cd")
def cat(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -581,12 +645,26 @@ def cat(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
"Use `ls` to list the root's children, or pass a specific name."
)
if is_absolute:
- # `cat /main/btn`: anchor at tab root, run `cat main/btn` relative,
- # restore the harness's tracked cwd.
- command = _wrap_absolute(f"cat {_q(translated)}", session)
- else:
- command = f"cat {_q(translated)}"
- return asyncio.run(_call_execute(command, use_daemon, session=session))
+ # Split-and-check: anchor at tab root, halt if anchor fails,
+ # otherwise run relative cat, restore. Anchor success is
+ # load-bearing — without it cat resolves the relative path
+ # against the wrong cwd.
+ anchor = asyncio.run(_call_execute(
+ _anchor_path_cmd(""), use_daemon, session=session,
+ ))
+ if _is_error(anchor):
+ return _parse_execute_result(anchor, "cat")
+ op = asyncio.run(_call_execute(
+ f"cat {_q(translated)}", use_daemon, session=session,
+ ))
+ asyncio.run(_call_execute(
+ _restore_cwd_cmd(session), use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "cat")
+ op = asyncio.run(_call_execute(
+ f"cat {_q(translated)}", use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "cat")
def grep(
@@ -635,36 +713,40 @@ def grep(
translated_path, path_abs = _translate_path(path)
if not translated_path:
# Unrooted grep — operate on lane cwd, no cd, no restore.
- return asyncio.run(
- _call_execute(f"grep {_q(pattern)}", use_daemon, session=session)
- )
+ op = asyncio.run(_call_execute(
+ f"grep {_q(pattern)}", use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "grep")
_assert_single_line("path", path)
_assert_single_line("prev", prev)
+ # Split-and-check. Anchor success is load-bearing: if the cd
+ # to the rooting path fails, grep would search against the wrong
+ # cwd and produce wrong-scope matches.
if path_abs:
- # Absolute path: anchor at `%here%/<target>`, grep, restore to the
- # harness's tracked working_dir (so the lane cwd doesn't drift).
- # The `%here%/<target>` token is quoted as a single unit by
- # `_here_path` — survives whitespace / shell metachars cleanly.
- cd_line = f"cd {_here_path(translated_path)}"
- restore = _restore_cwd_cmd(session)
+ anchor_cmd = _anchor_path_cmd(translated_path)
+ restore_cmd = _restore_cwd_cmd(session)
else:
- # Relative path: lane cwd is the right reference. `prev` defaults
- # to "/" — for relative grep we just go back to whatever caller
- # asked, shell-quoted (or `%here%/...` for absolute prev).
translated_prev, prev_abs = _translate_path(prev)
- cd_line = f"cd {_q(translated_path)}"
+ anchor_cmd = f"cd {_q(translated_path)}"
if prev_abs:
- restore = f"cd {_here_path(translated_prev)}"
+ restore_cmd = _anchor_path_cmd(translated_prev)
else:
- restore = (
+ restore_cmd = (
f"cd {_q(translated_prev)}"
if translated_prev
- else f"cd {_here_path('')}"
+ else _anchor_path_cmd("")
)
- command = f"{cd_line}\ngrep {_q(pattern)}\n{restore}"
- return asyncio.run(_call_execute(command, use_daemon, session=session))
+
+ anchor = asyncio.run(_call_execute(anchor_cmd, use_daemon, session=session))
+ if _is_error(anchor):
+ return _parse_execute_result(anchor, "grep")
+ op = asyncio.run(_call_execute(
+ f"grep {_q(pattern)}", use_daemon, session=session,
+ ))
+ asyncio.run(_call_execute(restore_cmd, use_daemon, session=session))
+ return _parse_execute_result(op, "grep")
def click(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -688,10 +770,26 @@ def click(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:
"click: an element name is required — cannot click the tab root."
)
if is_absolute:
- command = _wrap_absolute(f"click {_q(translated)}", session)
- else:
- command = f"click {_q(translated)}"
- return asyncio.run(_call_execute(command, use_daemon, session=session))
+ # Split-and-check: anchor at tab root, halt if anchor fails,
+ # otherwise click the relative path, restore. Anchor success is
+ # load-bearing — clicking the wrong element if cwd has drifted
+ # could trigger an unintended action.
+ anchor = asyncio.run(_call_execute(
+ _anchor_path_cmd(""), use_daemon, session=session,
+ ))
+ if _is_error(anchor):
+ return _parse_execute_result(anchor, "click")
+ op = asyncio.run(_call_execute(
+ f"click {_q(translated)}", use_daemon, session=session,
+ ))
+ asyncio.run(_call_execute(
+ _restore_cwd_cmd(session), use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "click")
+ op = asyncio.run(_call_execute(
+ f"click {_q(translated)}", use_daemon, session=session,
+ ))
+ return _parse_execute_result(op, "click")
def open_url(url: str, use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -709,9 +807,10 @@ def open_url(url: str, use_daemon: bool = False, *, session: Any = None) -> dict
>>> open_url("https://example.com")
{"url": "https://example.com", "status": "loaded"}
"""
- return asyncio.run(
+ result = asyncio.run(
_call_execute(f"open {_q(url)}", use_daemon, session=session)
)
+ return _parse_execute_result(result, "open")
def reload(use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -724,7 +823,8 @@ def reload(use_daemon: bool = False, *, session: Any = None) -> dict:
Returns:
Dict with reload result
"""
- return asyncio.run(_call_execute("refresh", use_daemon, session=session))
+ result = asyncio.run(_call_execute("refresh", use_daemon, session=session))
+ return _parse_execute_result(result, "refresh")
def back(use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -737,7 +837,8 @@ def back(use_daemon: bool = False, *, session: Any = None) -> dict:
Returns:
Dict with navigation result
"""
- return asyncio.run(_call_execute("back", use_daemon, session=session))
+ result = asyncio.run(_call_execute("back", use_daemon, session=session))
+ return _parse_execute_result(result, "back")
def forward(use_daemon: bool = False, *, session: Any = None) -> dict:
@@ -750,7 +851,8 @@ def forward(use_daemon: bool = False, *, session: Any = None) -> dict:
Returns:
Dict with navigation result
"""
- return asyncio.run(_call_execute("forward", use_daemon, session=session))
+ result = asyncio.run(_call_execute("forward", use_daemon, session=session))
+ return _parse_execute_result(result, "forward")
def type_text(
@@ -839,11 +941,11 @@ def type_text(
# best-effort call. All four share the persisted lane via session.
if is_absolute:
anchor_result = asyncio.run(_call_execute(
- f"cd {_here_path('')}", use_daemon, session=session,
+ _anchor_path_cmd(""), use_daemon, session=session,
))
if _is_error(anchor_result):
# Anchor failed — we never moved, so no restore is needed.
- return anchor_result
+ return _parse_execute_result(anchor_result, "focus")
focus_result = asyncio.run(_call_execute(
f"focus {_q(translated_path)}", use_daemon, session=session,
@@ -856,7 +958,7 @@ def type_text(
asyncio.run(_call_execute(
_restore_cwd_cmd(session), use_daemon, session=session,
))
- return focus_result
+ return _parse_execute_result(focus_result, "focus")
type_result = asyncio.run(_call_execute(
f"type {_q(text)}", use_daemon, session=session,
@@ -870,7 +972,7 @@ def type_text(
_restore_cwd_cmd(session), use_daemon, session=session,
))
- return type_result
+ return _parse_execute_result(type_result, "type")
# ── Daemon control functions ───────────────────────────────────────────