Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(sdk): surface stderr/return_code in _parse_sse error path (#1344)

r33drichardsa6656e3bace0
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/http.py b/libs/python/cua-sandbox/cua_sandbox/transport/http.py
index 490fab1b10..22c98f1492 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/http.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/http.py
@@ -68,12 +68,51 @@ class HTTPTransport(Transport):
@staticmethod
def _parse_sse(text: str) -> Dict[str, Any]:
- """Extract the first ``data: {...}`` frame from an SSE response."""
+ """Extract the first ``data: {...}`` frame from an SSE response.
+
+ The server returns one of two failure shapes when ``success`` is
+ false:
+
+ 1. Generic handler error — ``{"success": false, "error": "<msg>"}``
+ 2. Shell-command shape — ``{"success": false, "stdout": "...",
+ "stderr": "...", "return_code": <n>}`` (no ``error`` key)
+
+ The old code stringified ``payload.get('error', 'unknown')`` for
+ both shapes, which turned every shell-command failure into
+ ``Remote error: unknown`` and hid the actual ``stderr`` + exit
+ code. That masking made ``Command timed out after 10s``,
+ ``UI hierchary dump failed``, and similar concrete failures
+ indistinguishable from a genuine internal error — the common
+ pattern where ``await sb.shell.run(cmd)`` returned non-zero
+ became a debugging dead end.
+
+ This rewrite preserves the ``error``-key path verbatim and falls
+ back to a composite ``return_code=...`` / ``stderr=...`` /
+ ``stdout=...`` string when no ``error`` key is present.
+ """
for line in text.splitlines():
if line.startswith("data: "):
payload = json.loads(line[6:])
if isinstance(payload, dict) and not payload.get("success", True):
- raise RuntimeError(f"Remote error: {payload.get('error', 'unknown')}")
+ if "error" in payload:
+ raise RuntimeError(f"Remote error: {payload['error']}")
+ # Shell-command shape: surface return_code/stderr/stdout.
+ parts = []
+ rc = payload.get("return_code")
+ if rc is not None:
+ parts.append(f"return_code={rc}")
+ stderr = (payload.get("stderr") or "").strip()
+ if stderr:
+ parts.append(f"stderr={stderr!r}")
+ stdout = (payload.get("stdout") or "").strip()
+ if stdout and not stderr:
+ # Only surface stdout when there's nothing on
+ # stderr — saves bloating the message for noisy
+ # successful-output commands that happened to
+ # return non-zero.
+ parts.append(f"stdout={stdout!r}")
+ detail = ", ".join(parts) or "no detail"
+ raise RuntimeError(f"Remote error: {detail}")
return payload
raise RuntimeError(f"No SSE data frame in response: {text[:200]}")
diff --git a/libs/python/cua-sandbox/tests/test_parse_sse.py b/libs/python/cua-sandbox/tests/test_parse_sse.py
new file mode 100644
index 0000000000..c6be2c27fc
--- /dev/null
+++ b/libs/python/cua-sandbox/tests/test_parse_sse.py
@@ -0,0 +1,93 @@
+"""Unit tests for ``HTTPTransport._parse_sse`` — the error-surfacing path.
+
+When the server returns ``{"success": false, ...}``, ``_parse_sse`` raises
+``RuntimeError`` with a message derived from the payload. The previous
+implementation stringified ``payload.get('error', 'unknown')``, which
+turned every shell-command failure (``{"success": false, "stdout": "",
+"stderr": "Command timed out after 10s", "return_code": 1}``) into the
+opaque ``Remote error: unknown`` — hiding the actual cause.
+
+These tests pin the new behavior:
+ * explicit ``error`` key still wins
+ * shell-command shape surfaces ``return_code`` + ``stderr``
+ * stdout only appears as a fallback when stderr is empty
+ * successful payloads pass through unchanged
+ * an SSE stream with no data frame raises a parseable error
+"""
+
+import pytest
+
+from cua_sandbox.transport.http import HTTPTransport
+
+
+def _sse(obj: str) -> str:
+ """Wrap a JSON payload in a single SSE data frame."""
+ return f"data: {obj}\n\n"
+
+
+class TestParseSSESurfacesFailures:
+ def test_success_payload_returned_unchanged(self):
+ out = HTTPTransport._parse_sse(_sse('{"success": true, "result": 42}'))
+ assert out == {"success": True, "result": 42}
+
+ def test_explicit_error_field_preserved_verbatim(self):
+ with pytest.raises(RuntimeError, match=r"Remote error: boom"):
+ HTTPTransport._parse_sse(
+ _sse('{"success": false, "error": "boom"}')
+ )
+
+ def test_shell_failure_surfaces_return_code_and_stderr(self):
+ with pytest.raises(RuntimeError) as exc:
+ HTTPTransport._parse_sse(
+ _sse(
+ '{"success": false, "stdout": "", '
+ '"stderr": "Command timed out after 10s", '
+ '"return_code": 1}'
+ )
+ )
+ msg = str(exc.value)
+ assert "Remote error:" in msg
+ assert "return_code=1" in msg
+ assert "Command timed out after 10s" in msg
+
+ def test_shell_failure_uses_stdout_only_when_stderr_empty(self):
+ with pytest.raises(RuntimeError) as exc:
+ HTTPTransport._parse_sse(
+ _sse(
+ '{"success": false, "stdout": "partial progress", '
+ '"stderr": "", "return_code": 137}'
+ )
+ )
+ msg = str(exc.value)
+ assert "return_code=137" in msg
+ assert "partial progress" in msg
+
+ def test_shell_failure_stdout_not_added_when_stderr_present(self):
+ """stderr wins over stdout when both are non-empty — avoids bloating
+ the message with noisy successful-command output that happened to
+ return non-zero."""
+ with pytest.raises(RuntimeError) as exc:
+ HTTPTransport._parse_sse(
+ _sse(
+ '{"success": false, '
+ '"stdout": "UI hierchary dumped to: /sdcard/ui.xml\\n", '
+ '"stderr": "Killed", "return_code": 137}'
+ )
+ )
+ msg = str(exc.value)
+ assert "Killed" in msg
+ assert "return_code=137" in msg
+ assert "UI hierchary dumped" not in msg # stdout suppressed
+
+ def test_shell_failure_with_no_detail_falls_back_cleanly(self):
+ with pytest.raises(RuntimeError, match=r"Remote error: no detail"):
+ HTTPTransport._parse_sse(_sse('{"success": false}'))
+
+ def test_missing_data_frame_raises(self):
+ with pytest.raises(RuntimeError, match=r"No SSE data frame"):
+ HTTPTransport._parse_sse("event: ping\n\n")
+
+ def test_ignores_content_before_data_line(self):
+ text = ":comment\nevent: message\ndata: " + '{"success": true, "ok": 1}' + "\n\n"
+ out = HTTPTransport._parse_sse(text)
+ assert out == {"success": True, "ok": 1}