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.

test(cua-driver): prune redundant SDK and binding tests (#4112)

Francesco Bonacci483265700fc1
diff --git a/libs/cua-driver/compat-fixtures/python-package.json b/libs/cua-driver/compat-fixtures/python-package.json
index 9446f29b08..35ce586b6a 100644
--- a/libs/cua-driver/compat-fixtures/python-package.json
+++ b/libs/cua-driver/compat-fixtures/python-package.json
@@ -49,10 +49,6 @@
"request_mac_os_permissions",
"run_cua_driver"
],
- "package_constructor_signatures": [
- "_connect_python_sdk(cls, socket_path)",
- "_create_python_sdk(cls, options = None)"
- ],
"wrapper_signatures": [
"get_binary_path() -> Path",
"run_cua_driver(args: Optional[list[str]] = None) -> int"
@@ -72,9 +68,12 @@
"async get_desktop_state(self, input: cua_driver._native_contract.GetDesktopStateInput) -> ToolResult",
"async get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult",
"async get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput",
+ "async get_window_state(self, input: cua_driver._native_contract.GetWindowStateInput) -> cua_driver._native_contract.WindowStateOutput",
"async hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult",
"is_available(self) -> bool",
+ "async list_apps(self, input: cua_driver._native_contract.ListAppsInput) -> cua_driver._native_contract.ListAppsOutput",
"async list_tools_json(self) -> str",
+ "async list_windows(self, input: cua_driver._native_contract.ListWindowsInput) -> cua_driver._native_contract.ListWindowsOutput",
"async metadata(self) -> DriverMetadata",
"async move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult",
"async press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult",
diff --git a/libs/cua-driver/python/tests/test_compatibility_contract.py b/libs/cua-driver/python/tests/test_compatibility_contract.py
index eb73a45446..f2284611bf 100644
--- a/libs/cua-driver/python/tests/test_compatibility_contract.py
+++ b/libs/cua-driver/python/tests/test_compatibility_contract.py
@@ -71,24 +71,6 @@ def _functions(module: ast.Module) -> dict[str, ast.FunctionDef | ast.AsyncFunct
}
-def test_current_native_window_methods_have_typed_outputs() -> None:
- module = _module(PACKAGE_ROOT / "src" / "cua_driver" / "_native.py")
- driver = next(
- node for node in module.body if isinstance(node, ast.ClassDef) and node.name == "CuaDriver"
- )
- methods = _functions(driver)
- for name, input_type, output_type in [
- ("list_apps", "ListAppsInput", "ListAppsOutput"),
- ("list_windows", "ListWindowsInput", "ListWindowsOutput"),
- ("get_window_state", "GetWindowStateInput", "WindowStateOutput"),
- ("click", "ClickInput", "ActionResult"),
- ]:
- assert _signature(methods[name]) == (
- f"async {name}(self, input: cua_driver._native_contract.{input_type})"
- f" -> cua_driver._native_contract.{output_type}"
- )
-
-
def test_click_position_preserves_released_uniffi_ordinals() -> None:
generated = (
PACKAGE_ROOT / "src" / "cua_driver" / "_native_contract.py"
@@ -131,13 +113,6 @@ def test_released_python_exports_and_signatures_remain_available() -> None:
}
assert set(expected["package_root_exports"]) <= actual_exports
- package_functions = _functions(package_module)
- package_signatures = {
- _signature(package_functions["_connect_python_sdk"]),
- _signature(package_functions["_create_python_sdk"]),
- }
- assert set(expected["package_constructor_signatures"]) == package_signatures
-
wrapper_functions = _functions(wrapper_module)
wrapper_signatures = {
_signature(wrapper_functions["get_binary_path"]),
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index a8f2cb3099..92a0ec2e7c 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -25,106 +25,14 @@ LIBRARY = Path(__file__).parents[1] / "src" / "cua_driver" / _library_name()
@unittest.skipUnless(LIBRARY.exists(), "host-native UniFFI library is not staged")
class GeneratedOptionsTests(unittest.TestCase):
- def test_visual_contract_dtos_construct_and_round_trip_through_uniffi(self) -> None:
- from cua_driver import _native_contract as contract
-
- def round_trip(converter, value):
- return converter.lift(converter.lower(value))
-
- request = contract.ParseVisualRegionsInput(
- capture_id="capture-1",
- options=contract.ParseVisualRegionsOptions(
- kinds=[contract.VisualRegionKind.TEXT, contract.VisualRegionKind.ICON],
- min_confidence=0.25,
- max_regions=200,
- ),
- )
- self.assertEqual(
- round_trip(contract._UniffiFfiConverterTypeParseVisualRegionsInput, request),
- request,
- )
+ def test_public_constructors_keep_released_signatures(self) -> None:
+ import inspect
- coordinate_space = contract.VisualActionCoordinateSpace.AFFINE(
- m11=0.5,
- m12=0.25,
- m21=-0.5,
- m22=2.0,
- tx=-1920.0,
- ty=10.0,
- )
- output = contract.ParseVisualRegionsOutput(
- schema="cua.visual_regions_v1",
- capture=contract.VisualCaptureProvenance(
- capture_id="capture-1",
- source=contract.VisualCaptureSource.PRIMARY_DESKTOP("primary"),
- screenshot=contract.VisualScreenshotReference(
- reference="png-1",
- width=1920,
- height=1080,
- mime_type="image/png",
- sha256=None,
- ),
- action_coordinate_space=coordinate_space,
- captured_at="2026-09-17T12:00:00Z",
- ),
- parser=contract.VisualParserMetadata(
- extension_id="visual-parser",
- extension_version="1.0.0",
- model_id="default",
- model_version="1",
- runtime="cpu",
- backend="onnx_runtime_cpu",
- model_source_revision="revision-1",
- model_manifest_sha256="a" * 64,
- onnx_runtime_version="1.26.0",
- onnx_runtime_library_sha256="b" * 64,
- fixture_sha256=None,
- ),
- regions=[
- contract.VisualRegion(
- id="text-1",
- kind=contract.VisualRegionKind.TEXT,
- bounds=contract.VisualRegionBounds(x=11, y=20, width=101, height=21),
- text="Apply",
- label=None,
- confidence=0.95,
- interactive=True,
- parent_id=None,
- group_id=None,
- reading_order=1,
- )
- ],
- warnings=[
- contract.VisualParseWarning(
- code="low_contrast",
- message="contrast was low",
- detail="text-1",
- )
- ],
- timing=contract.VisualParseTiming(
- duration_ms=18,
- preprocess_ms=3,
- inference_ms=12,
- ),
- request_id="parse-1",
- )
- lifted = round_trip(contract._UniffiFfiConverterTypeParseVisualRegionsOutput, output)
- self.assertEqual(lifted, output)
- self.assertEqual(
- lifted.capture.action_coordinate_space.m11,
- 0.5,
- )
+ from cua_driver import CuaDriver
- error = contract.VisualParseError(
- code=contract.VisualParseErrorCode.CAPTURE_NOT_FOUND,
- message="capture was not found",
- retryable=True,
- detail=None,
- )
- self.assertEqual(
- round_trip(contract._UniffiFfiConverterTypeVisualParseError, error),
- error,
- )
+ # Released callers pass these by keyword; the helpers behind them are private.
+ self.assertEqual(str(inspect.signature(CuaDriver.connect)), "(socket_path)")
+ self.assertEqual(str(inspect.signature(CuaDriver.create)), "(options=None)")
def test_action_target_is_public_and_uses_the_generated_contract(self) -> None:
import cua_driver
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rs
index 4fe242f113..8eeb387b78 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rs
@@ -207,32 +207,6 @@ async fn window_observation_is_advertised_and_dispatches_without_changing_result
);
}
-#[tokio::test]
-async fn window_observation_rejects_local_paths_and_private_fields_before_dispatch() {
- let executor = FakeExecutor::new(Value::Null, false);
- let receiver = DriverEnvelopeReceiver::new(executor.clone());
- for name in ["list_windows", "get_window_state"] {
- for (field, value) in [
- ("screenshot_out_file", json!("/tmp/receiver-test.png")),
- ("image_path", json!("/tmp/receiver-test.png")),
- ("file_path", json!("/tmp/receiver-test.txt")),
- ("_session_id", json!("untrusted")),
- ("_permission_mode", json!("unrestricted")),
- ("_private", Value::Null),
- ] {
- let mut arguments = json!({"pid": 42, "window_id": 7});
- arguments[field] = value;
- let mut envelope = request("rejected-observation");
- envelope.name = Some(name.into());
- envelope.arguments = Some(arguments);
- let response = receiver.exchange(receiver.generation(), envelope).await;
- assert_refusal(&response, "invalid_request", true);
- }
- }
- assert_eq!(executor.count(), 0);
- assert!(receiver.state.lock().unwrap().requests.is_empty());
-}
-
#[tokio::test]
async fn preserves_native_tool_error_code_and_message() {
let executor = FakeExecutor::new(Value::Null, false);
@@ -273,17 +247,22 @@ async fn invalid_envelopes_never_reach_executor() {
for id in ["", "bad/id"] {
invalid.push(request(id));
}
- for arguments in [
- json!({"_session_id": "untrusted"}),
- json!({"_permission_mode": "unrestricted"}),
- json!({"screenshot_out_file": "/tmp/receiver-test.png"}),
- json!({"image_path": "/tmp/receiver-test.png"}),
- json!({"file_path": "/tmp/receiver-test.txt"}),
- json!(["not", "an", "object"]),
- ] {
- let mut envelope = request("arguments");
- envelope.arguments = Some(arguments);
- invalid.push(envelope);
+ // Argument checks are tool-independent; window observation shares them.
+ for name in ["click", "list_windows", "get_window_state"] {
+ for arguments in [
+ json!({"_session_id": "untrusted"}),
+ json!({"_permission_mode": "unrestricted"}),
+ json!({"_private": null}),
+ json!({"screenshot_out_file": "/tmp/receiver-test.png"}),
+ json!({"image_path": "/tmp/receiver-test.png"}),
+ json!({"file_path": "/tmp/receiver-test.txt"}),
+ json!(["not", "an", "object"]),
+ ] {
+ let mut envelope = request("arguments");
+ envelope.name = Some(name.into());
+ envelope.arguments = Some(arguments);
+ invalid.push(envelope);
+ }
}
for name in [
"execute_shell",
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
index 2178f94425..fae3e47b15 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
@@ -947,13 +947,27 @@ mod tests {
}
#[tokio::test]
- async fn shutdown_joins_lifecycle_maintenance() {
+ async fn shutdown_stops_lifecycle_maintenance() {
let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();
let runtime = DriverRuntime::create(standard_options()).unwrap();
- assert!(runtime.lifecycle_maintenance.lock().unwrap().is_some());
+ // The maintenance thread owns the only receiver, so sends fail once it
+ // exits. This proves the thread stopped; it cannot distinguish the join
+ // from the thread's own prompt exit after the stop signal.
+ let probe = runtime
+ .lifecycle_maintenance
+ .lock()
+ .unwrap()
+ .as_ref()
+ .expect("runtime creation starts lifecycle maintenance")
+ .shutdown
+ .clone();
runtime.shutdown().await;
assert!(runtime.lifecycle_maintenance.lock().unwrap().is_none());
+ assert!(
+ probe.send(()).is_err(),
+ "lifecycle maintenance is still running after shutdown"
+ );
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
index fd46d1c140..76607ddb89 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
@@ -439,64 +439,6 @@ mod tests {
server.join().unwrap();
}
- #[tokio::test]
- async fn lost_action_response_is_reported_with_unknown_completion() {
- let directory = tempfile::tempdir().unwrap();
- let socket = directory.path().join("service.sock");
- let listener = UnixListener::bind(&socket).unwrap();
- let server = std::thread::spawn(move || {
- serve_compatible_metadata(&listener);
- let (stream, _) = listener.accept().unwrap();
- let mut reader = BufReader::new(stream.try_clone().unwrap());
- let mut writer = stream;
-
- let mut line = String::new();
- reader.read_line(&mut line).unwrap();
- let begin: DaemonRequest = serde_json::from_str(&line).unwrap();
- assert_eq!(begin.method, "trusted_session_begin");
- writeln!(
- writer,
- "{}",
- serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
- "resume_credential": "resume-test-1"
- })))
- .unwrap()
- )
- .unwrap();
-
- line.clear();
- reader.read_line(&mut line).unwrap();
- let call: DaemonRequest = serde_json::from_str(&line).unwrap();
- assert_eq!(call.method, "trusted_session_call");
- // Closing the accepted connection after reading the action leaves
- // its completion unknown to the client.
- });
-
- let client = ServiceSessionClient::connect_and_bind(
- socket.to_string_lossy().into_owned(),
- TrustedSessionOptions {
- public_session: "lost-response".into(),
- mode: SessionPermissionMode::Standard,
- ttl_seconds: 60,
- idle_ttl_seconds: 30,
- capability_manifest_path: None,
- bounded_manifest_path: None,
- },
- DaemonClientKind::Unknown,
- )
- .unwrap();
- assert!(matches!(
- client
- .invoke("click", serde_json::json!({"x": 1, "y": 1}))
- .await,
- Err(DriverError::ActionInterrupted {
- completion: crate::worker::ActionCompletion::Unknown,
- ..
- })
- ));
- server.join().unwrap();
- }
-
#[tokio::test]
async fn next_call_resumes_with_single_use_host_credential_after_disconnect() {
let directory = tempfile::tempdir().unwrap();
diff --git a/libs/cua-driver/typescript/test/compatibility-contract.test.mjs b/libs/cua-driver/typescript/test/compatibility-contract.test.mjs
index 8274a09359..4c64358086 100644
--- a/libs/cua-driver/typescript/test/compatibility-contract.test.mjs
+++ b/libs/cua-driver/typescript/test/compatibility-contract.test.mjs
@@ -14,39 +14,6 @@ const fixture = JSON.parse(
const normalize = (value) => value.replace(/\s+/g, " ").trim()
-// UniFFI tags ClickPosition by declaration order. cua-driver-rs-v0.28.2 released
-// 1=Coordinates and 2=Element; new variants may only be appended. The generated
-// binding check in CI ties this list back to the Rust declaration order.
-const RELEASED_CLICK_POSITION_ORDINALS = [
- [1, "Coordinates"],
- [2, "Element"],
- [3, "CapturedCoordinates"],
-]
-
-test("current native-window methods return typed outputs", () => {
- const declarations = normalize(fs.readFileSync(
- path.join(packageRoot, "dist", "native", "cua_driver_sdk.d.ts"), "utf8",
- ))
- for (const [method, input, output] of [
- ["listApps", "ListAppsInput", "ListAppsOutput"],
- ["listWindows", "ListWindowsInput", "ListWindowsOutput"],
- ["getWindowState", "GetWindowStateInput", "WindowStateOutput"],
- ["click", "ClickInput", "ActionResult"],
- ]) {
- assert.ok(declarations.includes(`${method}(input: ${input}, asyncOpts_?: { signal: AbortSignal; }): Promise<${output}>;`), method)
- }
-})
-
-test("ClickPosition preserves released UniFFI ordinals", () => {
- const generated = fs.readFileSync(
- path.join(packageRoot, "src", "native", "cua_driver_contract.ts"), "utf8",
- )
- const observed = [
- ...generated.matchAll(/case (\d+): return new ClickPosition\.(\w+)\(/g),
- ].map(([, ordinal, variant]) => [Number(ordinal), variant])
- assert.deepEqual(observed, RELEASED_CLICK_POSITION_ORDINALS)
-})
-
test("released package exports and declarations remain available", () => {
const packageJson = JSON.parse(
fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),
diff --git a/libs/cua-driver/typescript/test/fleet.test.mjs b/libs/cua-driver/typescript/test/fleet.test.mjs
index 55dd51b264..ad26114b1e 100644
--- a/libs/cua-driver/typescript/test/fleet.test.mjs
+++ b/libs/cua-driver/typescript/test/fleet.test.mjs
@@ -21,6 +21,7 @@ const nativeAvailable = existsSync(
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const bytes = (value) => encoder.encode(value).buffer;
+const TRANSPORT_FAILED = 'MCP Driver transport failed; completion is unknown';
function fixture({ sse = false } = {}) {
const sandbox = {
@@ -174,6 +175,9 @@ test(
throw new Error('secret-token-private-response');
};
await assert.rejects(connectFleetDriver(f), (error) => {
+ // The adapter converts the throw into a declared transport failure. Without
+ // that, the callback error panics in Rust and the reason becomes a drain timeout.
+ assert.deepEqual(error.inner, { reason: TRANSPORT_FAILED });
assert.doesNotMatch(String(error), /secret-token-private-response/);
assert.doesNotMatch(JSON.stringify(error), /secret-token-private-response/);
return true;
@@ -201,6 +205,9 @@ test(
sandbox: { namespace: 'tenant', claim: 'claim', name: 'guest', services: ['mcp'] },
}),
(error) => {
+ // The adapter enforces the limit as a transport failure before Rust parses
+ // the body; Rust's own limit would report a malformed negotiation instead.
+ assert.deepEqual(error.inner, { reason: TRANSPORT_FAILED });
assert.doesNotMatch(String(error), new RegExp(secret));
assert.doesNotMatch(JSON.stringify(error), new RegExp(secret));
return true;
diff --git a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
index 41851b6b93..7457b18c51 100644
--- a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
+++ b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
@@ -79,7 +79,7 @@ const server = net.createServer((connection) => {
})}\n`,
)
completedCalls += 1
- if (completedCalls === 9) server.close()
+ if (completedCalls === 10) server.close()
})
})
diff --git a/libs/cua-driver/typescript/test/native-loader.test.mjs b/libs/cua-driver/typescript/test/native-loader.test.mjs
index ff33fc89c0..71b315e075 100644
--- a/libs/cua-driver/typescript/test/native-loader.test.mjs
+++ b/libs/cua-driver/typescript/test/native-loader.test.mjs
@@ -114,7 +114,7 @@ test(
fixture.on("error", reject)
fixture.on("message", (message) => {
if (message.request) requests.push(message.request)
- if (requests.length === 9) resolve(requests)
+ if (requests.length === 10) resolve(requests)
})
}),
)
@@ -240,6 +240,14 @@ test(
options: ParseVisualRegionsOptions.new({}),
}),
)
+ // A pixel click bound to a capture must reach the daemon with its capture_id.
+ const capturedAction = await driver.click(
+ ClickInput.new({
+ position: new ClickPosition.CapturedCoordinates({ x: 56, y: 78, captureId: "capture-123" }),
+ target: new ActionTarget.Desktop({ displayId: "primary" }),
+ deliveryMode: InputDeliveryMode.Foreground,
+ }),
+ )
await requestsPromise
driver.uniffiDestroy()
@@ -270,6 +278,15 @@ test(
capture_id: "capture-123",
options: {},
})
+ assert.equal(capturedAction.effect, ActionEffect.Unverifiable)
+ assert.equal(requests[9].name, "click")
+ assert.deepEqual(requests[9].args, {
+ x: 56,
+ y: 78,
+ capture_id: "capture-123",
+ target: { kind: "desktop", display_id: "primary" },
+ delivery_mode: "foreground",
+ })
assert.equal(requests[0].name, "verify_state")
assert.deepEqual(requests[0].args, {
pid: 123,
diff --git a/libs/cua-driver/typescript/test/visual-contract.test.mjs b/libs/cua-driver/typescript/test/visual-contract.test.mjs
deleted file mode 100644
index 7db0a27e91..0000000000
--- a/libs/cua-driver/typescript/test/visual-contract.test.mjs
+++ /dev/null
@@ -1,140 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-
-import contractModule, {
- ActionTarget,
- ClickInput,
- ClickPosition,
- InputDeliveryMode,
- ParseVisualRegionsInput,
- ParseVisualRegionsOptions,
- ParseVisualRegionsOutput,
- VisualActionCoordinateSpace,
- VisualCaptureProvenance,
- VisualCaptureSource,
- VisualParseError,
- VisualParseErrorCode,
- VisualParseTiming,
- VisualParseWarning,
- VisualParserMetadata,
- VisualRegion,
- VisualRegionBounds,
- VisualRegionKind,
- VisualScreenshotReference,
-} from "../dist/native/cua_driver_contract.js"
-
-const roundTrip = (converter, value) =>
- converter.lift(converter.lower(value, size => new Uint8Array(size)))
-
-test("visual contract records round-trip through generated UniFFI converters", () => {
- contractModule.initialize()
-
- const input = ParseVisualRegionsInput.create({
- captureId: "capture-1",
- options: ParseVisualRegionsOptions.create({
- kinds: [VisualRegionKind.Text, VisualRegionKind.Icon],
- minConfidence: 0.75,
- maxRegions: 50,
- }),
- })
- assert.deepEqual(
- roundTrip(contractModule.converters.FfiConverterTypeParseVisualRegionsInput, input),
- input,
- )
-
- const capturedClick = ClickInput.create({
- target: new ActionTarget.Desktop({ displayId: "primary" }),
- position: new ClickPosition.CapturedCoordinates({
- x: 12,
- y: 34,
- captureId: "capture-1",
- }),
- deliveryMode: InputDeliveryMode.Foreground,
- session: undefined,
- button: undefined,
- count: undefined,
- })
- assert.deepEqual(
- roundTrip(contractModule.converters.FfiConverterTypeClickInput, capturedClick),
- capturedClick,
- )
-
- const output = ParseVisualRegionsOutput.create({
- schema: "cua.visual_regions_v1",
- capture: VisualCaptureProvenance.create({
- captureId: "capture-1",
- source: new VisualCaptureSource.PrimaryDesktop({ displayId: "primary" }),
- screenshot: VisualScreenshotReference.create({
- reference: "sha256:abc123",
- width: 1440,
- height: 900,
- mimeType: "image/png",
- sha256: "abc123",
- }),
- actionCoordinateSpace: new VisualActionCoordinateSpace.Affine({
- m11: 0.5,
- m12: 0.25,
- m21: -0.5,
- m22: 2,
- tx: 10.25,
- ty: 20.75,
- }),
- capturedAt: "2026-09-17T12:00:00Z",
- }),
- parser: VisualParserMetadata.create({
- extensionId: "cua-perception",
- extensionVersion: "1.0.0",
- modelId: "visual-parser",
- modelVersion: "2026-09-17",
- runtime: "local",
- backend: "onnx_runtime_cpu",
- modelSourceRevision: "revision-1",
- modelManifestSha256: "a".repeat(64),
- onnxRuntimeVersion: "1.26.0",
- onnxRuntimeLibrarySha256: "b".repeat(64),
- fixtureSha256: undefined,
- }),
- regions: [VisualRegion.create({
- id: "region-1",
- kind: VisualRegionKind.Text,
- bounds: VisualRegionBounds.create({ x: 11, y: 20, width: 4, height: 3 }),
- text: "Open",
- label: "Open button",
- confidence: 0.99,
- interactive: true,
- parentId: "group-1",
- groupId: "toolbar",
- readingOrder: 1,
- })],
- warnings: [VisualParseWarning.create({
- code: "partial-ocr",
- message: "Some text could not be read",
- detail: "region-2",
- })],
- timing: VisualParseTiming.create({
- durationMs: 18n,
- preprocessMs: 3n,
- inferenceMs: 12n,
- }),
- requestId: "request-1",
- })
- const restored = roundTrip(
- contractModule.converters.FfiConverterTypeParseVisualRegionsOutput,
- output,
- )
- assert.deepEqual(restored, output)
- assert.equal(restored.capture.actionCoordinateSpace.inner.m11, 0.5)
- assert.equal(restored.regions[0].bounds.width, 4)
- assert.equal(restored.warnings[0].detail, "region-2")
-
- const error = VisualParseError.create({
- code: VisualParseErrorCode.CaptureExpired,
- message: "Capture expired",
- retryable: true,
- detail: "capture-1",
- })
- assert.deepEqual(
- roundTrip(contractModule.converters.FfiConverterTypeVisualParseError, error),
- error,
- )
-})