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.

docs(cua-bench): demonstrate external collector traces (#5688)

injaneityebd339311279
diff --git a/docs/content/docs/cua-bench/guides/meta.json b/docs/content/docs/cua-bench/guides/meta.json
index 31246a1bb1..41d8f088a2 100644
--- a/docs/content/docs/cua-bench/guides/meta.json
+++ b/docs/content/docs/cua-bench/guides/meta.json
@@ -1,8 +1,4 @@
{
"title": "Guides",
- "pages": [
- "benchmarks",
- "write-a-task",
- "adapter-benchmarks"
- ]
+ "pages": ["benchmarks", "write-a-task", "adapter-benchmarks", "record-external-events"]
}
diff --git a/docs/content/docs/cua-bench/guides/record-external-events.mdx b/docs/content/docs/cua-bench/guides/record-external-events.mdx
new file mode 100644
index 0000000000..2905f145da
--- /dev/null
+++ b/docs/content/docs/cua-bench/guides/record-external-events.mdx
@@ -0,0 +1,98 @@
+---
+title: Record external events
+description: Import synthetic collector observations into a Cua Bench trace and inspect them in the existing viewer.
+---
+
+Use `Tracing.record()` to include JSON metadata from an external collector
+alongside action events and images. This guide demonstrates the existing trace
+format with a separate, synthetic JSONL producer. It needs no sandbox, device,
+credentials, or capture permissions.
+
+## Run the example
+
+From a checkout of the [Cua repository](https://github.com/trycua/cua), install
+the Cua Bench development environment and run the
+external collector example.
+Use a new output directory; the example refuses to overwrite an existing one.
+
+```bash skip="no-runner"
+cd libs/cua-bench
+uv sync --frozen --extra dev
+uv run python examples/external_collector.py --output /tmp/collector-trace
+uv run cb trace view /tmp/collector-trace
+```
+
+The viewer opens a completed trace containing four rows: a synthetic click with
+a generated image, followed by a network response, an application operation,
+and a network request. Expand the JSON fields to inspect their metadata and click
+the image to enlarge it. Press Enter in the terminal to stop the viewer server.
+Use an absolute path when opening this standalone trace directory.
+
+The recorder and tests run offline. The viewer's expandable JSON component
+currently loads JavaScript from `pfau-software.de`, so rendering that component
+in a browser requires access to that host.
+
+## How the bridge works
+
+The script launches itself with `--emit` as a separate process. That mode emits
+three fictional observations as JSONL, without importing Cua Bench. The parent
+waits for the finite batch, starts one `Tracing(env=None)` instance, records a
+synthetic action, and passes each observation to `record(event_name, data)`.
+It saves the combined dataset with `save_to_disk()`.
+
+All events and the image use the existing trace schema and viewer. The example
+adds no collector registration API, event schema, or viewer plugin. Its JSONL
+envelope and metadata names are example conventions:
+
+| Field | Purpose |
+| --------------------- | -------------------------------------------------------------------------------- |
+| `action_id` | Connect observations to the example's synthetic action. |
+| `collector` | Identify the producer. |
+| `source_sequence` | Preserve the producer's emission order. |
+| `source_timestamp_ms` | Preserve the observation time supplied by the producer. |
+| `clock_domain` | Describe the source clock; this example uses a fictional session-relative clock. |
+| `synthetic` | Mark these observations as generated fixtures. |
+| `payload` | Hold collector-specific nested JSON. |
+
+The recorder's top-level `timestamp` is the time of ingestion. It does not
+replace or normalize source timestamps. Rows remain in recording order: the
+example deliberately emits its response before its request to demonstrate that
+late observations are preserved without automatic sorting.
+
+## Adapt it to a collector
+
+Replace the synthetic producer with a collector you operate, and translate its
+output into JSON-serializable metadata before calling `record()`. Start the
+trajectory first; calls made before `start()` are ignored. Calling `start()`
+again clears the current recording.
+
+Keep one owner of the recorder. For concurrent collectors, queue observations
+to that owner and define ordering and shutdown behavior in your integration.
+This example buffers a small, finite batch; a long-running collector needs
+bounded buffering, input validation, error handling, and a stop/flush mechanism.
+Save after draining the queue. The existing viewer displays a saved snapshot,
+not a live event stream.
+
+Preserve each source's clock domain and any available process, request, or
+operation identifiers. Establish clock offsets before comparing observations
+from different devices. Temporal proximity alone does not prove that a click
+caused an OS operation or network request. The example assigns its action ID
+explicitly; it does not discover causal relationships.
+
+Only collect data you are authorized to inspect. Remove credentials, cookies,
+tokens, and sensitive payload fields before recording. Large captures should
+stay in access-controlled artifacts, with suitable references and checksums in
+the trace metadata. The viewer displays those references as JSON; it does not
+automatically load external artifacts.
+
+## Validate the integration
+
+The regression tests run the example in a subprocess, reload the dataset, and
+fetch the HTML served by the existing viewer over loopback. They verify event
+order, correlation metadata, nested JSON with Unicode and HTML-sensitive text,
+and the embedded image. They do not launch a browser or capture real OS/network
+events.
+
+```bash skip="no-runner"
+uv run --frozen pytest -q cua_bench/tests/test_external_collector.py
+```
diff --git a/libs/cua-bench/cua_bench/tests/test_external_collector.py b/libs/cua-bench/cua_bench/tests/test_external_collector.py
new file mode 100644
index 0000000000..132134b64a
--- /dev/null
+++ b/libs/cua-bench/cua_bench/tests/test_external_collector.py
@@ -0,0 +1,95 @@
+"""External JSONL survives recording, persistence and the existing viewer."""
+
+from __future__ import annotations
+
+import base64
+import json
+import subprocess
+import sys
+from argparse import Namespace
+from html.parser import HTMLParser
+from io import BytesIO
+from pathlib import Path
+from urllib.request import ProxyHandler, build_opener
+
+import pytest
+from datasets import load_from_disk
+from PIL import Image
+
+EXAMPLE = Path(__file__).resolve().parents[2] / "examples" / "external_collector.py"
+
+
+def recorded_trace(tmp_path):
+ output = tmp_path / "collector trace"
+ subprocess.run(
+ [sys.executable, str(EXAMPLE), "--output", str(output)],
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ return output
+
+
+def test_external_collector_round_trip(recorded_trace):
+ rows = list(load_from_disk(str(recorded_trace)))
+ assert [row["event_name"] for row in rows] == [
+ "action",
+ "external.network.response",
+ "external.application.operation",
+ "external.network.request",
+ ]
+ assert {row["trajectory_id"] for row in rows} == {"external-collector-example"}
+ payloads = [json.loads(row["data_json"]) for row in rows]
+ assert {payload["action_id"] for payload in payloads} == {"submit-1"}
+ # Recorder insertion order is retained; collector timestamps do not sort rows.
+ assert [payload["source_timestamp_ms"] for payload in payloads[1:]] == [30, 20, 10]
+ assert [payload["source_sequence"] for payload in payloads[1:]] == [0, 1, 2]
+ assert payloads[2]["payload"]["arguments"]["label"] == 'Demo <form> "✓"'
+ assert payloads[1]["payload"]["request_id"] == payloads[3]["payload"]["request_id"]
+ assert rows[0]["data_images"][0].size == (160, 90)
+ assert all(row["data_images"] == [] for row in rows[1:])
+
+
+class ViewerContent(HTMLParser):
+ def __init__(self):
+ super().__init__()
+ self.json_values = []
+ self.images = []
+
+ def handle_starttag(self, tag, attrs):
+ attrs = dict(attrs)
+ if tag == "andypf-json-viewer":
+ self.json_values.append(json.loads(attrs["data"]))
+ if tag == "img" and attrs.get("class") == "trace-img":
+ self.images.append(attrs["src"])
+
+
+def test_external_collector_in_existing_viewer(recorded_trace, monkeypatch):
+ from cua_bench.cli.commands import trace
+
+ pages = []
+
+ def read_page(url):
+ # Bypass developer proxy settings for the viewer's loopback server.
+ with build_opener(ProxyHandler({})).open(url, timeout=10) as response:
+ pages.append(response.read().decode("utf-8"))
+ return True
+
+ # Fetch the real served HTML without launching a browser or waiting for input.
+ monkeypatch.setattr(trace.webbrowser, "open", read_page)
+ monkeypatch.setattr("builtins.input", lambda: "")
+ assert trace.cmd_view(Namespace(identifier=str(recorded_trace))) == 0
+ assert len(pages) == 1
+ content = ViewerContent()
+ content.feed(pages[0])
+ rows = list(load_from_disk(str(recorded_trace)))
+ assert content.json_values[::2] == [
+ {key: row[key] for key in ("event_name", "timestamp", "trajectory_id")} for row in rows
+ ]
+ assert content.json_values[1::2] == [json.loads(row["data_json"]) for row in rows]
+ assert len(content.images) == 1
+ assert content.images[0].startswith("data:image/png;base64,")
+ with Image.open(BytesIO(base64.b64decode(content.images[0].split(",", 1)[1]))) as image:
+ assert image.size == (160, 90)
diff --git a/libs/cua-bench/examples/external_collector.py b/libs/cua-bench/examples/external_collector.py
new file mode 100644
index 0000000000..fe5e52ad73
--- /dev/null
+++ b/libs/cua-bench/examples/external_collector.py
@@ -0,0 +1,104 @@
+"""Record synthetic external events alongside an action, without a sandbox.
+
+From libs/cua-bench, run:
+ uv run python examples/external_collector.py --output /tmp/collector-trace
+ uv run cb trace view /tmp/collector-trace
+
+The --emit mode is a standalone JSONL producer. The parent replays its output
+through Tracing.record; it does not install an OS or network collector.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+
+def emit_events() -> None:
+ """Emit deliberately out-of-order, fictional collector observations."""
+ observations = [
+ (
+ "external.network.response",
+ 30,
+ {"request_id": "request-1", "status": 200},
+ ),
+ (
+ "external.application.operation",
+ 20,
+ {"operation": "submit", "arguments": {"label": 'Demo <form> "✓"'}},
+ ),
+ (
+ "external.network.request",
+ 10,
+ {"request_id": "request-1", "method": "POST", "url": "https://example.test/submit"},
+ ),
+ ]
+ for sequence, (event_name, timestamp, payload) in enumerate(observations):
+ print(
+ json.dumps(
+ {
+ "event_name": event_name,
+ "data": {
+ "collector": "synthetic-jsonl",
+ "source_sequence": sequence,
+ "source_timestamp_ms": timestamp,
+ "clock_domain": "synthetic-session-relative",
+ "action_id": "submit-1",
+ "synthetic": True,
+ "payload": payload,
+ },
+ },
+ ensure_ascii=False,
+ ),
+ flush=True,
+ )
+
+
+def record_example(output: Path) -> None:
+ """Import a finite collector batch through one recorder owner."""
+ from cua_bench.tracing import Tracing
+ from PIL import Image
+
+ if output.exists():
+ raise FileExistsError(f"Choose a new trace directory: {output}")
+
+ collector = subprocess.run(
+ [sys.executable, str(Path(__file__).resolve()), "--emit"],
+ check=True,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ timeout=30,
+ )
+ tracing = Tracing(env=None)
+ tracing.start("external-collector-example")
+ tracing.record(
+ "action",
+ {"action_id": "submit-1", "action": "click", "target": "Submit", "synthetic": True},
+ [Image.new("RGB", (160, 90), color="navy")],
+ )
+ for line in collector.stdout.splitlines():
+ event = json.loads(line)
+ tracing.record(event["event_name"], event["data"])
+ tracing.save_to_disk(str(output))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--emit", action="store_true", help="Write synthetic JSONL to stdout")
+ mode.add_argument("--output", type=Path, help="New directory for the combined trace")
+ args = parser.parse_args()
+ if args.emit:
+ emit_events()
+ else:
+ output = args.output.expanduser().resolve()
+ record_example(output)
+ print(f"Saved trace to {output}")
+
+
+if __name__ == "__main__":
+ main()