diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba568cdfc6..6e6b242236 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -142,6 +142,10 @@ jobs: run: | sudo apt-get update sudo apt-get install -y --no-install-recommends \ + libgstreamer1.0-dev \ + libgstreamer-plugins-base1.0-dev \ + libtesseract-dev \ + libleptonica-dev \ pkg-config \ build-essential \ libxcb1-dev \ @@ -328,11 +332,11 @@ jobs: if: runner.os != 'Windows' run: cargo test --locked -p openbitfun-desktop --lib - # Exercise production UIA/control code even if the Tauri test executable - # cannot load. Interactive delivery fixtures remain explicitly ignored. - - name: Run Windows Computer Use provider regressions - if: runner.os == 'Windows' - run: node scripts/test-windows-computer-use-native.mjs + # Native tests moved out of Desktop with the shared provider. Run them + # on every OS, independently of Tauri's Windows test-loader limitation. + # Interactive delivery fixtures remain explicitly ignored. + - name: Run shared Computer Use provider regressions + run: cargo test --locked -p openbitfun-computer-use --lib # Tauri issue #13419 prevents some Windows MSVC lib-test harnesses from # entering Rust's test runner at all. Keep probing on every run so the diff --git a/.github/workflows/cli-package-manual.yml b/.github/workflows/cli-package-manual.yml index 797892d0de..eeab8bf311 100644 --- a/.github/workflows/cli-package-manual.yml +++ b/.github/workflows/cli-package-manual.yml @@ -142,7 +142,13 @@ jobs: shell: bash run: | sudo apt-get update + # Jammy runners may have conflicting LLVM libunwind development files. sudo apt-get install -y --no-install-recommends \ + libunwind-dev \ + libgstreamer1.0-dev \ + libgstreamer-plugins-base1.0-dev \ + libtesseract-dev \ + libleptonica-dev \ pkg-config \ build-essential \ libxcb1-dev \ diff --git a/.github/workflows/linux-binaries.yml b/.github/workflows/linux-binaries.yml index 0d4ca661e0..151634cc78 100644 --- a/.github/workflows/linux-binaries.yml +++ b/.github/workflows/linux-binaries.yml @@ -100,6 +100,8 @@ jobs: shell: bash run: | sudo apt-get update + # Select GStreamer's libunwind headers explicitly so apt can replace + # the conflicting LLVM libunwind-dev package preinstalled on Jammy. sudo apt-get install -y --no-install-recommends \ build-essential \ clang \ @@ -109,6 +111,11 @@ jobs: libxcb-render0-dev \ libxcb-shape0-dev \ libxcb-xfixes0-dev \ + libunwind-dev \ + libgstreamer1.0-dev \ + libgstreamer-plugins-base1.0-dev \ + libtesseract-dev \ + libleptonica-dev \ pkg-config \ python3 diff --git a/AGENTS-CN.md b/AGENTS-CN.md index c25f803074..57b2844839 100644 --- a/AGENTS-CN.md +++ b/AGENTS-CN.md @@ -27,7 +27,7 @@ Stable Contracts and Security Control Plane 的边界以 | 1 | 接口与入口层 | `src/apps/*`, `src/web-ui`, `src/mobile-web`, `OpenBitFun-Installer`, `tests/e2e`, `src/crates/interfaces` | 产品宿主、命令、UI 入口、协议接口和跨形态测试 | desktop、CLI、server、relay、Web UI、mobile web、installer、E2E、`acp`、`sdk-host` | 最近的本地 `AGENTS.md`;[interfaces](src/crates/interfaces/AGENTS.md) | | 2 | 产品组装层 | `src/crates/assembly` | 兼容导出、产品能力选择、product-full 接线、不可变内置 Agent 内容、adapter/service 注册和生态无关的来源协调 | `agent-content`, `core`, `external-sources`, `product-capabilities` | [AGENTS.md](src/crates/assembly/AGENTS.md) | | 3 | 适配层 | `src/crates/adapters` | AI/transport/WebDriver 协议 adapter、外部 AI work source adapter(OpenCode/Claude Code/Codex/Zcode)和外部 provider 转换 | `agent-runtime-ipc`、`ai-adapters`, `opencode-adapter`, `claude-code-adapter`, `codex-adapter`, `zcode-adapter`, `static-hook-support`, `transport`, `webdriver` | [AGENTS.md](src/crates/adapters/AGENTS.md) | -| 4 | 服务实现层 | `src/crates/services` | 可复用 OS、filesystem、terminal、MCP、remote、git、watch、process、session persistence primitives、network 和 MiniApp runtime IO 实现 | `services-core`, `services-integrations`, `relay-service`, `page-function-runtime`, `terminal` | [AGENTS.md](src/crates/services/AGENTS.md) | +| 4 | 服务实现层 | `src/crates/services` | 可复用 OS、filesystem、terminal、MCP、remote、git、watch、process、session persistence primitives、network 和 MiniApp runtime IO 实现 | `services-core`, `services-integrations`, `computer-use`, `relay-service`, `page-function-runtime`, `terminal` | [AGENTS.md](src/crates/services/AGENTS.md) | | 5 | 执行原语层 | `src/crates/execution` | 可移植 Agent Runtime、命名工作流策略、stream、插件运行时客户端、typed-service、tool-contract、tool-group 和 tool-execution 构件 | `agent-runtime`, `agent-workflows`, `agent-stream`, `tool-contracts`, `plugin-runtime-client`, `runtime-services`, `tool-provider-groups`, `tool-execution` | [AGENTS.md](src/crates/execution/AGENTS.md) | | 6 | 稳定契约与产品领域层 | `src/crates/contracts` | 跨层共享 DTO、事件形状、runtime port、产品领域契约和策略 | `core-types`, `events`, `runtime-ports`, `product-domains` | [AGENTS.md](src/crates/contracts/AGENTS.md) | diff --git a/AGENTS.md b/AGENTS.md index b390920776..2b64c51a0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ Keep crate dependencies inside each layer to the smallest set needed. | 1 | Interfaces and entrypoints | `src/apps/*`, `src/web-ui`, `src/mobile-web`, `OpenBitFun-Installer`, `tests/e2e`, `src/crates/interfaces` | Product hosts, commands, UI entrypoints, protocol interfaces, and cross-surface tests | desktop, CLI, server, relay, Web UI, mobile web, installer, E2E, `acp`, `app-server`, `sdk-host` | nearest local `AGENTS.md`; [interfaces](src/crates/interfaces/AGENTS.md) | | 2 | Product assembly | `src/crates/assembly` | Compatibility exports, product capability selection, product-full wiring, immutable built-in Agent content, adapter/service registration, and ecosystem-neutral source coordination | `agent-content`, `core`, `external-sources`, `product-capabilities` | [AGENTS.md](src/crates/assembly/AGENTS.md) | | 3 | Adapters | `src/crates/adapters` | AI/transport/WebDriver protocol adapters, external AI work source adapters (OpenCode/Claude Code/Codex/Zcode), and external-provider translation | `agent-runtime-ipc`, `ai-adapters`, `opencode-adapter`, `claude-code-adapter`, `codex-adapter`, `zcode-adapter`, `static-hook-support`, `transport`, `webdriver` | [AGENTS.md](src/crates/adapters/AGENTS.md) | -| 4 | Services | `src/crates/services` | Reusable OS, filesystem, terminal, MCP, remote, git, watch, process, session persistence primitives, MiniApp runtime IO, and network implementations | `services-core`, `services-integrations`, `miniapp-market-service`, `relay-service`, `page-function-runtime`, `terminal` | [AGENTS.md](src/crates/services/AGENTS.md) | +| 4 | Services | `src/crates/services` | Reusable OS, filesystem, terminal, MCP, remote, git, watch, process, session persistence primitives, MiniApp runtime IO, and network implementations | `services-core`, `services-integrations`, `computer-use`, `miniapp-market-service`, `relay-service`, `page-function-runtime`, `terminal` | [AGENTS.md](src/crates/services/AGENTS.md) | | 5 | Execution primitives | `src/crates/execution` | Portable Agent Runtime, named-workflow policy, stream, plugin runtime client, typed-service, tool-contract, tool-group, and tool-execution building blocks | `agent-runtime`, `agent-workflows`, `agent-stream`, `tool-contracts`, `plugin-runtime-client`, `runtime-services`, `tool-provider-groups`, `tool-execution` | [AGENTS.md](src/crates/execution/AGENTS.md) | | 6 | Stable contracts and product domains | `src/crates/contracts` | Shared DTOs, event shapes, runtime ports, and product domain contracts/policies | `core-types`, `events`, `runtime-ports`, `product-domains` | [AGENTS.md](src/crates/contracts/AGENTS.md) | diff --git a/Cargo.lock b/Cargo.lock index 87fb61f7d9..15fe2a204e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -438,7 +438,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" dependencies = [ "atk-sys", - "glib 0.18.5", + "glib", "libc", ] @@ -448,10 +448,10 @@ version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -469,12 +469,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "atomic_refcell" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" - [[package]] name = "atspi" version = "0.29.0" @@ -664,28 +658,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bindgen" -version = "0.64.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4243e6031260db77ede97ad86c27e501d646a27ab57b59a574f725d98ab1fb4" -dependencies = [ - "bitflags 1.3.2", - "cexpr", - "clang-sys", - "lazy_static", - "lazycell", - "log", - "peeking_take_while", - "proc-macro2", - "quote", - "regex", - "rustc-hash 1.1.0", - "shlex 1.3.0", - "syn 1.0.109", - "which 4.4.2", -] - [[package]] name = "bit-set" version = "0.8.0" @@ -921,7 +893,7 @@ checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" dependencies = [ "bitflags 2.11.1", "cairo-sys-rs", - "glib 0.18.5", + "glib", "libc", "once_cell", "thiserror 1.0.69", @@ -933,9 +905,9 @@ version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" dependencies = [ - "glib-sys 0.18.1", + "glib-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -1022,15 +994,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom 7.1.3", -] - [[package]] name = "cfb" version = "0.7.3" @@ -1060,17 +1023,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" dependencies = [ "smallvec", - "target-lexicon 0.12.16", -] - -[[package]] -name = "cfg-expr" -version = "0.20.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917" -dependencies = [ - "smallvec", - "target-lexicon 0.13.5", + "target-lexicon", ] [[package]] @@ -1158,17 +1111,6 @@ dependencies = [ "inout", ] -[[package]] -name = "clang-sys" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" -dependencies = [ - "glob", - "libc", - "libloading 0.8.9", -] - [[package]] name = "clap" version = "4.6.4" @@ -2422,6 +2364,7 @@ dependencies = [ "log", "objc2 0.5.2", "windows 0.56.0", + "x11rb", "xkbcommon", "xkeysym", ] @@ -2992,7 +2935,7 @@ dependencies = [ "gdk-pixbuf", "gdk-sys", "gio", - "glib 0.18.5", + "glib", "libc", "pango", ] @@ -3005,7 +2948,7 @@ checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" dependencies = [ "gdk-pixbuf-sys", "gio", - "glib 0.18.5", + "glib", "libc", "once_cell", ] @@ -3016,11 +2959,11 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" dependencies = [ - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -3031,13 +2974,13 @@ checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" dependencies = [ "cairo-sys-rs", "gdk-pixbuf-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", "pango-sys", "pkg-config", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -3047,11 +2990,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" dependencies = [ "gdk-sys", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", "pkg-config", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -3063,7 +3006,7 @@ dependencies = [ "gdk", "gdkx11-sys", "gio", - "glib 0.18.5", + "glib", "libc", "x11", ] @@ -3075,9 +3018,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" dependencies = [ "gdk-sys", - "glib-sys 0.18.1", + "glib-sys", "libc", - "system-deps 6.2.2", + "system-deps", "x11", ] @@ -3192,8 +3135,8 @@ dependencies = [ "futures-core", "futures-io", "futures-util", - "gio-sys 0.18.1", - "glib 0.18.5", + "gio-sys", + "glib", "libc", "once_cell", "pin-project-lite", @@ -3207,26 +3150,13 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", "winapi", ] -[[package]] -name = "gio-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0071fe88dba8e40086c8ff9bbb62622999f49628344b1d1bf490a48a29d80f22" -dependencies = [ - "glib-sys 0.21.5", - "gobject-sys 0.21.5", - "libc", - "system-deps 7.0.8", - "windows-sys 0.61.2", -] - [[package]] name = "git2" version = "0.21.0" @@ -3251,10 +3181,10 @@ dependencies = [ "futures-executor", "futures-task", "futures-util", - "gio-sys 0.18.1", - "glib-macros 0.18.5", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", "libc", "memchr", "once_cell", @@ -3262,27 +3192,6 @@ dependencies = [ "thiserror 1.0.69", ] -[[package]] -name = "glib" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16de123c2e6c90ce3b573b7330de19be649080ec612033d397d72da265f1bd8b" -dependencies = [ - "bitflags 2.11.1", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys 0.21.5", - "glib-macros 0.21.5", - "glib-sys 0.21.5", - "gobject-sys 0.21.5", - "libc", - "memchr", - "smallvec", -] - [[package]] name = "glib-macros" version = "0.18.5" @@ -3297,19 +3206,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "glib-macros" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf59b675301228a696fe01c3073974643365080a76cc3ed5bc2cbc466ad87f17" -dependencies = [ - "heck 0.5.0", - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "glib-sys" version = "0.18.1" @@ -3317,17 +3213,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" dependencies = [ "libc", - "system-deps 6.2.2", -] - -[[package]] -name = "glib-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d95e1a3a19ae464a7286e14af9a90683c64d70c02532d88d87ce95056af3e6c" -dependencies = [ - "libc", - "system-deps 7.0.8", + "system-deps", ] [[package]] @@ -3367,20 +3253,9 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" dependencies = [ - "glib-sys 0.18.1", - "libc", - "system-deps 6.2.2", -] - -[[package]] -name = "gobject-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dca35da0d19a18f4575f3cb99fe1c9e029a2941af5662f326f738a21edaf294" -dependencies = [ - "glib-sys 0.21.5", + "glib-sys", "libc", - "system-deps 7.0.8", + "system-deps", ] [[package]] @@ -3431,99 +3306,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "gstreamer" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8251db223ca38d9aefaf3d19f6f11581a9123cd12dacebd8b9e182da965023" -dependencies = [ - "cfg-if", - "futures-channel", - "futures-core", - "futures-util", - "glib 0.21.5", - "gstreamer-sys", - "itertools 0.14.0", - "kstring", - "libc", - "muldiv", - "num-integer", - "num-rational", - "option-operations", - "pastey", - "pin-project-lite", - "smallvec", - "thiserror 2.0.19", -] - -[[package]] -name = "gstreamer-app" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3da7017b2a2fa5cdf9123b1603947ea24174f6d8cea0ea673411df824c811921" -dependencies = [ - "futures-core", - "futures-sink", - "glib 0.21.5", - "gstreamer", - "gstreamer-app-sys", - "gstreamer-base", - "libc", -] - -[[package]] -name = "gstreamer-app-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fa9f1b12b546aea543c15a0fdbc5a53617902a74f6d357a32b6a9fb4bc4725c" -dependencies = [ - "glib-sys 0.21.5", - "gstreamer-base-sys", - "gstreamer-sys", - "libc", - "system-deps 7.0.8", -] - -[[package]] -name = "gstreamer-base" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9375f9a12120a8ee17b765c816c9b23861ce258def77b0ee40a05acb00c74972" -dependencies = [ - "atomic_refcell", - "cfg-if", - "glib 0.21.5", - "gstreamer", - "gstreamer-base-sys", - "libc", -] - -[[package]] -name = "gstreamer-base-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b844f3559b6ab0379b4b771261643783ae4e0ffa71d5f5f46e33b7acf66b752" -dependencies = [ - "glib-sys 0.21.5", - "gobject-sys 0.21.5", - "gstreamer-sys", - "libc", - "system-deps 7.0.8", -] - -[[package]] -name = "gstreamer-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5d37c1a599ae57b8186948bd5699f2dbfc044baea9d400228b489a85bcf2759" -dependencies = [ - "cfg-if", - "glib-sys 0.21.5", - "gobject-sys 0.21.5", - "libc", - "system-deps 7.0.8", -] - [[package]] name = "gtk" version = "0.18.2" @@ -3537,7 +3319,7 @@ dependencies = [ "gdk", "gdk-pixbuf", "gio", - "glib 0.18.5", + "glib", "gtk-sys", "gtk3-macros", "libc", @@ -3555,12 +3337,12 @@ dependencies = [ "cairo-sys-rs", "gdk-pixbuf-sys", "gdk-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", "pango-sys", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -4360,7 +4142,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" dependencies = [ "bitflags 1.3.2", - "glib 0.18.5", + "glib", "javascriptcore-rs-sys", ] @@ -4370,10 +4152,10 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -4654,15 +4436,6 @@ dependencies = [ "libc", ] -[[package]] -name = "kstring" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e" -dependencies = [ - "static_assertions", -] - [[package]] name = "kurbo" version = "0.13.1" @@ -4684,12 +4457,6 @@ dependencies = [ "spin", ] -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "lebe" version = "0.5.3" @@ -4712,38 +4479,6 @@ dependencies = [ "url", ] -[[package]] -name = "leptess" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8964e3d3270be667dda2d0026e8c77011bafaad33936011b93750489987513" -dependencies = [ - "tesseract-plumbing", - "thiserror 1.0.69", -] - -[[package]] -name = "leptonica-plumbing" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7a74c43d6f090d39158d233f326f47cd8bba545217595c93662b4e31156f42" -dependencies = [ - "leptonica-sys", - "libc", - "thiserror 1.0.69", -] - -[[package]] -name = "leptonica-sys" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da627c72b2499a8106f4dd33143843015e4a631f445d561f3481f7fba35b6151" -dependencies = [ - "bindgen", - "pkg-config", - "vcpkg", -] - [[package]] name = "lettre" version = "0.11.23" @@ -4777,7 +4512,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" dependencies = [ - "glib 0.18.5", + "glib", "gtk", "gtk-sys", "libappindicator-sys", @@ -5323,12 +5058,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "muldiv" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" - [[package]] name = "ndk" version = "0.9.0" @@ -6226,6 +5955,7 @@ dependencies = [ "openbitfun-agent-runtime-ipc", "openbitfun-agent-tools", "openbitfun-app-server", + "openbitfun-computer-use", "openbitfun-core", "openbitfun-core-types", "openbitfun-events", @@ -6278,6 +6008,47 @@ dependencies = [ "url", ] +[[package]] +name = "openbitfun-computer-use" +version = "1.0.8" +dependencies = [ + "async-trait", + "atspi", + "base64 0.22.1", + "block2 0.6.2", + "cc", + "chrono", + "core-foundation 0.9.4", + "core-graphics 0.23.2", + "dirs 6.0.0", + "dispatch", + "enigo", + "foreign-types 0.5.0", + "futures", + "image 0.25.10", + "libc", + "log", + "objc2 0.6.4", + "objc2-app-kit", + "objc2-foundation", + "objc2-vision", + "openbitfun-agent-tools", + "openbitfun-core-types", + "openbitfun-services-core", + "pkg-config", + "screenshots", + "serde", + "serde_json", + "sha1 0.10.7", + "sha2", + "tempfile", + "tokio", + "tool-runtime", + "windows 0.61.3", + "windows-core 0.61.2", + "x11rb", +] + [[package]] name = "openbitfun-config-contracts" version = "1.0.8" @@ -6418,31 +6189,24 @@ dependencies = [ "alloc-stdlib", "anyhow", "async-trait", - "atspi", "axum", "base64 0.22.1", "bitflags 2.11.1", "block2 0.6.2", "brotli-decompressor", "bzip2 0.5.2", - "cc", "chrono", "core-foundation 0.9.4", "core-graphics 0.23.2", "dark-light", "dirs 6.0.0", "dispatch", - "enigo", "flate2", - "foreign-types 0.5.0", "futures", - "gstreamer", - "gstreamer-app", "gtk", "ignore", "image 0.25.10", "keepawake", - "leptess", "libc", "log", "mime_guess", @@ -6451,10 +6215,10 @@ dependencies = [ "objc2 0.6.4", "objc2-app-kit", "objc2-foundation", - "objc2-vision", "openbitfun-acp", "openbitfun-agent-runtime", "openbitfun-agent-tools", + "openbitfun-computer-use", "openbitfun-core", "openbitfun-core-types", "openbitfun-events", @@ -6788,7 +6552,7 @@ dependencies = [ "tokio", "ts-rs", "url", - "which 8.0.5", + "which", ] [[package]] @@ -6972,7 +6736,7 @@ dependencies = [ "thiserror 2.0.19", "tokio", "uuid", - "which 8.0.5", + "which", "win32job", "windows 0.61.3", "zip 4.6.1", @@ -7048,7 +6812,7 @@ dependencies = [ "url", "urlencoding", "uuid", - "which 8.0.5", + "which", "windows 0.61.3", "windows-native-keyring-store", "x25519-dalek", @@ -7137,7 +6901,7 @@ dependencies = [ "axum", "base64 0.22.1", "block2 0.6.2", - "glib 0.18.5", + "glib", "gtk", "image 0.25.10", "log", @@ -7181,15 +6945,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" -[[package]] -name = "option-operations" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" -dependencies = [ - "pastey", -] - [[package]] name = "ordered-multimap" version = "0.4.3" @@ -7686,7 +7441,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" dependencies = [ "gio", - "glib 0.18.5", + "glib", "libc", "once_cell", "pango-sys", @@ -7698,10 +7453,10 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" dependencies = [ - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -7796,12 +7551,6 @@ dependencies = [ "unicode-normalization", ] -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -8736,8 +8485,8 @@ checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" dependencies = [ "block2 0.6.2", "dispatch2", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "glib-sys", + "gobject-sys", "gtk-sys", "js-sys", "log", @@ -10066,7 +9815,7 @@ checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" dependencies = [ "futures-channel", "gio", - "glib 0.18.5", + "glib", "libc", "soup3-sys", ] @@ -10077,11 +9826,11 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" dependencies = [ - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "libc", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -10435,7 +10184,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", - "quote", "unicode-ident", ] @@ -10526,26 +10274,13 @@ version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" dependencies = [ - "cfg-expr 0.15.8", + "cfg-expr", "heck 0.5.0", "pkg-config", "toml 0.8.2", "version-compare", ] -[[package]] -name = "system-deps" -version = "7.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" -dependencies = [ - "cfg-expr 0.20.9", - "heck 0.5.0", - "pkg-config", - "toml 1.1.4+spec-1.1.0", - "version-compare", -] - [[package]] name = "tao" version = "0.36.0" @@ -10613,12 +10348,6 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" -[[package]] -name = "target-lexicon" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - [[package]] name = "tauri" version = "2.11.5" @@ -11117,29 +10846,6 @@ dependencies = [ "libc", ] -[[package]] -name = "tesseract-plumbing" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25fbbb95169954a9262a565fbfb001c4d9dad271d48142e6632a3e2b7314b35" -dependencies = [ - "leptonica-plumbing", - "tesseract-sys", - "thiserror 1.0.69", -] - -[[package]] -name = "tesseract-sys" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd33f6f216124cfaf0fa86c2c0cdf04da39b6257bd78c5e44fa4fa98c3a5857b" -dependencies = [ - "bindgen", - "leptonica-sys", - "pkg-config", - "vcpkg", -] - [[package]] name = "textwrap" version = "0.16.2" @@ -12452,10 +12158,10 @@ dependencies = [ "gdk", "gdk-sys", "gio", - "gio-sys 0.18.1", - "glib 0.18.5", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", "gtk", "gtk-sys", "javascriptcore-rs", @@ -12474,15 +12180,15 @@ dependencies = [ "bitflags 1.3.2", "cairo-sys-rs", "gdk-sys", - "gio-sys 0.18.1", - "glib-sys 0.18.1", - "gobject-sys 0.18.0", + "gio-sys", + "glib-sys", + "gobject-sys", "gtk-sys", "javascriptcore-rs-sys", "libc", "pkg-config", "soup3-sys", - "system-deps 6.2.2", + "system-deps", ] [[package]] @@ -12554,18 +12260,6 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" -[[package]] -name = "which" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" -dependencies = [ - "either", - "home", - "once_cell", - "rustix 0.38.44", -] - [[package]] name = "which" version = "8.0.5" diff --git a/Cargo.toml b/Cargo.toml index 0e8fbe3fc5..7af9353485 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ members = [ "src/crates/adapters/webdriver", "src/crates/adapters/transport", "src/crates/services/services-core", + "src/crates/services/computer-use", "src/crates/services/services-integrations", "src/crates/services/legacy-migration", "src/crates/services/legacy-migration-adapters", @@ -90,6 +91,8 @@ undocumented_unsafe_blocks = "warn" # Shared dependency versions to keep all crates aligned [workspace.dependencies] +pkg-config = "0.3" +x11rb = { version = "0.13", default-features = false } # Async runtime tokio = { version = "1.52", default-features = false } tokio-stream = { version = "0.1.18", default-features = false } @@ -235,13 +238,10 @@ keepawake = "0.6.0" # Desktop support screenshots = "0.8" -enigo = "0.2" +enigo = { version = "0.2", default-features = false } resvg = { version = "0.47", default-features = false } atspi = "0.29" -gstreamer = { version = "0.24", default-features = false } -gstreamer-app = { version = "0.24", default-features = false } cc = { version = "1", default-features = false } -leptess = "0.14" core-foundation = "0.9" core-graphics = { version = "0.23", features = ["elcapitan", "highsierra"] } foreign-types = "0.5" diff --git a/docs/architecture/computer-use-control.md b/docs/architecture/computer-use-control.md index 320186b716..032fea6973 100644 --- a/docs/architecture/computer-use-control.md +++ b/docs/architecture/computer-use-control.md @@ -10,6 +10,36 @@ cross-compilation. Windows native execution, GNOME Wayland portal execution and remote end-to-end control remain acceptance gaps. Compilation is not native acceptance, and background support is limited to each provider's declared routes. +## Native provider ownership + +`services/computer-use` owns the Windows, macOS and Linux native implementation. +Desktop and graphical CLI execution inject the same `NativeComputerUseHost`; +`tool-contracts::computer_use_host` owns the portable provider interface and +`core::agentic::tools::computer_use_host` remains a source-path facade. Core +continues to own tool orchestration and product permission policy. The provider +receives the host's diagnostic directory instead of discovering Core config. + +CLI chat/exec (including the executing Shared/Peer host) register a provider only +inside a graphical login session. macOS keeps the real main thread servicing +CoreFoundation/main dispatch while the existing async Runtime runs on its worker. +Shutdown revokes native control before that run loop ends. Startup never prompts +for OS consent. The `computer-use` CLI command exposes status, the existing +`ai.computer_use_enabled` switch and explicit native permission requests. The +shared setting defaults to enabled when absent; saved true/false values survive +upgrades. Provider availability, OS consent and tool approval are separate gates. +Linux's GStreamer/Tesseract adapters load system libraries on demand so headless +CLI startup does not require desktop packages. Missing libraries and plugins +return explicit capture/OCR errors. The native contract and existing Linux +portal/AT-SPI capability limits remain unchanged. + +Remote workspace refusal is unchanged. Remote control can drive a graphical CLI +host's Agent with its own OS consent and normal cancellation; OS dialogs still +require a person at that host. CLI does not advertise the Desktop sharing/preview +capability. Detached Dispatch has no negotiated GUI provider and stays disabled; +ACP and the stdio server likewise keep their provider-free initialization. No +persisted record or remote wire shape changes in this extraction. + + ## Product contract Computer Use controls the GUI on the machine that owns the selected provider. @@ -868,7 +898,7 @@ checks discard stale preview responses and device-switch results. | Scenario | Required behavior | |---|---| | Remote workspace | Existing SSH/Docker workspace refusal; never operate the controller's local GUI as fallback | -| Remote control | An executing Desktop's Agent selects and controls its own applications without requiring an App picker on Mobile/IM; cancellation remains reachable. Native OS consent and missing GUI providers are explicit limitations; no hidden app-selection dialog | +| Remote control | An executing Desktop or graphical CLI host's Agent selects and controls its own applications without requiring an App picker on Mobile/IM; cancellation remains reachable. Native OS consent and missing GUI providers are explicit limitations; no hidden app-selection dialog | | Peer Device | Share/permission/preview commands proxy to the peer only after `computer_use_sharing_v1` negotiation; controller permission is not peer permission; old peers and CLI without GUI reject explicitly | | Detached Dispatch | Headless execution has no implied GUI capability or submitter UI dependency; require an explicitly negotiated target provider | @@ -1181,13 +1211,14 @@ expanded. That visual harness mocks transport. It is not an end-to-end Tauri permission-dialog test. Full OS denied-to-granted/restart flows and system Stop Sharing UI interaction remain manual acceptance work. -Run focused checks from the [Desktop Computer Use guide](../../src/apps/desktop/src/computer_use/AGENTS.md) +Run focused checks from the [Native Computer Use guide](../../src/crates/services/computer-use/AGENTS.md) and [Core guide](../../src/crates/assembly/core/AGENTS.md). A build-only result, ignored native test or permissive first-click fixture is not a successful strict background-input run. | Area | Recorded evidence | Remaining scope | |---|---|---| +| CLI shared native provider | macOS real CLI process observed a disposable native window, returned AX and image content, and stopped control; shared native directed-input and Desktop full Tool fixtures passed. Linux CLI compiled; shared-provider tests, GTK/AT-SPI under D-Bus/Xvfb, generated GStreamer frames, real Tesseract OCR and missing-runtime-library errors passed. Windows shared Rust library and tests type-checked | Windows native runtime/C linkage; Linux Wayland portal chooser, PipeWire seat input; all four remote scenarios remain without end-to-end GUI evidence | | macOS strict production Tool pipeline | User-selected share and separate grant; five-action non-AX canvas/text/menu/scroll/emoji program with one final observation; exactly one content click and one outside-frame focus pair; native preview input and revocation; observer foreground/key/stacking and human cursor unchanged; no observer input; Stop deactivated target | Wider applications, cross-Space behavior and visual system Sharing UI acceptance | | macOS capture/feedback | Dedicated native fixtures exercised obscured target pixels, binding retention, movement/resize, hidden/minimized errors, closure and pointer lifetime; earlier locked-session rejection evidence was not rerun | System Stop Sharing interaction and broader platform/application matrix | | Linux text semantics and scope | 65 production-module tests plus a real GTK/AT-SPI activation and UTF-8 insertion fixture under D-Bus/Xvfb; portable admission, permission, grant and geometry checks | Full Linux Desktop build, GNOME Wayland portal consent, real PipeWire/seat input and sharing UI; arbitrary background coordinates remain explicitly unsupported | diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index 96efc90eab..5731b4b88e 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -4621,6 +4621,7 @@ test('capability contract consumers may inherit empty defaults but must select r }), pathDependency('src/crates/execution/tool-contracts', { name: 'openbitfun-agent-tools', + features: ['computer-use-contract'], }), ], ); @@ -4648,6 +4649,22 @@ test('capability contract consumers may inherit empty defaults but must select r assert.ok(violations.some(({ message }) => /tool-runtime.*openbitfun-runtime-ports/.test(message)), `tool-runtime must retain exactly workspace-ports, not ${features.join(', ') || 'an empty edge'}`); } + for (const features of [[], ['computer-use-contract', 'mcp-bridge']]) { + const mutatedConsumer = { + ...toolRuntime, + dependencies: [ + toolRuntime.dependencies[0], + { ...toolRuntime.dependencies[1], features }, + ], + }; + const violations = findTestCapabilityViolations( + cargoBoundaries.findCapabilityContractConsumerViolations, + [runtimePorts, agentTools, mutatedConsumer], + ioContractRules, + ); + assert.ok(violations.some(({ message }) => /tool-runtime.*openbitfun-agent-tools/.test(message)), + `tool-runtime must retain exactly computer-use-contract, not ${features.join(', ') || 'an empty edge'}`); + } }); test('unreviewed consumers cannot add capability contract dependency edges', async () => { diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index eb1a6863a8..b1a4b46d9b 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -552,6 +552,7 @@ const THIRD_PARTY_CAPABILITY_PROFILES = new Map([ ['image', { label: 'Image', packages: new Map([ + ['openbitfun-computer-use', dependencyProfile(['jpeg', 'png'], { useDefaultFeatures: false })], ['openbitfun-services-core', dependencyProfile([], { optional: true, useDefaultFeatures: false, diff --git a/scripts/core-boundaries/rules/crate-layout.mjs b/scripts/core-boundaries/rules/crate-layout.mjs index d0517dc30d..5cd733d3e1 100644 --- a/scripts/core-boundaries/rules/crate-layout.mjs +++ b/scripts/core-boundaries/rules/crate-layout.mjs @@ -21,6 +21,7 @@ export const crateLayoutRules = [ { crateName: 'product-capabilities', layer: 'assembly', path: 'src/crates/assembly/product-capabilities' }, { crateName: 'external-sources', layer: 'assembly', path: 'src/crates/assembly/external-sources' }, + { crateName: 'computer-use', layer: 'services', path: 'src/crates/services/computer-use' }, { crateName: 'services-core', layer: 'services', path: 'src/crates/services/services-core' }, { crateName: 'services-integrations', layer: 'services', path: 'src/crates/services/services-integrations' }, { crateName: 'legacy-migration-adapters', layer: 'services', path: 'src/crates/services/legacy-migration-adapters' }, diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index f75ebe5c05..b120c5dff0 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -607,7 +607,9 @@ export const capabilityContractDependencyRules = [ ['remote-connect'], ['product-full'], )], - ['tool-runtime', capabilityConsumer([capabilityEdge()])], + // Native resources consume only the portable automation contract and tokens. + ['openbitfun-computer-use', capabilityConsumer([capabilityEdge(['computer-use-contract', 'element-token'])])], + ['tool-runtime', capabilityConsumer([capabilityEdge(['computer-use-contract'])])], ]), }, { diff --git a/scripts/fixtures/computer-use-pointer-motion.c b/scripts/fixtures/computer-use-pointer-motion.c index 1ff47694b9..ea6ca44623 100644 --- a/scripts/fixtures/computer-use-pointer-motion.c +++ b/scripts/fixtures/computer-use-pointer-motion.c @@ -1,5 +1,5 @@ // The production presentation model can be verified without a desktop session. -#include "../../src/apps/desktop/src/computer_use/pointer_motion.h" +#include "../../src/crates/services/computer-use/src/computer_use/pointer_motion.h" #include #include diff --git a/scripts/fixtures/computer-use-pointer.m b/scripts/fixtures/computer-use-pointer.m index 6804e09b07..5a54206602 100644 --- a/scripts/fixtures/computer-use-pointer.m +++ b/scripts/fixtures/computer-use-pointer.m @@ -1,5 +1,5 @@ // Black-box lifecycle checks against the production passive AppKit cursor. -#import "../../src/apps/desktop/src/computer_use/macos_capture.m" +#import "../../src/crates/services/computer-use/src/computer_use/macos_capture.m" #include void obf_control_native_stopped(uint64_t generation, uint64_t revision, int32_t pid, uint32_t windowID, const char *reason) { diff --git a/scripts/test-browser-snapshot.mjs b/scripts/test-browser-snapshot.mjs index 1b3954433e..2dffb276f4 100644 --- a/scripts/test-browser-snapshot.mjs +++ b/scripts/test-browser-snapshot.mjs @@ -123,7 +123,7 @@ try { })); const nativeCode = await new Promise((resolveExit, reject) => { const nativeArgs = ['--ignored', '--exact', 'computer_use::screen_ocr::native_fixture_tests::native_vision_reads_rendered_fixture']; - const child = spawn(process.env.OPENBITFUN_TEST_BINARY || 'cargo', process.env.OPENBITFUN_TEST_BINARY ? nativeArgs : ['test', '-p', 'openbitfun-desktop', '--lib', 'native_vision_reads_rendered_fixture', '--', ...nativeArgs], { + const child = spawn(process.env.OPENBITFUN_TEST_BINARY || 'cargo', process.env.OPENBITFUN_TEST_BINARY ? nativeArgs : ['test', '-p', 'openbitfun-computer-use', '--lib', 'native_vision_reads_rendered_fixture', '--', ...nativeArgs], { cwd: root, stdio: 'inherit', windowsHide: true, env: { ...process.env, OPENBITFUN_OCR_FIXTURE: ocrFixture }, }); diff --git a/scripts/test-computer-use-context.mjs b/scripts/test-computer-use-context.mjs index 1b81bd1007..fe77f813fe 100644 --- a/scripts/test-computer-use-context.mjs +++ b/scripts/test-computer-use-context.mjs @@ -34,21 +34,20 @@ pub use computer_use_contract as computer_use; pub mod computer_use_control; #[path = ${source('src/crates/execution/tool-contracts/src/computer_use_geometry.rs')}] pub mod computer_use_geometry; -#[path = ${source('src/apps/desktop/src/computer_use/control_session/admission.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/control_session/admission.rs')}] mod control_admission; -#[path = ${source('src/apps/desktop/src/computer_use/observation_cache.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/observation_cache.rs')}] mod observation_cache; -pub mod agentic { pub mod tools { pub mod computer_use_host { - pub use crate::computer_use_contract::*; -}}} +pub mod computer_use_host { pub use crate::computer_use_contract::*; } +pub mod agentic { pub mod tools { pub use crate::computer_use_host; }} mod screen_ocr { pub use crate::computer_use_contract::OcrTextMatch; } -#[path = ${source('src/apps/desktop/src/computer_use/ocr_context.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/ocr_context.rs')}] mod ocr_context; -#[path = ${source('src/apps/desktop/src/computer_use/interactive_filter.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/interactive_filter.rs')}] mod interactive_filter; -#[path = ${source('src/apps/desktop/src/computer_use/ax_snapshot_digest.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/ax_snapshot_digest.rs')}] mod ax_snapshot_digest; -#[path = ${source('src/apps/desktop/src/computer_use/windows_window_target.rs')}] +#[path = ${source('src/crates/services/computer-use/src/computer_use/windows_window_target.rs')}] mod windows_window_target; #[path = ${source('src/crates/assembly/core/src/agentic/tools/browser_control/snapshot_context.rs')}] mod snapshot_context; diff --git a/scripts/test-linux-computer-use-atspi.sh b/scripts/test-linux-computer-use-atspi.sh index 10e6fef625..ac157d442c 100755 --- a/scripts/test-linux-computer-use-atspi.sh +++ b/scripts/test-linux-computer-use-atspi.sh @@ -48,4 +48,4 @@ for attempt in {1..100}; do sleep 0.1 done [[ -s "$fixture_ready" ]] || { echo "GTK fixture readiness timed out." >&2; exit 1; } -node scripts/test-linux-computer-use-native.mjs atspi_semantic_fixture -- --ignored --nocapture --test-threads=1 +cargo test --locked -p openbitfun-computer-use --lib atspi_semantic_fixture -- --ignored --nocapture --test-threads=1 diff --git a/scripts/test-linux-computer-use-native.mjs b/scripts/test-linux-computer-use-native.mjs index cbddcec14e..2dd378881b 100644 --- a/scripts/test-linux-computer-use-native.mjs +++ b/scripts/test-linux-computer-use-native.mjs @@ -1,82 +1,14 @@ -// Compile and test production Linux providers and the real control-resource owner. -// GTK/portal integration tests are ignored unless explicitly selected; no native API is mocked. -import { mkdtemp, readFile, writeFile, copyFile, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +// Test the production shared provider, including its actual optional native shim. +// GTK/portal fixtures remain ignored unless explicitly selected by the caller. import { fileURLToPath } from 'node:url'; import { spawn } from 'node:child_process'; -if (process.platform !== 'linux') { - throw new Error('This harness requires Linux and the GStreamer development packages.'); -} +if (process.platform !== 'linux') throw new Error('Native provider tests require Linux.'); const root = fileURLToPath(new URL('../', import.meta.url)); -const dir = await mkdtemp(join(tmpdir(), 'openbitfun-linux-native-')); -const source = (path) => JSON.stringify(resolve(root, path)); -try { - // Extract the actual lease trait rather than maintaining a replacement contract. - const host = await readFile(join(root, 'src/crates/assembly/core/src/agentic/tools/computer_use_host.rs'), 'utf8'); - const lease = host.match(/pub trait ComputerUseActionLease:[\s\S]*?\n\}/)?.[0]; - if (!lease) throw new Error('The production lease trait could not be extracted.'); - await writeFile(join(dir, 'Cargo.toml'), `[package] -name = "linux-computer-use-native-tests" -version = "0.0.0" -edition = "2021" -[workspace] -[lib] -path = "lib.rs" -[dependencies] -atspi = { version = "0.29", features = ["zbus"] } -gstreamer = { version = "0.24", default-features = false } -gstreamer-app = { version = "0.24", default-features = false } -futures = "0.3" -tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha1 = "0.10" -sha2 = "0.10" -tempfile = "3" -libc = "0.2" -screenshots = "0.8" -base64 = "0.22" -image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } -`); - await copyFile(join(root, 'Cargo.lock'), join(dir, 'Cargo.lock')); - await writeFile(join(dir, 'lib.rs'), `#![allow(dead_code, unused_imports)] -extern crate self as openbitfun_core; -extern crate self as openbitfun_agent_tools; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use.rs')}] -pub mod computer_use_contract; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use_control.rs')}] -pub mod computer_use_control; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use_permissions.rs')}] -pub mod computer_use_permissions; -pub mod agentic { pub mod tools { pub mod computer_use_host { - pub use crate::computer_use_contract::*; - ${lease} -}}} -pub mod util { pub mod errors { - pub use crate::computer_use_contract::{ComputerUseContractError as OpenBitFunError, ComputerUseContractResult as OpenBitFunResult}; -}} -mod computer_use { - ${['control_session', 'process_identity', 'grants', 'permissions', 'linux_control', 'linux_control_ax', 'linux_ax_ui', 'ui_locate_common', 'ax_snapshot_digest'].map(name => `#[path = ${source(`src/apps/desktop/src/computer_use/${name}.rs`)}] mod ${name};`).join('\n ')} - mod desktop_host { - use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; - #[path = ${source('src/apps/desktop/src/computer_use/desktop_host/background_guard.rs')}] mod background_guard; - } -} - -`); - const code = await new Promise((resolveExit, reject) => { - const child = spawn('cargo', ['test', '--offline', '--manifest-path', join(dir, 'Cargo.toml'), '--lib', ...process.argv.slice(2)], { - cwd: root, - stdio: 'inherit', - windowsHide: true, - env: { ...process.env, CARGO_TARGET_DIR: process.env.CARGO_TARGET_DIR ?? join(root, 'target/linux-computer-use-native') }, - }); - child.on('error', reject); - child.on('close', (code) => resolveExit(code ?? 1)); +process.exitCode = await new Promise((resolve, reject) => { + const child = spawn('cargo', ['test', '--locked', '-p', 'openbitfun-computer-use', '--lib', ...process.argv.slice(2)], { + cwd: root, stdio: 'inherit', windowsHide: true, }); - process.exitCode = code; -} finally { - await rm(dir, { recursive: true, force: true }); -} + child.on('error', reject); + child.on('close', code => resolve(code ?? 1)); +}); diff --git a/scripts/test-linux-computer-use-portal.sh b/scripts/test-linux-computer-use-portal.sh index 5562beae9d..bc997dfc96 100755 --- a/scripts/test-linux-computer-use-portal.sh +++ b/scripts/test-linux-computer-use-portal.sh @@ -34,4 +34,4 @@ Gtk.main() PY fixture_pid=$! trap 'kill "$fixture_pid" 2>/dev/null || true' EXIT -node scripts/test-linux-computer-use-native.mjs portal_observe_lifecycle -- --ignored --nocapture --test-threads=1 +cargo test --locked -p openbitfun-computer-use --lib portal_observe_lifecycle -- --ignored --nocapture --test-threads=1 diff --git a/scripts/test-macos-control-capture.mjs b/scripts/test-macos-control-capture.mjs index ca073cd1be..aa02a92f2c 100644 --- a/scripts/test-macos-control-capture.mjs +++ b/scripts/test-macos-control-capture.mjs @@ -22,7 +22,7 @@ function run(command, args) { try { const binary = join(directory, 'window-capture-fixture'); await run('xcrun', ['clang', '-fobjc-arc', '-fblocks', '-Wall', '-Werror', '-Wno-unguarded-availability-new', - 'src/apps/desktop/src/computer_use/macos_capture.m', 'scripts/fixtures/computer-use-capture.m', + 'src/crates/services/computer-use/src/computer_use/macos_capture.m', 'scripts/fixtures/computer-use-capture.m', '-framework', 'AppKit', '-framework', 'ScreenCaptureKit', '-framework', 'CoreMedia', '-framework', 'CoreVideo', '-framework', 'CoreImage', '-o', binary]); if (args.length) { diff --git a/scripts/test-macos-directed-input.mjs b/scripts/test-macos-directed-input.mjs index 7b3a2a098f..f0fd62fc7b 100644 --- a/scripts/test-macos-directed-input.mjs +++ b/scripts/test-macos-directed-input.mjs @@ -31,7 +31,7 @@ try { }); const testArgs = ['native_directed_input_fixture_counts_and_stop_release', '--ignored', '--test-threads=1', '--nocapture']; const command = process.env.OPENBITFUN_TEST_BINARY || 'cargo'; - const args = process.env.OPENBITFUN_TEST_BINARY ? testArgs : ['test', '-p', 'openbitfun-desktop', '--lib', 'native_directed_input_fixture_counts_and_stop_release', '--', ...testArgs.slice(1)]; + const args = process.env.OPENBITFUN_TEST_BINARY ? testArgs : ['test', '-p', 'openbitfun-computer-use', '--lib', 'native_directed_input_fixture_counts_and_stop_release', '--', ...testArgs.slice(1)]; await run(command, args, { ...process.env, OPENBITFUN_INPUT_FIXTURE_PID: pid, OPENBITFUN_INPUT_FIXTURE_X: x, OPENBITFUN_INPUT_FIXTURE_Y: y, OPENBITFUN_INPUT_FIXTURE_RESULT: result, diff --git a/scripts/test-macos-input-controls.mjs b/scripts/test-macos-input-controls.mjs index 632dfa4ca5..bb1fdf15e4 100644 --- a/scripts/test-macos-input-controls.mjs +++ b/scripts/test-macos-input-controls.mjs @@ -21,7 +21,7 @@ const run = (command, args, env = process.env, onSpawn) => new Promise((resolve, }); const nativeTestBinary = async () => process.env.OPENBITFUN_TEST_BINARY || new Promise((resolve, reject) => { - const build = spawn('cargo', ['test', '--locked', '-p', 'openbitfun-desktop', ...(orchestration ? ['--features', 'devtools', '--test', 'computer_use_native_roundtrip'] : ['--lib']), '--no-run', '--message-format=json'], { + const build = spawn('cargo', ['test', '--locked', '-p', orchestration ? 'openbitfun-desktop' : 'openbitfun-computer-use', ...(orchestration ? ['--features', 'devtools', '--test', 'computer_use_native_roundtrip'] : ['--lib']), '--no-run', '--message-format=json'], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true, }); let pending = ''; @@ -32,7 +32,7 @@ const nativeTestBinary = async () => process.env.OPENBITFUN_TEST_BINARY || new P pending = lines.pop(); for (const line of lines) { const message = JSON.parse(line); - if (message.reason === 'compiler-artifact' && message.target.name === (orchestration ? 'computer_use_native_roundtrip' : 'openbitfun_desktop_lib') && message.executable) executable = message.executable; + if (message.reason === 'compiler-artifact' && message.target.name === (orchestration ? 'computer_use_native_roundtrip' : 'openbitfun_computer_use') && message.executable) executable = message.executable; if (message.reason === 'compiler-message' && message.message.rendered) process.stderr.write(message.message.rendered); } }); diff --git a/scripts/test-macos-popup-overlay.mjs b/scripts/test-macos-popup-overlay.mjs index d35ce4af80..64d6b5e25e 100644 --- a/scripts/test-macos-popup-overlay.mjs +++ b/scripts/test-macos-popup-overlay.mjs @@ -39,7 +39,7 @@ try { }); const testArgs = ['native_popup_overlay_fixture', '--ignored', '--test-threads=1', '--nocapture']; const command = process.env.OPENBITFUN_TEST_BINARY || 'cargo'; - const args = process.env.OPENBITFUN_TEST_BINARY ? testArgs : ['test', '-p', 'openbitfun-desktop', '--lib', 'native_popup_overlay_fixture', '--', ...testArgs.slice(1)]; + const args = process.env.OPENBITFUN_TEST_BINARY ? testArgs : ['test', '-p', 'openbitfun-computer-use', '--lib', 'native_popup_overlay_fixture', '--', ...testArgs.slice(1)]; await run(command, args, { ...process.env, OPENBITFUN_POPUP_FIXTURE_PID: pid, OPENBITFUN_POPUP_FIXTURE_RESULT: result }); const final = JSON.parse(await readFile(result, 'utf8')); assert.equal(final.popup_presses.length, 2, `${mode}: popup received exactly one press and release`); diff --git a/scripts/test-native-ax-context.mjs b/scripts/test-native-ax-context.mjs index 1a038cca2d..6ebb4dd5e5 100644 --- a/scripts/test-native-ax-context.mjs +++ b/scripts/test-native-ax-context.mjs @@ -6,6 +6,7 @@ import { spawn } from 'node:child_process'; import { fileURLToPath } from 'node:url'; assert.equal(process.platform, 'darwin', 'native AX fixture requires macOS'); +const cli = process.argv.includes('--cli'); const root = fileURLToPath(new URL('../', import.meta.url)); const dir = await mkdtemp(join(tmpdir(), 'openbitfun-ax-context-')); const run = (cmd, args, env = process.env) => new Promise((resolve, reject) => { @@ -24,8 +25,8 @@ try { fixture.on('exit', code => { clearTimeout(timeout); reject(new Error(`AX fixture exited ${code}`)); }); fixture.stdout.on('data', chunk => { if (String(chunk).includes('READY')) { clearTimeout(timeout); resolve(); } }); }); - const nativeArgs = ['native_ax_fixture_round_trips_tree_and_cached_targets', '--ignored']; - await run(process.env.OPENBITFUN_TEST_BINARY || 'cargo', process.env.OPENBITFUN_TEST_BINARY ? nativeArgs : ['test', '-p', 'openbitfun-desktop', '--lib', nativeArgs[0], '--', ...nativeArgs.slice(1)], { + const nativeArgs = [cli ? 'computer_use_native_cli_observes_and_stops_fixture' : 'native_ax_fixture_round_trips_tree_and_cached_targets', '--ignored']; + await run(process.env.OPENBITFUN_TEST_BINARY || 'cargo', process.env.OPENBITFUN_TEST_BINARY ? nativeArgs : ['test', '-p', cli ? 'openbitfun-cli' : 'openbitfun-computer-use', ...(cli ? ['--test', 'cli_command_contracts'] : ['--lib']), nativeArgs[0], '--', ...nativeArgs.slice(1)], { ...process.env, OPENBITFUN_AX_FIXTURE_PID: String(fixture.pid), }); } finally { diff --git a/scripts/test-windows-computer-use-native.mjs b/scripts/test-windows-computer-use-native.mjs index bbfce5714e..7229ce858b 100644 --- a/scripts/test-windows-computer-use-native.mjs +++ b/scripts/test-windows-computer-use-native.mjs @@ -1,103 +1,48 @@ -// Compile production WGC/UIA/MSAA/control modules without linking the desktop shell. -// Cross-host mode checks types only; it never claims native Windows execution. -import { mkdtemp, readFile, writeFile, copyFile, rm } from 'node:fs/promises'; +// Native mode tests the whole shared provider. Cross-host mode type-checks the +// same Rust lib with its declared dependencies, without compiling/linking C. +import { mkdtemp, writeFile, copyFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { spawn } from 'node:child_process'; +import { spawn, execFileSync } from 'node:child_process'; const root = fileURLToPath(new URL('../', import.meta.url)); const args = process.argv.slice(2); const check = args[0] === '--check'; if (check) args.shift(); if (process.platform !== 'win32' && !check) { - throw new Error('Native tests require Windows. Use --check --target x86_64-pc-windows-msvc for a compile-only check.'); + throw new Error('Native tests require Windows. Use --check --target x86_64-pc-windows-msvc for Rust types only.'); } -const dir = await mkdtemp(join(tmpdir(), 'openbitfun-windows-native-')); -const source = (path) => JSON.stringify(resolve(root, path)); -try { - const host = await readFile(join(root, 'src/crates/assembly/core/src/agentic/tools/computer_use_host.rs'), 'utf8'); - const lease = host.match(/pub trait ComputerUseActionLease:[\s\S]*?\n\}/)?.[0]; - if (!lease) throw new Error('The production lease trait could not be extracted.'); - await writeFile(join(dir, 'Cargo.toml'), `[package] -name = "windows-computer-use-native-tests" -version = "0.0.0" -edition = "2021" -[workspace] -[lib] -path = "lib.rs" -[dependencies] -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha1 = "0.10" -sha2 = "0.10" -tempfile = "3" -log = "0.4" -tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros", "sync", "time"] } -screenshots = "0.8" -base64 = "0.22" -image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } -windows = { version = "0.61", features = [ - "Foundation", "Graphics_Capture", "Graphics_DirectX", "Graphics_DirectX_Direct3D11", - "Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", - "Win32_Graphics_Dwm", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_Graphics_Gdi", - "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_LibraryLoader", - "Win32_System_Threading", "Win32_System_WinRT", "Win32_System_WinRT_Direct3D11", - "Win32_System_WinRT_Graphics_Capture", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", - "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell" -] } -${check ? '' : '[build-dependencies]\ncc = "1"\n'} -`); - if (!check) { - await writeFile(join(dir, 'build.rs'), `fn main() { - cc::Build::new() - .file(${source('src/apps/desktop/src/computer_use/pointer_motion.c')}) - .std("c11") - .compile("computer_use_pointer_motion"); - }`); +const run = cargoArgs => new Promise((resolve, reject) => { + const child = spawn('cargo', cargoArgs, { cwd: root, stdio: 'inherit', windowsHide: true }); + child.on('error', reject); + child.on('close', code => resolve(code ?? 1)); +}); +if (!check) { + process.exitCode = await run(['test', '--locked', '-p', 'openbitfun-computer-use', '--lib', ...args]); +} else { + const dir = await mkdtemp(join(tmpdir(), 'openbitfun-windows-native-')); + try { + const metadata = JSON.parse(execFileSync('cargo', ['metadata', '--locked', '--no-deps', '--format-version=1'], { + cwd: root, encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024, + })); + const pkg = metadata.packages.find(item => item.name === 'openbitfun-computer-use'); + const quote = JSON.stringify; + let manifest = `[package]\nname = "windows-computer-use-typecheck"\nversion = "0.0.0"\nedition = ${quote(pkg.edition)}\n[workspace]\n[lib]\npath = ${quote(pkg.targets.find(t => t.kind.includes('lib')).src_path)}\n[features]\n`; + for (const [feature, values] of Object.entries(pkg.features)) manifest += `${quote(feature)} = ${quote(values)}\n`; + for (const dep of pkg.dependencies.filter(dep => dep.kind !== 'build')) { + const section = dep.kind === 'dev' ? 'dev-dependencies' : 'dependencies'; + manifest += `\n[${dep.target ? `target.${quote(dep.target)}.` : ''}${section}.${quote(dep.rename ?? dep.name)}]\n`; + manifest += `package = ${quote(dep.name)}\nversion = ${quote(dep.req)}\ndefault-features = ${dep.uses_default_features}\nfeatures = ${quote(dep.features)}\n`; + if (dep.path) manifest += `path = ${quote(dep.path)}\n`; + if (dep.optional) manifest += 'optional = true\n'; + } + await writeFile(join(dir, 'Cargo.toml'), manifest); + await copyFile(join(root, 'Cargo.lock'), join(dir, 'Cargo.lock')); + // All native implementations, runtime admission and tests come from the + // actual crate. This mode deliberately provides no evidence of C ABI/linking. + process.exitCode = await run(['check', '--offline', '--manifest-path', join(dir, 'Cargo.toml'), '--tests', '--target-dir', join(root, 'target/windows-computer-use-native'), ...args]); + } finally { + await rm(dir, { recursive: true, force: true }); } - await copyFile(join(root, 'Cargo.lock'), join(dir, 'Cargo.lock')); - // Only the error-category constructors are adapted to the portable error - // envelope. Every native API, DTO, cache, lease and algorithm is production code. - await writeFile(join(dir, 'lib.rs'), `#![allow(dead_code, unused_imports, non_snake_case)] -extern crate self as openbitfun_core; -extern crate self as openbitfun_agent_tools; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use.rs')}] -pub mod computer_use_contract; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use_control.rs')}] -pub mod computer_use_control; -#[path = ${source('src/crates/execution/tool-contracts/src/computer_use_permissions.rs')}] -pub mod computer_use_permissions; -impl computer_use_contract::ComputerUseContractError { - pub fn service(message: impl Into) -> Self { Self::tool(message) } - pub fn io(message: impl Into) -> Self { Self::tool(message) } -} -pub mod agentic { pub mod tools { pub mod computer_use_host { - pub use crate::computer_use_contract::*; - ${lease} -}}} -pub mod util { pub mod errors { - pub use crate::computer_use_contract::{ComputerUseContractError as OpenBitFunError, ComputerUseContractResult as OpenBitFunResult}; -}} -mod computer_use { - ${['control_session', 'process_identity', 'grants', 'permissions', 'windows_list_apps', 'windows_window_target', 'windows_ax_ui', 'windows_ax_shortcuts', 'provider_worker', 'windows_msaa', 'windows_capture', 'windows_wgc_capture', 'windows_pointer_feedback', 'ui_locate_common', 'ax_snapshot_digest', 'overlay_windows', 'windows_overlay', 'windows_bg_input'].map(name => `#[path = ${source(`src/apps/desktop/src/computer_use/${name}.rs`)}] mod ${name};`).join('\n ')} - mod desktop_host { - struct DesktopComputerUseHost; - #[path = ${source('src/apps/desktop/src/computer_use/desktop_host/foreground.rs')}] mod foreground; - use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; - #[path = ${source('src/apps/desktop/src/computer_use/desktop_host/background_guard.rs')}] mod background_guard; - #[path = ${source('src/apps/desktop/src/computer_use/desktop_host/windows_launch.rs')}] mod windows_launch; - } -} -`); - process.exitCode = await new Promise((resolveExit, reject) => { - const child = spawn('cargo', [check ? 'check' : 'test', '--offline', '--manifest-path', join(dir, 'Cargo.toml'), check ? '--tests' : '--lib', ...args], { - cwd: root, stdio: 'inherit', windowsHide: true, - env: { ...process.env, CARGO_TARGET_DIR: process.env.CARGO_TARGET_DIR ?? join(root, 'target/windows-computer-use-native') }, - }); - child.on('error', reject); - child.on('close', code => resolveExit(code ?? 1)); - }); -} finally { - await rm(dir, { recursive: true, force: true }); } diff --git a/src/apps/cli/AGENTS.md b/src/apps/cli/AGENTS.md index b1c9e11c3b..c85ee00d4c 100644 --- a/src/apps/cli/AGENTS.md +++ b/src/apps/cli/AGENTS.md @@ -219,3 +219,15 @@ For the inline WeChat QR card, collapsed output, theme contrast and narrow termi ```bash cargo test --locked -p openbitfun-cli --bin openbitfun ui::tool_cards::tests:: ``` + +For native Computer Use host wiring and headless/dispatch admission: + +```bash +cargo test --locked -p openbitfun-cli --bin openbitfun computer_use:: +cargo test --locked -p openbitfun-cli --test cli_command_contracts computer_use_ +``` + +Native provider and OS fixture checks belong to +[`services/computer-use`](../../crates/services/computer-use/AGENTS.md). CLI owns +the main-thread run-loop adapter and provider injection, including Shared TUI's +executing host. Dispatch, ACP and the stdio server do not infer a GUI provider. diff --git a/src/apps/cli/Cargo.toml b/src/apps/cli/Cargo.toml index bbdc803d8a..69c5481202 100644 --- a/src/apps/cli/Cargo.toml +++ b/src/apps/cli/Cargo.toml @@ -29,6 +29,7 @@ name = "terminal_process_contracts" path = "tests/terminal_process_contracts.rs" [dependencies] +openbitfun-computer-use = { path = "../../crates/services/computer-use" } # Internal crates openbitfun-core = { path = "../../crates/assembly/core", features = [ "agent-runtime", diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index 23fb0c2b4a..3c3ff7fb63 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -40,6 +40,51 @@ current invocation may approve them. Run `openbitfun --help` or `openbitfun --help` for the complete command and option reference. +## Computer Use + +CLI chat and `exec` can use the same native Computer Use provider as Desktop on +Linux, macOS and Windows. It is enabled by default when the executing machine has +a graphical user session; no enable command is needed on a fresh configuration: + +```bash +openbitfun computer-use status +# macOS: explicitly request the permissions needed by the terminal/CLI host. +openbitfun computer-use request-permission accessibility +openbitfun computer-use request-permission screen-recording +``` + +`status` reports JSON with the setting, graphical-session availability and OS +permission states. Availability does not imply consent or an active capture. +`disable` turns the shared setting off; `enable` restores it. These are persistent, +optional controls, not startup steps. Existing saved `false` values are preserved +on upgrade; use `enable` once to change that preference. CLI and Desktop share it; +OS permission is tied to the executing application and may need separate consent. +The existing tool approval policy still applies (`exec` rejects asks by default). +Cancel the active turn with the normal interrupt control to revoke its native +action lease; process shutdown also stops capture and input. + +On macOS, window capture requires macOS 12.3 or newer and Screen Recording; +Accessibility is needed for application trees and directed input. Windows +requires an interactive user window station, not a service/session 0. Linux +requires an X11/Wayland session and its D-Bus session bus. Native capture and +foreground input use the desktop portal's consented PipeWire surface; AT-SPI +provides supported background semantic actions. The system portal chooser and +native permission dialogs appear on the executing machine. + +Linux capture needs GStreamer with PipeWire, base and good plugins; OCR needs +Tesseract with English data (`tesseract-ocr-eng` on Ubuntu). These runtime +libraries load only when used; their absence does not prevent ordinary CLI +commands from starting. Source builds additionally need `pkg-config`, +`libgstreamer1.0-dev`, `libgstreamer-plugins-base1.0-dev`, `libtesseract-dev` and +`libleptonica-dev` on Ubuntu, or the equivalent development packages. + +SSH/headless sessions and remote workspaces do not fall back to the controller's +desktop. Detached jobs, ACP and the stdio server do not acquire an implicit GUI +provider. Peer/mobile control can use the executing CLI host's Agent only when +that host has a graphical provider and local OS consent; Desktop sharing/preview +commands are not added to CLI peer capabilities. Shared TUI uses the Shared +Runtime host's provider, never the controller process's desktop. + ## Interactive TUI The most frequently used commands follow established OpenCode names where an diff --git a/src/apps/cli/build.rs b/src/apps/cli/build.rs index 994307d351..10ff670f68 100644 --- a/src/apps/cli/build.rs +++ b/src/apps/cli/build.rs @@ -4,6 +4,11 @@ use std::io::Write; use std::path::Path; fn main() { + // Cargo does not propagate a dependency's link-arg to the final executable. + // Keep the shared provider optional on macOS older than ScreenCaptureKit. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rustc-link-arg=-Wl,-weak_framework,ScreenCaptureKit"); + } if let Err(e) = embed_cli_prompts() { eprintln!("Warning: Failed to embed CLI prompts: {}", e); } diff --git a/src/apps/cli/src/agent/agentic_system.rs b/src/apps/cli/src/agent/agentic_system.rs index fdacb2fa86..eceb7c8aef 100644 --- a/src/apps/cli/src/agent/agentic_system.rs +++ b/src/apps/cli/src/agent/agentic_system.rs @@ -15,14 +15,17 @@ pub(crate) fn select_agentic_system_profile(profile: DeliveryProfile) -> Result< pub(crate) async fn init_agentic_system( profile: DeliveryProfile, runtime_ownership: Arc, + computer_use_host: Option< + openbitfun_core::agentic::tools::computer_use_host::ComputerUseHostRef, + >, ) -> Result { - let system = - openbitfun_core::agentic::system::init_agentic_system_for_profile_with_runtime_ownership( - profile, - runtime_ownership, - ) - .await - .context("Failed to initialize agentic system")?; + let system = openbitfun_core::agentic::system::init_agentic_system_with_computer_use_host( + profile, + runtime_ownership, + computer_use_host, + ) + .await + .context("Failed to initialize agentic system")?; system .coordinator .set_terminal_port(CoreRuntimeServicesProvider::terminal_port()); diff --git a/src/apps/cli/src/computer_use.rs b/src/apps/cli/src/computer_use.rs new file mode 100644 index 0000000000..067c6b80c6 --- /dev/null +++ b/src/apps/cli/src/computer_use.rs @@ -0,0 +1,119 @@ +//! CLI composition only. Native behavior and resources live in Services. +use super::BootstrapProfile; +use openbitfun_core::agentic::tools::computer_use_host::ComputerUseHostRef; +use std::sync::Arc; + +fn profile_allows_gui(profile: BootstrapProfile) -> bool { + matches!( + profile, + BootstrapProfile::Interactive | BootstrapProfile::Execution + ) +} + +pub(crate) fn provider(profile: BootstrapProfile) -> Option { + if !profile_allows_gui(profile) { + return None; + } + // No OS prompts, application launch or implicit grants during bootstrap. + // Permission requests remain an explicit user action. + if let Err(reason) = openbitfun_computer_use::host_runtime::initialize() { + tracing::info!(%reason, "Native Computer Use provider unavailable"); + return None; + } + if let Ok(paths) = openbitfun_core::infrastructure::try_get_path_manager_arc() { + openbitfun_computer_use::set_ocr_debug_directory( + paths + .default_assistant_workspace_dir(None) + .join(openbitfun_core_types::product_identity::hidden_data_directory()) + .join("computer_use_debug"), + ); + } + Some(Arc::new( + openbitfun_computer_use::NativeComputerUseHost::new(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn detached_jobs_require_a_negotiated_provider_and_management_has_no_gui() { + assert!(!profile_allows_gui(BootstrapProfile::Detached)); + assert!(!profile_allows_gui(BootstrapProfile::Management)); + assert!(profile_allows_gui(BootstrapProfile::Interactive)); + assert!(profile_allows_gui(BootstrapProfile::Execution)); + } +} + +#[derive(clap::Subcommand)] +pub(crate) enum Action { + /// Report configuration, graphical-session availability and OS permissions as JSON + Status, + /// Enable the shared ai.computer_use_enabled setting (OS consent is separate) + Enable, + /// Disable the shared ai.computer_use_enabled setting + Disable, + /// Explicitly request one OS permission on this machine + RequestPermission { + #[arg(value_enum)] + kind: PermissionKind, + }, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +pub(crate) enum PermissionKind { + Accessibility, + ScreenRecording, + InputPosting, + InputMonitoring, +} + +pub(crate) async fn run(action: Action) -> anyhow::Result<()> { + use openbitfun_agent_tools::computer_use_permissions::ComputerPermissionKind as Kind; + use openbitfun_core::service::config; + config::initialize_global_config().await?; + let config = config::get_global_config_service().await?; + match action { + Action::Enable | Action::Disable => { + let enabled = matches!(action, Action::Enable); + config + .set_config("ai.computer_use_enabled", enabled) + .await?; + println!("{}", serde_json::json!({"computer_use_enabled": enabled})); + } + Action::Status => { + let available = openbitfun_computer_use::host_runtime::availability(); + // Without a graphical session the OS permission probe cannot improve + // availability and must not connect to another user's session bus. + let permissions = if available.is_ok() { + Some(openbitfun_computer_use::permissions::status().await) + } else { + None + }; + let enabled: bool = config.get_config(Some("ai.computer_use_enabled")).await?; + println!( + "{}", + serde_json::json!({ + "computer_use_enabled": enabled, + "provider_available": available.is_ok(), + "unavailable_reason": available.err(), + "permissions": permissions, + }) + ); + } + Action::RequestPermission { kind } => { + openbitfun_computer_use::host_runtime::initialize().map_err(anyhow::Error::msg)?; + let kind = match kind { + PermissionKind::Accessibility => Kind::Accessibility, + PermissionKind::ScreenRecording => Kind::ScreenRecording, + PermissionKind::InputPosting => Kind::InputPosting, + PermissionKind::InputMonitoring => Kind::InputMonitoring, + }; + let receipt = openbitfun_computer_use::permissions::request(kind) + .await + .map_err(anyhow::Error::msg)?; + println!("{}", serde_json::to_string(&receipt)?); + } + } + Ok(()) +} diff --git a/src/apps/cli/src/dispatch/worker.rs b/src/apps/cli/src/dispatch/worker.rs index e64f4673ff..338b085dbc 100644 --- a/src/apps/cli/src/dispatch/worker.rs +++ b/src/apps/cli/src/dispatch/worker.rs @@ -146,7 +146,7 @@ async fn run_inner(store: &DispatchStore, job_id: &str) -> Result<()> { let runtime = crate::initialize_core_services( workspace, permissions::cli_policy(effective_policy), - BootstrapProfile::Execution, + BootstrapProfile::Detached, ) .await?; let agent_runtime = runtime.agent_runtime().clone(); diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index c57d3b61a1..bfc994e99e 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -226,6 +226,12 @@ fn agent_type_with_harness_profile(agent_type: String, harness_profile: Option<& #[derive(Subcommand)] enum Commands { + /// Inspect or configure native Computer Use on this executing machine + ComputerUse { + #[command(subcommand)] + action: computer_use::Action, + }, + /// Start interactive chat (TUI) Chat { /// Agent type @@ -599,6 +605,8 @@ pub(crate) enum BootstrapProfile { Interactive, Execution, Management, + /// Dispatch has not negotiated a GUI provider with its submitter. + Detached, } impl BootstrapProfile { @@ -614,7 +622,7 @@ impl BootstrapProfile { } const fn starts_mcp(self) -> bool { - matches!(self, Self::Interactive | Self::Execution) + matches!(self, Self::Interactive | Self::Execution | Self::Detached) } const fn starts_scheduled_jobs( @@ -623,7 +631,7 @@ impl BootstrapProfile { ) -> bool { // Shared TUI owns one workspace and exits after the last controller // disconnects. It cannot own the host-wide durable scheduler lease. - matches!(self, Self::Interactive | Self::Execution) + matches!(self, Self::Interactive | Self::Execution | Self::Detached) && matches!( deployment, openbitfun_services_core::runtime_ownership::RuntimeDeployment::Embedded @@ -634,7 +642,7 @@ impl BootstrapProfile { matches!( PLUGIN_HOST_LAUNCH_POLICY, openbitfun_core::plugin_host::PluginHostLaunchPolicy::Enabled - ) && matches!(self, Self::Interactive | Self::Execution) + ) && matches!(self, Self::Interactive | Self::Execution | Self::Detached) } } @@ -898,7 +906,7 @@ async fn initialize_core_services_for_deployment( tracing::info!("Global config service initialized"); if matches!( bootstrap_profile, - BootstrapProfile::Interactive | BootstrapProfile::Execution + BootstrapProfile::Interactive | BootstrapProfile::Execution | BootstrapProfile::Detached ) { if let Err(error) = plugin_host_activation::ensure_configured_plugin_execution_supported().await @@ -968,6 +976,7 @@ async fn initialize_core_services_for_deployment( let agentic_system = agent::agentic_system::init_agentic_system( openbitfun_core::product_assembly::DeliveryProfile::Cli, runtime_ownership, + computer_use::provider(bootstrap_profile), ) .await .map_err(|error| anyhow!("Failed to initialize agentic system: {error}"))?; @@ -1561,6 +1570,10 @@ async fn run_cli() -> Result<()> { root_handlers::handle_config_action(action, &config).await?; } + Some(Commands::ComputerUse { action }) => { + computer_use::run(action).await?; + } + Some(Commands::Health) => { root_handlers::handle_health_command()?; } @@ -1733,6 +1746,8 @@ async fn run_interactive_with_session( Ok(()) } +mod computer_use; + fn main() { // Install the workspace-owned ring CryptoProvider before any TLS-capable // work (relay WS, reqwest rustls paths, Feishu wss) so every client uses @@ -1750,6 +1765,7 @@ fn main() { .build() .expect("failed to build tokio runtime"); runtime.block_on(async { + let _native_cleanup = openbitfun_computer_use::host_runtime::StopOnExit; let result = run_cli().await; match openbitfun_core::plugin_host::shutdown_configured_plugin_host().await { Ok(Some(report)) => tracing::info!( @@ -1770,7 +1786,7 @@ fn main() { }) .expect("failed to spawn openbitfun worker thread"); - match worker.join() { + match openbitfun_computer_use::host_runtime::join(worker) { Ok(Ok(())) => {} Ok(Err(err)) => { if let Some(reported) = err.downcast_ref::() { diff --git a/src/apps/cli/src/root_handlers.rs b/src/apps/cli/src/root_handlers.rs index bad3c9d32b..5855d40688 100644 --- a/src/apps/cli/src/root_handlers.rs +++ b/src/apps/cli/src/root_handlers.rs @@ -951,6 +951,8 @@ pub(crate) async fn serve_acp_stdio() -> Result<()> { let agentic_system = crate::agent::agentic_system::init_agentic_system( openbitfun_core::product_assembly::DeliveryProfile::Acp, std::sync::Arc::new(runtime_ownership), + // This protocol host has no negotiated native GUI provider. + None, ) .await .context("Failed to initialize agentic system")?; diff --git a/src/apps/cli/src/server_host.rs b/src/apps/cli/src/server_host.rs index 40f3e94e35..fabfab7952 100644 --- a/src/apps/cli/src/server_host.rs +++ b/src/apps/cli/src/server_host.rs @@ -294,6 +294,8 @@ pub(crate) async fn serve() -> Result<()> { let agentic_system = crate::agent::agentic_system::init_agentic_system( openbitfun_core::product_assembly::DeliveryProfile::Cli, std::sync::Arc::new(runtime_ownership), + // This protocol host has no negotiated native GUI provider. + None, ) .await .context("Failed to initialize agentic system")?; diff --git a/src/apps/cli/tests/cli_command_contracts/exec_cli_contracts.rs b/src/apps/cli/tests/cli_command_contracts/exec_cli_contracts.rs index 9acc6878ef..7fabfae5b1 100644 --- a/src/apps/cli/tests/cli_command_contracts/exec_cli_contracts.rs +++ b/src/apps/cli/tests/cli_command_contracts/exec_cli_contracts.rs @@ -719,3 +719,200 @@ fn stream_json_disconnect_then_authorization_failure_emits_one_error_terminal() "provider disconnect emitted a successful completion: {stdout}" ); } + +#[test] +fn computer_use_default_is_enabled_without_requesting_graphical_access() { + let environment = CliTestEnvironment::new(); + let mut command = environment.std_command(); + command + .env("SSH_CONNECTION", "fixture") + .args(["computer-use", "status"]); + let output = command_output_with_timeout(&mut command, std::time::Duration::from_secs(15)); + assert!(output.status.success(), "{}", stderr(&output)); + let status: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["computer_use_enabled"], true); + assert_eq!(status["provider_available"], false); + assert!(status["permissions"].is_null()); +} + +#[test] +fn computer_use_setting_survives_restart_without_a_graphical_session() { + let environment = CliTestEnvironment::new(); + for (action, enabled) in [("enable", true), ("disable", false)] { + let mut command = environment.std_command(); + command + .env("SSH_CONNECTION", "fixture") + .args(["computer-use", action]); + let output = command_output_with_timeout(&mut command, std::time::Duration::from_secs(15)); + assert!(output.status.success(), "{}", stderr(&output)); + assert_eq!( + environment.app_config()["ai"]["computer_use_enabled"], + enabled + ); + + let mut status = environment.std_command(); + status + .env("SSH_CONNECTION", "fixture") + .args(["computer-use", "status"]); + let output = command_output_with_timeout(&mut status, std::time::Duration::from_secs(15)); + assert!(output.status.success(), "{}", stderr(&output)); + let status: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["computer_use_enabled"], enabled); + assert_eq!(status["provider_available"], false); + assert!(status["unavailable_reason"] + .as_str() + .unwrap() + .contains("GUI_SESSION_UNAVAILABLE")); + assert!(status["permissions"].is_null()); + } +} + +fn computer_use_agent_status(ssh: bool) -> Vec { + let server = MockOpenAiServer::tool_sequence(vec![( + "ComputerUse".into(), + serde_json::json!({"action":"control_status"}), + )]); + let environment = CliTestEnvironment::new(); + environment.configure_tool_loop_mock_model(server.base_url()); + let mut command = environment.std_command(); + if ssh { + command.env("SSH_CONNECTION", "fixture"); + } + command.args([ + "exec", + "Read native control status only; do not capture or operate an application", + "--auto", + "--no-verify-final-changes", + "--output-format", + "json", + ]); + let output = command_output_with_timeout(&mut command, std::time::Duration::from_secs(60)); + assert!( + output.status.success(), + "{}\n{}", + stderr(&output), + stdout(&output) + ); + server.assert_chat_completion_requests(2); + server.chat_completion_request_bodies() +} + +#[test] +fn computer_use_provider_does_not_determine_cli_terminal_availability() { + let server = MockOpenAiServer::tool_sequence(vec![( + "ControlHub".into(), + serde_json::json!({"domain":"meta","action":"capabilities"}), + )]); + let environment = CliTestEnvironment::new(); + environment.configure_tool_loop_mock_model(server.base_url()); + let mut command = environment.std_command(); + command.env("SSH_CONNECTION", "fixture").args([ + "exec", + "Report registered capabilities without starting a terminal or capturing a screen", + "--auto", + "--no-verify-final-changes", + "--output-format", + "json", + ]); + let output = command_output_with_timeout(&mut command, std::time::Duration::from_secs(60)); + assert!(output.status.success(), "{}", stderr(&output)); + server.assert_chat_completion_requests(2); + let requests = server.chat_completion_request_bodies(); + let message = requests[1]["messages"] + .as_array() + .unwrap() + .iter() + .find(|message| message["role"] == "tool") + .expect("capability tool result"); + let payload: serde_json::Value = serde_json::from_str(message["content"].as_str().unwrap()) + .unwrap_or_else(|error| panic!("invalid capability payload: {error}: {message}")); + assert_eq!(payload["domains"]["terminal"]["available"], true); + assert_eq!(payload["computer_use"]["available"], false); +} + +#[test] +fn computer_use_is_not_exposed_by_an_ssh_execution_host() { + let requests = computer_use_agent_status(true); + assert!(requests[0]["tools"] + .as_array() + .unwrap() + .iter() + .all(|tool| tool["function"]["name"] != "ComputerUse")); + assert!(!requests[1]["messages"] + .to_string() + .contains("agent-directed-control-v1")); +} + +#[test] +#[ignore = "requires a local graphical login session; reads status only and requests no OS consent"] +fn computer_use_graphical_cli_routes_the_real_tool_to_the_native_provider() { + let requests = computer_use_agent_status(false); + assert!(requests[0]["tools"] + .as_array() + .unwrap() + .iter() + .any(|tool| tool["function"]["name"] == "ComputerUse")); + let reply = requests[1]["messages"].to_string(); + assert!( + reply.contains("agent-directed-control-v1"), + "native provider was not called: {reply}" + ); + assert!(reply.contains("stop-control"), "{reply}"); +} + +#[cfg(target_os = "macos")] +#[test] +#[ignore = "requires the disposable AX fixture plus Accessibility and Screen Recording; run test-native-ax-context.mjs --cli"] +fn computer_use_native_cli_observes_and_stops_fixture() { + use serde_json::json; + let pid: i32 = std::env::var("OPENBITFUN_AX_FIXTURE_PID") + .expect("disposable fixture PID") + .parse() + .unwrap(); + let server = MockOpenAiServer::tool_sequence(vec![ + ( + "ComputerUse".into(), + json!({"action":"get_app_state","app":{"pid":pid}}), + ), + ("ComputerUse".into(), json!({"action":"stop_control"})), + ("ComputerUse".into(), json!({"action":"control_status"})), + ]); + let environment = CliTestEnvironment::new(); + environment.configure_tool_loop_image_model(server.base_url()); + let mut command = environment.std_command(); + command.args([ + "exec", + "Observe the disposable OpenBitFun AX context fixture, then stop control", + "--auto", + "--no-verify-final-changes", + "--output-format", + "json", + ]); + let output = command_output_with_timeout(&mut command, std::time::Duration::from_secs(60)); + assert!(output.status.success(), "{}", stderr(&output)); + server.assert_chat_completion_requests(4); + let requests = server.chat_completion_request_bodies(); + let observation = requests[1]["messages"].to_string(); + assert!( + observation.contains("context-value"), + "fixture AX text was not observed" + ); + assert!( + observation.contains("Save report"), + "fixture button was not observed" + ); + assert!( + observation.contains("screenshot_id"), + "capture was not bound to an observation" + ); + assert!( + observation.contains("data:image/"), + "native window capture did not reach the model" + ); + let stopped = + requests[3]["messages"].as_array().unwrap().last().unwrap()["content"].to_string(); + assert!( + stopped.contains("stopped"), + "native control was not stopped: {stopped}" + ); +} diff --git a/src/apps/cli/tests/cli_command_contracts/product_assembly_cli.rs b/src/apps/cli/tests/cli_command_contracts/product_assembly_cli.rs index ae509ff608..6be726546c 100644 --- a/src/apps/cli/tests/cli_command_contracts/product_assembly_cli.rs +++ b/src/apps/cli/tests/cli_command_contracts/product_assembly_cli.rs @@ -594,9 +594,15 @@ fn runtime_ownership_policy_is_assembled_once_in_core() { && !CLI_RUNTIME.contains("_runtime_ownership"), "Coordinator must retain the Core owner; CliRuntimeContext must not keep a second guard" ); + let assembly_call: String = AGENTIC_SYSTEM + .chars() + .filter(|character| !character.is_whitespace()) + .collect(); assert!( CLI_MAIN.contains("CoreRuntimeOwnership") - && AGENTIC_SYSTEM.contains("init_agentic_system_for_profile_with_runtime_ownership"), + && assembly_call.contains( + "init_agentic_system_with_computer_use_host(profile,runtime_ownership,computer_use_host,)" + ), "CLI must select a deployment and inject the single Core owner" ); } diff --git a/src/apps/cli/tests/support/mod.rs b/src/apps/cli/tests/support/mod.rs index 63b64d7980..89bdbd5e85 100644 --- a/src/apps/cli/tests/support/mod.rs +++ b/src/apps/cli/tests/support/mod.rs @@ -163,6 +163,15 @@ impl CliTestEnvironment { pub(crate) fn configure_tool_loop_mock_model(&self, server_base_url: &str) { self.configure_mock_model(server_base_url); + self.allow_tool_loop_rounds(); + } + + pub(crate) fn configure_tool_loop_image_model(&self, server_base_url: &str) { + self.configure_mock_image_model(server_base_url); + self.allow_tool_loop_rounds(); + } + + fn allow_tool_loop_rounds(&self) { let config_path = self.user_root.join("config/app.json"); let mut config: serde_json::Value = serde_json::from_slice( &std::fs::read(&config_path).expect("read tool-loop model config"), diff --git a/src/apps/desktop/Cargo.toml b/src/apps/desktop/Cargo.toml index 58cca30e76..e1169d50bd 100644 --- a/src/apps/desktop/Cargo.toml +++ b/src/apps/desktop/Cargo.toml @@ -14,11 +14,11 @@ name = "openbitfun-desktop" path = "src/main.rs" [build-dependencies] -cc = { workspace = true } tauri-build = { workspace = true } serde_json = { workspace = true } [dependencies] +openbitfun-computer-use = { path = "../../crates/services/computer-use" } openbitfun-miniapp-ipc = { path = "../../crates/adapters/miniapp-ipc" } openbitfun-services-core = { path = "../../crates/services/services-core", features = ["pet-packages", "local-storage"] } # Internal crates @@ -86,7 +86,6 @@ sha1 = { workspace = true } sha2 = { workspace = true } minisign-verify = { workspace = true } screenshots = { workspace = true } -enigo = { workspace = true } # Controller-local drag thumbnails decode these formats; other files use UI icons. image = { workspace = true, features = ["bmp", "gif", "jpeg", "png", "webp"] } resvg = { workspace = true } @@ -102,32 +101,17 @@ bitflags = { workspace = true } core-foundation = { workspace = true } core-graphics = { workspace = true } dispatch = { workspace = true } -foreign-types = { workspace = true } libc = { workspace = true } objc2 = { workspace = true, features = ["exception"] } block2 = { workspace = true } objc2-foundation = { workspace = true, features = ["std", "NSArray", "NSData", "NSDictionary", "NSError", "NSGeometry", "NSNotification", "NSOperation", "NSString", "block2"] } objc2-app-kit = { workspace = true, features = ["std", "libc", "NSAnimationContext", "NSButton", "NSControl", "NSResponder", "NSView", "NSWindow", "NSWorkspace", "NSRunningApplication"] } -objc2-vision = { workspace = true, features = ["std", "VNRecognizeTextRequest", "VNRequest", "VNObservation", "VNRequestHandler", "VNUtils", "VNTypes", "objc2-core-foundation"] } [target.'cfg(windows)'.dependencies] notify-rust = { workspace = true } win32job = { workspace = true } windows = { workspace = true, features = [ - "Foundation", - "Globalization", - "Graphics_Capture", - "Graphics_DirectX", - "Graphics_DirectX_Direct3D11", - "Graphics_Imaging", - "Media_Ocr", - "Storage_Streams", "Win32_Foundation", - "Win32_Graphics_Direct3D", - "Win32_Graphics_Direct3D11", - "Win32_Graphics_Dwm", - "Win32_Graphics_Dxgi", - "Win32_Graphics_Dxgi_Common", "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", @@ -138,11 +122,6 @@ windows = { workspace = true, features = [ "Win32_System_Com_StructuredStorage", "Win32_System_Ole", "Win32_System_Variant", - "Win32_System_WinRT", - "Win32_System_WinRT_Direct3D11", - "Win32_System_WinRT_Graphics", - "Win32_System_WinRT_Graphics_Capture", - "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem", @@ -160,15 +139,11 @@ default = [] # Enable webview devtools and element inspector for development builds. # Only active in debug builds or when explicitly requested via --features devtools. # Never enabled in release profile intended for end users. -devtools = ["tauri/devtools", "openbitfun-webdriver/embedded"] +devtools = ["openbitfun-computer-use/test-support", "tauri/devtools", "openbitfun-webdriver/embedded"] [target.'cfg(target_os = "linux")'.dependencies] libc = { workspace = true } gtk = { workspace = true } -atspi = { workspace = true, features = ["zbus"] } -gstreamer = { workspace = true } -gstreamer-app = { workspace = true } -leptess = { workspace = true } [lints] workspace = true diff --git a/src/apps/desktop/build.rs b/src/apps/desktop/build.rs index 61c53e6e34..afd3508725 100644 --- a/src/apps/desktop/build.rs +++ b/src/apps/desktop/build.rs @@ -1,31 +1,8 @@ fn main() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.h"); - println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.c"); - cc::Build::new() - .file("src/computer_use/pointer_motion.c") - .std("c11") - .compile("computer_use_pointer_motion"); - } + // Cargo does not propagate a dependency's link-arg to the final executable. + // Keep the shared provider optional on macOS older than ScreenCaptureKit. if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { - println!("cargo:rerun-if-changed=src/computer_use/macos_capture.m"); - println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.h"); - cc::Build::new() - .file("src/computer_use/macos_capture.m") - .flag("-fobjc-arc") - .flag("-fblocks") - .compile("computer_use_capture"); - // Older macOS installs must reach the runtime unsupported-version guard. println!("cargo:rustc-link-arg=-Wl,-weak_framework,ScreenCaptureKit"); - for framework in [ - "CoreMedia", - "CoreVideo", - "CoreImage", - "AppKit", - "ApplicationServices", - ] { - println!("cargo:rustc-link-lib=framework={framework}"); - } } println!("cargo:rerun-if-env-changed=OPENBITFUN_RELEASE_CHANNEL"); println!("cargo:rerun-if-env-changed=OPENBITFUN_DESKTOP_BINARY_NAME"); diff --git a/src/apps/desktop/src/computer_use/AGENTS.md b/src/apps/desktop/src/computer_use/AGENTS.md index f96ba34800..eb2cdb5641 100644 --- a/src/apps/desktop/src/computer_use/AGENTS.md +++ b/src/apps/desktop/src/computer_use/AGENTS.md @@ -1,357 +1,16 @@ -# Computer Use (desktop host) +# Desktop Computer Use wiring -## Scope - -Platform-specific automation for the unified `computer_use` tool lives under -`src/apps/desktop/src/computer_use/`. Shared contracts and tool orchestration -are in `src/crates/assembly/core` and `src/crates/execution/tool-contracts`. - -## Platform maturity - -| Platform | Tier | Capabilities | -|---|---|---| -| **macOS** | AX-first | Accessibility tree, directed background input, persistent ScreenCaptureKit window capture, menu shortcuts, interactive/visual views | -| **Windows** | AX-first | UI Automation patterns/tree, persistent WGC window capture, MSAA observation for legacy VCL, targeted message input | -| **Linux** | Portal + AT-SPI | Consented PipeWire capture, foreground portal input, background semantic activation and EditableText, AT-SPI application trees | - -### Ubuntu / Linux control - -Wayland capture and seat input use one xdg-desktop-portal session. Never use an -XWayland `DISPLAY` as evidence that X11 desktop input is supported. Portal denial, -revocation, missing plugins, and stream geometry changes fail explicitly; they -must not trigger X11 input or whole-desktop capture fallback. GStreamer consumes -the portal's authorized PipeWire FD, not a default unrestricted connection. - -AT-SPI provides `list_apps`, `get_app_state`, `app_click` with a cached `NodeIdx`, -and `app_type_text` with an explicit EditableText node. These semantic operations -do not change compositor focus. Arbitrary background coordinates, app-scoped key -chords, interactive/visual cached views, and menu shortcuts are unavailable. -Portal-selected pixels are not automatically attached to a PID-selected tree. - -Run the real native portal fixture in the desktop user's Ubuntu session (requires -`python3-gi`, GTK 3, GStreamer PipeWire/base/good plugins and portal services): +Native OS implementation and focused provider tests live in +[the shared service](../../../../crates/services/computer-use/AGENTS.md). +This directory only re-exports that provider for existing Desktop APIs and owns +the devtools-only full Core Tool integration fixtures. Keep Tauri projection in +the app; do not reintroduce a separate native implementation here. ```bash cargo check --locked -p openbitfun-desktop --tests -node scripts/test-linux-computer-use-native.mjs -- --test-threads=1 -bash scripts/test-linux-computer-use-atspi.sh -bash scripts/test-linux-computer-use-portal.sh -``` - -Select only the dedicated **OpenBitFun Portal Fixture** window. The fixture checks -real PipeWire frames, observation-only input rejection and stop revocation. It -does not prove foreground input delivery or remote behavior. -For headless AT-SPI verification, use -`dbus-run-session -- xvfb-run -a bash -lc 'export NO_AT_BRIDGE=0; bash scripts/test-linux-computer-use-atspi.sh'`. -The AT-SPI fixture checks one GTK button activation and UTF-8 EditableText insertion -while preserving existing text; -it does not establish compatibility with every application. Run the SPEC's -remaining native acceptance scenarios separately. - -## Module map - -- `desktop_host/` — `ComputerUseHost` trait impl; entry for all actions -- `control_session/admission.rs` — pure mode/owner/lease/start/stop state machine -- `control_session/sharing.rs`, `desktop_host/sharing.rs` — user-selected window, observe-first sharing and revocable input grant -- `permissions.rs`, `process_identity.rs`, `grants.rs`, `share_grants.rs` — explicit OS requests and executable-bound remembered preferences -- `desktop_host/shared_preview.rs` — scoped manual preview input through the same native host/lease as the Agent -- `desktop_host/background_guard.rs` — before/after desktop witnesses; no focus restoration or replay -- `desktop_host/foreground.rs` — explicit exact-window activation and global input destination checks -- `desktop_host/linux_launch.rs` — literal executable/desktop-entry launch with bounded helper waits -- `desktop_host/observation.rs`, `observation_cache.rs` — observation identity and bounded screenshot geometry; never input authority -- `desktop_host/state.rs` — derived host feedback and view caches -- `macos_*` / `windows_*` — platform AX, capture, list-apps, shortcuts -- `macos_ax_dispatch` — per-element AX thread routing and native exception boundary -- `windows_capture.rs` — WGC frame conversion and authoritative window bounds -- `windows_wgc_capture.rs` — Windows.Graphics.Capture (Direct3D11) -- `windows_window_target.rs` — Win32 window facts and portable default-target policy -- `linux_ax_ui.rs` — AT-SPI locate -- `linux_control.rs` — portal lifetime, PipeWire frame consumption, foreground seat input -- `linux_control_ax.rs` — AT-SPI background semantic operations -- `linux_control_policy.rs` — pure session classification and keysym encoding -- `screen_ocr.rs`, `ui_locate_common.rs` — shared OCR/locate helpers - -## Native capture boundaries - -The implementation contract is [Computer Use control-session SPEC](../../../../../docs/architecture/computer-use-control.md). -macOS and Windows retain a real native single-window capture session. Never fall -back to desktop pixels when window capture fails or the target is obscured. -Background input must not activate a window or use the global input seat. -For an ordinary user-requested GUI task, the Agent may explicitly change to -foreground mode when background delivery is unsupported or verified ineffective, -unless the user required background-only/no-disruption. This is a new tool -decision, never a native retry or implicit escalation. macOS/Windows -`activate-app-v1` activates the exact bound window and returns a fresh observation; -global input must validate the foreground destination. Linux retains its separate -portal consent/surface identity. Preserve user Stop, cancellation and OS denial. - -Surface errors name the state the host established (minimized, hidden, cloaked, -off-Space, display affinity) for the exact window; keep the codes stable and -the wording free of recovery advice, which the tool adds per mode. A bound -stream that loses its surface reports that state too, never "closed": macOS -per-window `CGWindowList` queries omit minimized and other-Space windows, so a -window counts as closed only when the full list lacks it, and Windows checks -the bound HWND's surface state before reusing its stream. Native status reports -a lost surface as status 2 without querying Accessibility; describe it with -`obf_capture_describe_surface` only after releasing `CAPTURE`, so Stop never -waits on the target. Target validation and stream start hold `CAPTURE` by -design. -`restore_window` (unhide, un-minimize) runs only for foreground `activate_app`, -requires `foreground_allowed` and `target_admissible`, and restores the window -the surface error named: the requested or bound one, else the window capture -selects for the process (Windows: its first minimized window). An unreadable -minimized state is a restore failure, never "nothing to restore". On macOS -activation sets the capture input barrier so the next observation is a -post-activation frame. -`app-zoom-v1` re-captures the bound window only: macOS 14+ uses a one-shot -desktop-independent window filter at backing scale, older macOS and Windows -crop the live frame. Zoomed pointer maps are marked zoomed and keep their -window offset and size; never re-anchor them on raw region bounds, infer zoom -from region size, or let a zoom read pixels outside the bound window. Only -inputs that can name a screenshot_id require one after a zoom. - -## Target-local macOS focus acceptance - -AX walks and cached-node operations run on a blocking worker. Route each native -message by the element's serving PID through `macos_ax_dispatch`: same-process -AppKit callbacks require main, while WebKit subprocess messages need main free -to answer synchronous IPC, including AX client authentication. Never dispatch an -entire walk based on its root PID; a single tree spans both processes. -`AXUIElementGetPid` reports the presenter for WebKit descendants; thread routing -uses dynamically resolved `_AXUIElementGetActualPid`. Keep the presenter PID for -target/permission validation. If the serving-PID SPI is unavailable, report an -explicit unsupported state instead of guessing a thread. Keep the -control token across same-process dispatch and catch Objective-C exceptions on -the executing thread. Recheck input authority there before actions or user -attribute writes, because Stop may revoke a queued message. Observation-only -AX enablement does not acquire input authority. Enigo / HIToolbox input retains -its main-thread wrapper. - -Cross-process AX proxies can advertise a writable `AXSelectedText` whose setter -does nothing (WebKit). Select the existing directed-keyboard route before -submission for these proxies; native controls retain AX insertion at the current -selection. Never retry a submitted text write based only on unchanged AX state. - -The directed-input route can change a target application's internal -focus without changing the human foreground application. Its window-addressed -focus pair at local `(-8,-8)` must remain outside content; the requested gesture -must reach content exactly once with unchanged modifiers. Do not validate it -using a fixture that overrides `acceptsFirstMouse`. Record dequeued mouse events -so standard controls' tracking loops cannot hide a delivered mouse-up. Record observer active/key, -frontmost PID, stacking order, real text destination and content event counts. -Do not use missing AX key-state attributes as a substitute for native focus -validation: fixtures inspect their own `NSWindow.keyWindow`. Preparation caches -must include generation, PID, window ID, human foreground identity and activation -epoch plus a passive target-local loss epoch, and must not add app-name rules or -content-coordinate guesses. Target-local event monitoring must be listen-only; -unavailable monitoring disables cache reuse, not background input. An off-frame routing -position is distinct from the actual user-requested content target. -No after-action raise/restore is allowed. Stop may deactivate a target only when -it is not the user's actual foreground application. Prototype success is not -production acceptance; the complete native Tool pipeline must pass separately. -Mouse events use CombinedSessionState and explicit requested flags; keyboard -events retain a private source. Preserve field 58 as window-routing metadata, -not a click-group counter. Cleanup validates process-serial identity before -target deactivation; it does not require the original window to remain open. - -## Verification - -For observation payloads, OCR projection, AX filtering/digests, and browser -snapshot context, use the isolated compiler harness first. It compiles the -production Rust files by path, with the actual DTO source and no replacement -algorithms or native-host mocks. Cargo dependencies must already be cached -(`cargo fetch --locked` on a fresh machine). - -```bash -node scripts/test-computer-use-context.mjs -cargo test -p openbitfun-desktop --lib context_integrity_tests -``` - -Native black-box fixtures use only a dedicated test window / rendered image: - -```bash -# Node 22/24 and installed workspace dependencies; installed Chrome required. -# CHROME_PATH can select another Chromium executable. -node scripts/test-browser-snapshot.mjs --native-ocr -# macOS + Accessibility permission; creates and closes its own AppKit window. -node scripts/test-native-ax-context.mjs -# macOS + Screen Recording permission; captures only its own obscured test window. -node scripts/test-macos-control-capture.mjs -# Locked-host rejection only; never wakes or unlocks the desktop. -node scripts/test-macos-control-capture.mjs --locked -# macOS passive cursor lifecycle; no capture or accessibility permission required. -node scripts/test-macos-control-pointer.mjs -# Shared macOS/Windows presentation math; also runnable on Linux without a GUI. -node scripts/test-computer-use-pointer-motion.mjs -# macOS + Accessibility and Screen Recording permissions; clicks only its dedicated fixture process. -node scripts/test-macos-directed-input.mjs -# Covered standard controls: exact native AX hit + semantic action + fresh capture. -node scripts/test-macos-input-controls.mjs --semantic -# Full Tool image-coordinate button activation/text focus and wrong-field guard. -# Target/observer have distinct app bundles; AppKit initializes before the -# foreground baseline. Activation history catches transient focus changes. -# Also induces target-local loss while foreground stays fixed, then verifies -# the next ordinary input prepares focus again without another content click. -node scripts/test-macos-input-controls.mjs --orchestration -# Real AX messaging timeout in a stopped disposable process, then one directed -# click after resumption; retains exact delivery and foreground/cursor checks. -node scripts/test-macos-input-controls.mjs --busy-ax -# Explicit foreground transition on disposable windows; wrong-focus rejection, -# exact activation and native Unicode/shortcut delivery. -node scripts/test-macos-input-controls.mjs --foreground -# Identical five-input sequence: five tool calls vs one batch, with default -# images and AX-only observations. Fresh isolated app/host per case. -node scripts/test-macos-input-controls.mjs --latency -# Diagnostic raw-pointer contract, including ordinary non-AX first click and -# unchanged modifiers/z-order. Both this raw runner and the full Tool five-action -# fixture passed; do not substitute a permissive first-click implementation. -node scripts/test-macos-input-controls.mjs -# Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop. node scripts/test-macos-control-roundtrip.mjs -# Same-process AppKit + real WebKit subtree: observe, capture, image/node clicks, -# exact text, actual DOM results, shortcuts and Stop; external deadlock watchdog. node scripts/test-macos-computer-use-self.mjs -# Same-process popup panel over a dedicated window, once as an attached child -# window (inherits layer 0) and once at the pop-up menu level: composited pixels -# and auxiliary metadata, popup-routed press without focus preparation -# dismissing it, and an outside press reaching the bound window. -node scripts/test-macos-popup-overlay.mjs ``` -For explicitly selected disposable real applications, the devtools JSONL probe -uses the same production Tool path and main-thread run loop. It accepts only one -startup PID (optionally one window), background observations and app actions; -it rejects activation, global input, clipboard and scripts. Do not use personal -application windows or infer delivery from `ok: true`. Observe after errors -before choosing another action; the probe never retries input automatically. - -```bash -cargo test -p openbitfun-desktop --features devtools --test computer_use_native_roundtrip --no-run --message-format=json -# Use the executable path emitted above; EOF or the total deadline stops control. -OPENBITFUN_CUA_PROBE_PID= OPENBITFUN_CUA_PROBE_OUTPUT_DIR=/tmp/cua-probe -# stdin JSONL: {"id":"observe","input":{"action":"get_app_state","include_image":true}} -cargo test -p openbitfun-desktop --features devtools --lib native_control_roundtrip::probe -# Independent read-only witness; no app launch, permission prompts or input. -clang -fobjc-arc -fblocks -Wall -Wextra -Werror -framework AppKit -framework ApplicationServices scripts/fixtures/computer-use-background-witness.m -o /tmp/cua-witness -/tmp/cua-witness --target-pid --target-window --output /tmp/cua-witness.json -``` - -Wait for the witness's baseline before input. `SIGUSR1` requests a new baseline; -wait for its sequence to advance. `SIGTERM` flushes the final record. Check -sampling gaps and unknown AX reads, and separate concurrent human activity from -backend-caused changes. The witness records IDs/coordinates, not titles, text or -pixels; it cannot independently prove key-window state or causal attribution. - -The browser fixture runs production snapshot/resolver JavaScript in Chromium, -then passes the actual DOM payload to compiled Rust presentation tests. The -optional OCR step compiles the Desktop test target and invokes macOS Vision on -the rendered JPEG. The AX fixture compiles the Desktop test target and checks -native AX nodes, text, states, parent indices, cache entries, filtering, and DTO -round trips. These are local macOS checks, not Windows/Linux or remote evidence. - -The latency fixture reports actual returned observations/images, AX node counts -and native tool wall time including one separately timed fixture JSON check. -It checks exact Unicode text, immediate shortcut delivery, -fresh AX-only node identities, recovery of default screenshot observations, -and the same foreground/cursor invariants as the orchestration fixture. It does -not invoke a model. Startup and cleanup are outside the reported measurement; -timings are diagnostic evidence, not machine-dependent pass/fail thresholds. -The native fixture requires an unlocked desktop; its read-only startup gate -reports a locked screen as inconclusive without waking or unlocking it. - -Observation invariants: - -- Rectangle containment does not prove two controls have the same action. -- Projection uses content padding and authoritative global bounds; invalid - geometry and OCR matches outside the content are not actionable coordinates. -- AX snapshot digests cover state and geometry as well as labels. A state-only - change must not be mistaken for a failed action and trigger duplicate input. -- Stale interactive/visual indices must be returned to the caller for a fresh - choice, never silently reused after rebuilding a different view. -- Element-budget omissions are reported in `omitted_element_count`, including - when text rendering is disabled; focused controls survive budget selection. - -```bash -cargo test -p openbitfun-desktop --lib computer_use -cargo build -p openbitfun-desktop -``` - -Windows-only paths (`windows_wgc_capture`, UIA) compile on CI (`windows-latest`). -The Windows job also runs the isolated native-module unit suite independently -of the Tauri test loader; interactive native delivery fixtures remain ignored. -UIA observation, semantic input, locate, hit-test and shortcut discovery share -one MTA worker. `provider_worker.rs` bounds admission and caller waits: a request -has a ten-second deadline and polls control cancellation every 50 ms. UIA also -uses two-second connection and five-second transaction limits with automatic -focus disabled. Never release the occupied slot, spawn replacement workers, or -queue another input just because a caller timed out. Foreign code may still be -running. Input that has crossed its submission fence has an unknown outcome on -failure; do not retry it or switch to a coordinate click. Stop fences input still -in preflight, while already submitted input can complete later. After the native -call returns, discard abandoned observations and require a fresh read. A provider -that never returns leaves UIA explicitly busy until it recovers or the host is -restarted; status and Stop must remain independent of that worker. - -The focused desktop `computer_use` tests include portable blocking-provider -regressions for deadlines, cancellation, late input, busy admission and recovery. -They simulate foreign-call stalls and do not establish real Windows delivery. -The isolated native-module harness compiles the production control owner, UIA, -MSAA, WGC and pointer modules. Its portable error-envelope adapter replaces no -native APIs or algorithms. Cross-compilation is type-checking, not Windows -execution; full Desktop compilation and native fixtures still belong on Windows. - -```bash -# Native Windows: unit tests; native delivery fixtures remain opt-in/ignored. -node scripts/test-windows-computer-use-native.mjs -# Other hosts with the target installed: compile production native modules only. -node scripts/test-windows-computer-use-native.mjs --check --target x86_64-pc-windows-msvc -# Interactive Windows: own-process main + topmost companion selection and real WGC pixels. -node scripts/test-windows-computer-use-native.mjs default_window_captures_main_beside_topmost_companion -- --ignored --test-threads=1 -``` - -For default Windows target selection, run -`node scripts/test-computer-use-context.mjs windows_window_target`. -The portable regression includes issue #3291's reported HWNDs, styles and bounds; -it is not evidence of WGC execution. Native default selection must prefer content -over floating utility windows without app-name rules. Explicit HWNDs and existing -bindings bypass ranking. WGC rejection reports the selected HWND and window facts; -never probe another target or substitute desktop pixels after a failure. The -interactive fixture captures only its own Win32 window; it does not establish -Tauri/WebView2 compatibility on every Windows build. - -Observation IDs and target revisions are additive wire fields. Keep accepting -legacy payloads, advertise `observation-id-v1`, and reject explicit stale IDs -before input. New observations invalidate prior AX/view indices even when the -content digest is unchanged. Do not replace namespace identity with a digest. - -Agent native fixtures must discover and address their target through production -tools without manual share selection or a separate input grant. Cover explicit -`start_control` and implicit first-action startup. Optional manual-share fixtures -exercise target inventory, observe-first capture and grants separately; they must -not hide an Agent regression by performing those UI steps in fixture setup. -Permission probes never prompt. Desktop-state witnesses record concurrent human -activity without revoking Agent control or replaying input. - -The Web preview's deterministic cursor is verified against Rust-generated -`computer-use-rust` samples retained in the repository. The reference source is -not required to build or run tests. After preview, sharing or permission UI edits: - -```bash -pnpm --dir src/web-ui run test:run src/app/components/ComputerUseControlCard.test.tsx src/app/components/computer-use src/infrastructure/api/adapters/peer-device-adapter.test.ts -``` - -These UI tests cover permission requests, stale device/grant responses, geometry, -gesture cancellation and cursor math. They do not establish native delivery or -remote end-to-end behavior. The strict macOS fixture also exercises native shared -preview capture/input and stale preview rejection after revocation. - -Native pointer presentation uses `pointer_motion.h` for both AppKit and Win32. -Keep elapsed-time spring math free of OS/input dependencies. AppKit's visibility -refresh must never snap an in-flight movement; Win32 reuses one worker/window, -coalesces only visual targets and wakes on Stop. The native click pulse follows -visual arrival without delaying input. Linux/Wayland uses the shared Web preview; -do not introduce an X11/global pointer fallback. After native-motion changes run -the portable math fixture plus the platform fixture above. The Windows -`--check` command validates types only; its native test mode links the shared C -model. Browser tests and portable math on macOS are not native Windows/Linux -or remote-session evidence. +The strict fixtures use disposable windows and retain the shared service guide's +permission, foreground-preservation and no-replay requirements. diff --git a/src/apps/desktop/src/computer_use/mod.rs b/src/apps/desktop/src/computer_use/mod.rs index 412cdafb40..ccd3df55a2 100644 --- a/src/apps/desktop/src/computer_use/mod.rs +++ b/src/apps/desktop/src/computer_use/mod.rs @@ -1,78 +1,9 @@ -//! Desktop Computer Use: portable admission/observation lifecycle, native OS providers. - -mod ax_snapshot_digest; -pub(crate) mod control_session; -mod debug_overlay; -mod desktop_host; -pub(crate) mod grants; -mod interactive_filter; -#[cfg(target_os = "linux")] -mod linux_ax_ui; -#[cfg(target_os = "linux")] -mod linux_control; -#[cfg(target_os = "linux")] -mod linux_control_ax; -#[cfg(target_os = "macos")] -mod macos_ax_dispatch; -#[cfg(target_os = "macos")] -mod macos_ax_dump; -#[cfg(target_os = "macos")] -mod macos_ax_shortcuts; -#[cfg(target_os = "macos")] -mod macos_ax_ui; -#[cfg(target_os = "macos")] -mod macos_ax_write; -#[cfg(target_os = "macos")] -mod macos_bg_input; -#[cfg(target_os = "macos")] -mod macos_capture; -#[cfg(target_os = "macos")] -mod macos_input_focus; -#[cfg(target_os = "macos")] -mod macos_list_apps; -#[cfg(target_os = "macos")] -mod macos_skylight; -mod observation_cache; -mod ocr_context; -#[cfg(any(target_os = "macos", target_os = "windows", test))] -mod overlay_windows; -pub(crate) mod permissions; -pub(crate) mod process_identity; -#[cfg(any(target_os = "windows", test))] -mod provider_worker; -mod screen_ocr; -pub(crate) mod share_grants; -mod som_overlay; -mod terminal_detect; -mod ui_locate_common; -#[cfg(target_os = "windows")] -mod windows_ax_shortcuts; -#[cfg(target_os = "windows")] -mod windows_ax_ui; -#[cfg(target_os = "windows")] -mod windows_bg_input; -#[cfg(target_os = "windows")] -mod windows_capture; -#[cfg(target_os = "windows")] -mod windows_list_apps; -#[cfg(target_os = "windows")] -mod windows_msaa; -#[cfg(any(target_os = "windows", test))] -mod windows_overlay; -#[cfg(target_os = "windows")] -mod windows_pointer_feedback; -#[cfg(target_os = "windows")] -mod windows_wgc_capture; -#[cfg(any(target_os = "windows", test))] -mod windows_window_target; - -pub(crate) use desktop_host::shared_preview; -pub(crate) use desktop_host::sharing::targets as share_targets; -pub use desktop_host::DesktopComputerUseHost; - -#[cfg(test)] -mod integration_e2e; +//! Desktop wiring for the shared native Computer Use provider. +pub use openbitfun_computer_use::NativeComputerUseHost as DesktopComputerUseHost; +pub(crate) use openbitfun_computer_use::{ + control_session, grants, permissions, share_grants, share_targets, shared_preview, +}; #[cfg(all(feature = "devtools", target_os = "macos"))] -#[path = "desktop_host/native_control_roundtrip_tests.rs"] +#[path = "native_control_roundtrip_tests.rs"] pub(crate) mod native_control_roundtrip; diff --git a/src/apps/desktop/src/computer_use/desktop_host/native_control_probe.rs b/src/apps/desktop/src/computer_use/native_control_probe.rs similarity index 99% rename from src/apps/desktop/src/computer_use/desktop_host/native_control_probe.rs rename to src/apps/desktop/src/computer_use/native_control_probe.rs index 544da3c63d..4e39164571 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/native_control_probe.rs +++ b/src/apps/desktop/src/computer_use/native_control_probe.rs @@ -227,7 +227,7 @@ async fn run_inner() -> Result<(), String> { std::fs::create_dir_all(directory).map_err(|error| error.to_string())?; } let scope = Scope { pid, window }; - let identity = crate::computer_use::process_identity::ProcessIdentity::read(pid)?; + let identity = openbitfun_computer_use::test_support::ProcessIdentity::read(pid)?; let host = Arc::new(DesktopComputerUseHost::new()); let mut context = ToolUseContext::for_tool_listing(None, None); context.session_id = Some(OWNER.into()); diff --git a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs b/src/apps/desktop/src/computer_use/native_control_roundtrip_tests.rs similarity index 91% rename from src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs rename to src/apps/desktop/src/computer_use/native_control_roundtrip_tests.rs index af8cfd7b9c..b25a62ae09 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs +++ b/src/apps/desktop/src/computer_use/native_control_roundtrip_tests.rs @@ -1,5 +1,5 @@ //! Real Tool -> desktop host -> native capture/input regression, opt-in only. -use super::desktop_host::DesktopComputerUseHost; +use super::DesktopComputerUseHost; use openbitfun_core::agentic::tools::computer_use_host::ComputerUseHost; use openbitfun_core::agentic::tools::framework::{Tool, ToolResult, ToolUseContext}; use openbitfun_core::agentic::tools::implementations::ComputerUseTool; @@ -191,7 +191,7 @@ fn assert_session( Some(target), "capture retargeted between actions" ); - assert_eq!(crate::computer_use::macos_bg_input::frontmost_pid_macos(), foreground, + assert_eq!(openbitfun_computer_use::test_support::frontmost_pid(), foreground, "tool pipeline changed the foreground application; human switching also invalidates this assertion"); } @@ -206,7 +206,7 @@ async fn wait_for_observer(path: &str) -> Value { && state["active"] == true && state["key_window"] == true && state["pid"].as_i64().map(|pid| pid as i32) - == crate::computer_use::macos_bg_input::frontmost_pid_macos() + == openbitfun_computer_use::test_support::frontmost_pid() }) { return state; } @@ -251,7 +251,7 @@ pub(crate) async fn run() { if let Ok(observer_path) = std::env::var("OPENBITFUN_INPUT_OBSERVER_RESULT") { wait_for_observer(&observer_path).await; } - let foreground = crate::computer_use::macos_bg_input::frontmost_pid_macos(); + let foreground = openbitfun_computer_use::test_support::frontmost_pid(); assert_ne!( foreground, Some(pid), @@ -510,7 +510,7 @@ pub(crate) async fn run() { "stop must revoke the active generation" ); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); eprintln!("PASS native tool pipeline: observation, semantic click, image click, Unicode input, Return, OCR verification and stop; binding/generation/foreground stayed stable"); @@ -590,17 +590,7 @@ async fn self_webview_roundtrip() { // Use the actual observed element geometry to address the screenshot. The // tool still validates the screenshot and dispatches the input itself. let (left, top, width, height) = tokio::task::spawn_blocking(move || { - let target = - crate::computer_use::macos_ax_dump::retained_cached_target(pid as i32, idx).unwrap(); - assert_ne!( - unsafe { crate::computer_use::macos_ax_dispatch::actual_pid(target.reference().0) } - .unwrap(), - pid as i32, - "The fixture must exercise a real WebKit subprocess element" - ); - target - .frame_global() - .expect("WebKit button must expose real geometry") + openbitfun_computer_use::test_support::webkit_target_frame(pid as i32, idx) }) .await .unwrap(); @@ -670,45 +660,8 @@ async fn self_webview_roundtrip() { ) .await; let native_idx = observed_node_index(&typed, "Computer Use Self WebView Fixture"); - let native_target = - crate::computer_use::macos_ax_dump::retained_cached_target(pid as i32, native_idx).unwrap(); - let lease = crate::computer_use::control_session::acquire(OWNER, "app_click").unwrap(); - let stale_token = crate::computer_use::control_session::capture_token().unwrap(); - crate::computer_use::control_session::stop(Some(OWNER), "fixture_revoke_queued_input").unwrap(); - drop(lease); - tokio::task::spawn_blocking(move || { - use crate::computer_use::{control_session, macos_ax_dispatch}; - use core_foundation::{base::TCFType, string::CFString}; - assert_eq!( - unsafe { macos_ax_dispatch::actual_pid(native_target.reference().0) }.unwrap(), - pid as i32, - "Revocation must exercise a same-process main-queue message" - ); - control_session::with_token(stale_token, || unsafe { - let action = CFString::new("AXRaise"); - assert_eq!( - macos_ax_dispatch::perform_action( - native_target.reference().0, - action.as_concrete_TypeRef() - ), - -25200, - "Stopped input must be rejected on main before AXRaise" - ); - let attr = CFString::new("AXTitle"); - let value = CFString::new("Revoked write must not arrive"); - assert_eq!( - macos_ax_dispatch::set_input_attribute_value( - native_target.reference().0, - attr.as_concrete_TypeRef(), - value.as_CFTypeRef() - ), - -25200, - "Stopped input must be rejected on main before attribute writes" - ); - }); - }) - .await - .unwrap(); + openbitfun_computer_use::test_support::assert_revoked_writes(OWNER, pid as i32, native_idx) + .await; call(&tool, &context, json!({"action":"stop_control"})).await; eprintln!("PASS same-process AppKit/WebKit observations, screenshot, exact image/node clicks, Unicode text, shortcuts and Stop with stale-input rejection through ComputerUse"); } @@ -736,7 +689,7 @@ async fn run_covered_semantic() { .unwrap() .len(); assert_eq!(initial_observer["target_ahead"], false); - let foreground = crate::computer_use::macos_bg_input::frontmost_pid_macos(); + let foreground = openbitfun_computer_use::test_support::frontmost_pid(); assert_ne!(foreground, Some(pid)); assert_eq!(initial["active"], false); let host = Arc::new(DesktopComputerUseHost::new()); @@ -775,7 +728,7 @@ async fn run_covered_semantic() { let active = call(&tool, &context, json!({"action":"activate_app","app":app})).await; assert_eq!(active["activated"], true); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), Some(pid) ); let field = observed_node_index(&active, "fixture-text-field"); @@ -810,8 +763,7 @@ async fn run_covered_semantic() { // with live alternatives; foreground activate_app restores the exact // window before activating it and returns a fresh observation. let window_id = initial["window_id"].as_u64().unwrap(); - crate::computer_use::macos_ax_ui::minimize_window_for_fixture(pid, window_id as u32) - .unwrap(); + openbitfun_computer_use::test_support::minimize_window(pid, window_id as u32).unwrap(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); let unavailable = loop { match tool @@ -860,7 +812,7 @@ async fn run_covered_semantic() { Some(format!("pid:{pid}/window:{window_id}")) ); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), Some(pid) ); assert_eq!(read(&path)["foreign_actions"], 0); @@ -887,7 +839,7 @@ async fn run_covered_semantic() { assert_eq!(opened["success"], true); assert_eq!(opened["process_id"], pid); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); let opened_by_path = call( @@ -900,7 +852,7 @@ async fn run_covered_semantic() { assert_eq!(opened_by_path["process_id"], pid); assert_eq!(opened_by_path["launch_path"], "open_background"); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); let observation = call( @@ -945,32 +897,14 @@ async fn run_covered_semantic() { eprintln!("PASS AX-only observations retain fresh actionable node identities and default observation restores pixels"); eprintln!( "After initial observation frontmost={:?} observer={}", - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), read(&observer_path) ); // Reading an all-window AX snapshot is allowed, but input cannot escape // the captured window via a same-pid node or its coordinate fallback. { - let mut lease = crate::computer_use::control_session::acquire(OWNER, "app_click").unwrap(); - let snapshot = - crate::computer_use::macos_ax_dump::dump_app_ax(pid, Default::default()).unwrap(); - let foreign = snapshot - .nodes - .iter() - .find(|node| node.title.as_deref() == Some("Unbound semantic action")) - .expect("second-window control missing"); - let target = - crate::computer_use::macos_ax_dump::retained_cached_target(pid, foreign.idx).unwrap(); - assert!( - crate::computer_use::macos_ax_dump::validate_bound_target(pid, target.reference()) - .is_err() - ); - assert!(matches!( - crate::computer_use::macos_ax_write::try_ax_press(target.reference()), - crate::computer_use::macos_ax_write::AxWriteOutcome::Unavailable(_) - )); + openbitfun_computer_use::test_support::assert_unbound_window_rejected(OWNER, pid); assert_eq!(read(&path)["foreign_actions"], 0); - lease.complete(); eprintln!("PASS same-process unbound AX window cannot receive semantic input or a pointer fallback"); } let image_target = |observation: &Value, name: &str| { @@ -1045,7 +979,7 @@ async fn run_covered_semantic() { assert_eq!(content_events[1]["type"], 2); assert_eq!(target["foreign_actions"], 0); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); let observer = read(&observer_path); @@ -1064,13 +998,13 @@ async fn run_covered_semantic() { eprintln!( "Before image button: observer={} frontmost={:?}", read(&observer_path), - crate::computer_use::macos_bg_input::frontmost_pid_macos() + openbitfun_computer_use::test_support::frontmost_pid() ); let observation = call(&tool, &context, json!({"action":"app_click","app":{"pid":pid},"target":image_target(&observation,"button")})).await; tokio::time::sleep(std::time::Duration::from_millis(80)).await; let button_state = read(&path); let button_observer = read(&observer_path); - eprintln!("After image button: target={button_state} observer={button_observer} frontmost={:?} expected={foreground:?}", crate::computer_use::macos_bg_input::frontmost_pid_macos()); + eprintln!("After image button: target={button_state} observer={button_observer} frontmost={:?} expected={foreground:?}", openbitfun_computer_use::test_support::frontmost_pid()); assert_eq!(button_state["button_actions"], 2); assert_eq!( button_state["events"].as_array().unwrap().len(), @@ -1083,7 +1017,7 @@ async fn run_covered_semantic() { assert_eq!(button_observer["key_window"], true); assert_eq!(button_observer["target_ahead"], false); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); eprintln!("PASS production ImageXy button activation exactly once without raw pointer events or raising the target"); @@ -1101,7 +1035,7 @@ async fn run_covered_semantic() { tokio::time::sleep(std::time::Duration::from_millis(80)).await; let state = read(&path); let observer = read(&observer_path); - eprintln!("TRACE production ImageXy semantic focus: target={state} observer={observer} frontmost={:?}", crate::computer_use::macos_bg_input::frontmost_pid_macos()); + eprintln!("TRACE production ImageXy semantic focus: target={state} observer={observer} frontmost={:?}", openbitfun_computer_use::test_support::frontmost_pid()); assert_eq!(state["field_text"], "native-control🙂中文"); assert_eq!( state["events"].as_array().unwrap().len(), @@ -1114,7 +1048,7 @@ async fn run_covered_semantic() { assert_eq!(observer["key_window"], true); assert_eq!(observer["target_ahead"], false); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); let result = call(&tool, &context, json!({"action":"app_scroll","app":{"pid":pid},"dx":0,"dy":42,"focus":image_target(&result,"canvas")})).await; @@ -1136,7 +1070,7 @@ async fn run_covered_semantic() { assert_eq!(scroll_observer["key_window"], true); assert_eq!(scroll_observer["target_ahead"], false); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); eprintln!("PASS scroll anchor delivers canvas scrolling without a click or foreground change"); @@ -1179,13 +1113,13 @@ async fn run_covered_semantic() { let before_stop_observer = read(&observer_path); eprintln!( "TRACE after canvas batch: observer={before_stop_observer} foreground={:?}", - crate::computer_use::macos_bg_input::frontmost_pid_macos() + openbitfun_computer_use::test_support::frontmost_pid() ); assert_eq!(before_stop_observer["active"], true); assert_eq!(before_stop_observer["key_window"], true); assert_eq!(before_stop_observer["target_ahead"], false); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); eprintln!( @@ -1207,12 +1141,10 @@ async fn run_covered_semantic() { // Induce a real target-local deactivation without changing the global // foreground. The next ordinary Tool input must notice the stale local // focus and prepare it again, preserving the original first responder. - let identity = crate::computer_use::macos_skylight::process_identity(pid).unwrap(); - assert!(crate::computer_use::macos_skylight::set_local_activation( - identity, + openbitfun_computer_use::test_support::deactivate_target( + pid, initial["window_id"].as_u64().unwrap() as u32, - false - )); + ); for _ in 0..25 { if read(&path)["active"] == false { break; @@ -1225,7 +1157,7 @@ async fn run_covered_semantic() { "fixture must really lose local focus" ); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); let recovered = call( @@ -1302,13 +1234,13 @@ async fn run_covered_semantic() { eprintln!( "TRACE after stop: observer={final_observer} target={} foreground={:?}", read(&path), - crate::computer_use::macos_bg_input::frontmost_pid_macos() + openbitfun_computer_use::test_support::frontmost_pid() ); assert_eq!(final_observer["active"], true); assert_eq!(final_observer["key_window"], true); assert_eq!(final_observer["target_ahead"], false); assert_eq!( - crate::computer_use::macos_bg_input::frontmost_pid_macos(), + openbitfun_computer_use::test_support::frontmost_pid(), foreground ); assert!( @@ -1344,7 +1276,7 @@ async fn run_latency_case(case: &str) { serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() }; let observer = wait_for_observer(&observer_path).await; - let foreground = crate::computer_use::macos_bg_input::frontmost_pid_macos(); + let foreground = openbitfun_computer_use::test_support::frontmost_pid(); assert_ne!(foreground, Some(pid)); assert_eq!(observer["target_ahead"], false); assert_eq!(read(&path)["field_text"], ""); diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 6ed7aa8a7b..f5f32eddfd 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -52,7 +52,7 @@ mod window_state_support; mod window_webview_geometry; use openbitfun_agent_runtime::sdk::{attach_session_event_cursor, SessionEventJournal}; -use openbitfun_core::agentic::tools::computer_use_capability::set_computer_use_desktop_available; +use openbitfun_core::agentic::tools::computer_use_capability::set_computer_use_host_available; use openbitfun_core::agentic::tools::computer_use_host::ComputerUseHostRef; use openbitfun_core::infrastructure::ai::AIClientFactory; use openbitfun_core::infrastructure::{get_path_manager_arc, try_get_path_manager_arc}; @@ -2177,9 +2177,17 @@ async fn init_agentic_system() -> anyhow::Result<( openbitfun_core::product_runtime::core_permission_request_manager() .map_err(anyhow::Error::msg)?; + if let Ok(paths) = openbitfun_core::infrastructure::try_get_path_manager_arc() { + openbitfun_computer_use::set_ocr_debug_directory( + paths + .default_assistant_workspace_dir(None) + .join(openbitfun_core_types::product_identity::hidden_data_directory()) + .join("computer_use_debug"), + ); + } let computer_use_host: ComputerUseHostRef = Arc::new(computer_use::DesktopComputerUseHost::new()); - set_computer_use_desktop_available(true); + set_computer_use_host_available(true); let tool_pipeline = Arc::new( tools::pipeline::ToolPipeline::new( diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 251f3d64ce..98687a7b79 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -612,7 +612,7 @@ cargo test -p openbitfun-core --no-default-features --features agent-runtime,git ``` These mock-host tests do not validate native capture, background input or remote -GUI behavior; native fixtures remain owned by the Desktop Computer Use guide. +GUI behavior; native fixtures remain owned by the shared Computer Use service guide. For plain-prompt goal activation and remote goal storage routing: diff --git a/src/crates/assembly/core/src/agentic/system.rs b/src/crates/assembly/core/src/agentic/system.rs index dc4a50a3e7..21cd42d47e 100644 --- a/src/crates/assembly/core/src/agentic/system.rs +++ b/src/crates/assembly/core/src/agentic/system.rs @@ -81,6 +81,17 @@ pub async fn init_agentic_system_for_profile_with_runtime_ownership( delivery_profile: DeliveryProfile, runtime_ownership: Arc, ) -> Result { + init_agentic_system_with_computer_use_host(delivery_profile, runtime_ownership, None).await +} + +/// Assemble the same Runtime with an explicit native provider from its host. +/// No provider is inferred from the delivery profile or controller environment. +pub async fn init_agentic_system_with_computer_use_host( + delivery_profile: DeliveryProfile, + runtime_ownership: Arc, + computer_use_host: Option, +) -> Result { + tools::computer_use_capability::set_computer_use_host_available(computer_use_host.is_some()); info!("Initializing agentic system for profile {delivery_profile}"); select_agentic_system_profile(delivery_profile)?; @@ -120,7 +131,7 @@ pub async fn init_agentic_system_for_profile_with_runtime_ownership( let permission_request_manager = crate::product_runtime::core_permission_request_manager().map_err(anyhow::Error::msg)?; let tool_pipeline = Arc::new( - tools::pipeline::ToolPipeline::new(tool_registry, tool_state_manager, None) + tools::pipeline::ToolPipeline::new(tool_registry, tool_state_manager, computer_use_host) .with_permission_request_manager(permission_request_manager), ); diff --git a/src/crates/assembly/core/src/agentic/tools/computer_use_capability.rs b/src/crates/assembly/core/src/agentic/tools/computer_use_capability.rs index f7b334d37e..d865ff5c25 100644 --- a/src/crates/assembly/core/src/agentic/tools/computer_use_capability.rs +++ b/src/crates/assembly/core/src/agentic/tools/computer_use_capability.rs @@ -1,14 +1,13 @@ -//! Desktop-only gate for Computer use (set from OpenBitFun desktop at startup). - +//! Runtime-host capability gate; a product surface name is not a provider. use std::sync::atomic::{AtomicBool, Ordering}; +static COMPUTER_USE_HOST_AVAILABLE: AtomicBool = AtomicBool::new(false); -static COMPUTER_USE_DESKTOP_AVAILABLE: AtomicBool = AtomicBool::new(false); - -/// Mark whether this process is OpenBitFun desktop with OS automation wired up. -pub fn set_computer_use_desktop_available(available: bool) { - COMPUTER_USE_DESKTOP_AVAILABLE.store(available, Ordering::SeqCst); +pub fn set_computer_use_host_available(available: bool) { + COMPUTER_USE_HOST_AVAILABLE.store(available, Ordering::SeqCst); } - -pub fn computer_use_desktop_available() -> bool { - COMPUTER_USE_DESKTOP_AVAILABLE.load(Ordering::SeqCst) +pub fn computer_use_host_available() -> bool { + COMPUTER_USE_HOST_AVAILABLE.load(Ordering::SeqCst) } +// Retained source compatibility for existing embedders. +pub use computer_use_host_available as computer_use_desktop_available; +pub use set_computer_use_host_available as set_computer_use_desktop_available; diff --git a/src/crates/assembly/core/src/agentic/tools/computer_use_host.rs b/src/crates/assembly/core/src/agentic/tools/computer_use_host.rs index 330edaefa4..de22297478 100644 --- a/src/crates/assembly/core/src/agentic/tools/computer_use_host.rs +++ b/src/crates/assembly/core/src/agentic/tools/computer_use_host.rs @@ -1,677 +1,2 @@ -//! Host abstraction for desktop automation (implemented in `openbitfun-desktop`). - -// Re-export optimizer types so downstream crates can import from computer_use_host. -pub use crate::agentic::tools::computer_use_optimizer::{ActionRecord, LoopDetectionResult}; -pub use openbitfun_agent_tools::computer_use::{ - app_input_settle_decision, app_input_settle_next_wait_ms, clamp_point_crop_half_extent, - parse_windows_accelerator_display, suggested_point_crop_half_extent_from_native_bounds, - AppClickParams, AppInfo, AppInputAction, AppInputSettle, AppInputSettlePolicy, - AppInputSettleStatus, AppMenuShortcut, AppSelector, AppShortcutsSnapshot, AppStateSnapshot, - AppWaitPredicate, AppWindowInfo, AxNode, CaptureFrameInfo, ClickIndexTarget, ClickTarget, - ComputerScreenshot, ComputerUseAuxiliaryWindow, ComputerUseDisplayInfo, - ComputerUseForegroundApplication, ComputerUseImageContentRect, ComputerUseImageGlobalBounds, - ComputerUseImplicitScreenshotCenter, ComputerUseInteractionScreenshotKind, - ComputerUseInteractionState, ComputerUseLastMutationKind, ComputerUseNavigateQuadrant, - ComputerUseNavigationRect, ComputerUsePermissionSnapshot, ComputerUsePointerGlobal, - ComputerUseScreenshotParams, ComputerUseScreenshotRefinement, ComputerUseSessionSnapshot, - ComputerUseZoomRegion, InteractiveActionResult, InteractiveClickParams, InteractiveElement, - InteractiveScrollParams, InteractiveTypeTextParams, InteractiveView, InteractiveViewOpts, - OcrAccessibilityHit, OcrRegionNative, OcrTextMatch, OpenAppResult, ScreenshotCropCenter, - UiElementLocateQuery, UiElementLocateResult, VisualActionResult, VisualClickParams, - VisualImageRegion, VisualMark, VisualMarkView, VisualMarkViewOpts, - COMPUTER_USE_POINT_CROP_HALF_DEFAULT, COMPUTER_USE_POINT_CROP_HALF_MAX, - COMPUTER_USE_POINT_CROP_HALF_MIN, COMPUTER_USE_QUADRANT_CLICK_READY_MAX_LONG_EDGE, - COMPUTER_USE_QUADRANT_EDGE_EXPAND_PX, -}; - -use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; -use async_trait::async_trait; -pub use openbitfun_agent_tools::computer_use_control::{ - ControlMode, ControlSnapshot, ControlStartRequest, -}; - -/// A host resource lease. Dropping an unfinished lease cancels native control. -pub trait ComputerUseActionLease: Send + Sync { - fn complete(&mut self); -} - -#[async_trait] -pub trait ComputerUseHost: Send + Sync + std::fmt::Debug { - /// Scope of the current native capture. None preserves older host behavior. - /// This is an observation fact, independent of the legacy navigation enum. - fn capture_scope(&self) -> Option<&'static str> { - None - } - - /// Validate an opaque observation reference against the prepared target. - /// Older hosts must reject explicit references they cannot validate. - fn validate_observation(&self, _observation_id: &str) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "[OBSERVATION_REFERENCE_UNSUPPORTED] This host cannot validate observation_id", - )) - } - - async fn prepare_control_target(&self, _app: AppSelector) -> OpenBitFunResult<()> { - Ok(()) - } - /// Foreground-only activation of the prepared native window. Capability - /// negotiation prevents an older/portal host from ignoring an exact target. - async fn activate_app(&self, _app: AppSelector) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "[ACTIVATION_UNSUPPORTED] This host cannot activate a native window. On Linux use the consented portal surface and verify focus before seat input.", - )) - } - /// Capture a rectangle of an earlier observation of the bound window again - /// at higher detail (app-zoom-v1). The result is a new image observation - /// with its own screenshot_id; image_xy on it maps into that rectangle. - async fn zoom_observation( - &self, - _app: AppSelector, - _region: ComputerUseZoomRegion, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "[ZOOM_UNSUPPORTED] This host does not advertise app-zoom-v1; observe the full window instead", - )) - } - /// Foreground-only recovery of a selected window that has no live surface: - /// unhide its application and un-minimize the window. Returns whether a - /// window state was changed; the caller prepares the target again. - async fn restore_window(&self, _app: AppSelector) -> OpenBitFunResult { - Ok(false) - } - async fn start_control( - &self, - _owner: &str, - _request: ControlStartRequest, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "[CONTROL_UNSUPPORTED] This host has no control-session provider", - )) - } - fn control_snapshot(&self) -> ControlSnapshot { - ControlSnapshot::default() - } - async fn stop_control(&self, _owner: &str) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "[CONTROL_UNSUPPORTED] This host has no control-session provider", - )) - } - async fn stop_control_generation( - &self, - owner: &str, - generation: u64, - ) -> OpenBitFunResult { - let _ = (owner, generation); - Err(OpenBitFunError::tool( - "[CONTROL_UNSUPPORTED] Conditional stop is unavailable on this host", - )) - } - async fn acquire_control_action( - &self, - _owner: &str, - _action: &str, - ) -> OpenBitFunResult>> { - Ok(None) - } - async fn permission_snapshot(&self) -> OpenBitFunResult; - - /// Platform-specific prompt (e.g. macOS accessibility dialog). - async fn request_accessibility_permission(&self) -> OpenBitFunResult<()>; - - /// Open settings or trigger OS screen-capture permission flow where supported. - async fn request_screen_capture_permission(&self) -> OpenBitFunResult<()>; - - /// Capture the display that contains `(0,0)`. See [`ComputerUseScreenshotParams`]: point crop, optional quadrant drill, refresh, reset. - async fn screenshot_display( - &self, - params: ComputerUseScreenshotParams, - ) -> OpenBitFunResult; - - /// Full-screen capture for **UI / human verification only**. Must **not** replace - /// `last_pointer_map`, navigation focus, or `last_screenshot_refinement` (unlike [`screenshot_display`](Self::screenshot_display)). - /// Desktop overrides with a side-effect-free capture; default delegates to a plain full-frame `screenshot_display` (may still advance navigation on naive embedders — override on desktop). - async fn screenshot_peek_full_display(&self) -> OpenBitFunResult { - self.screenshot_display(ComputerUseScreenshotParams::default()) - .await - } - - /// OCR on **raw display pixels** (no pointer overlay). Desktop captures only the relevant region: - /// optional `region_native`, else on macOS the frontmost window from Accessibility, else the primary display. - /// Default returns a "not implemented" error. Desktop overrides with Vision (macOS), WinRT OCR (Windows), or Tesseract (Linux). - async fn ocr_find_text_matches( - &self, - text_query: &str, - region_native: Option, - ) -> OpenBitFunResult> { - let _ = (text_query, region_native); - Err(OpenBitFunError::tool( - "OCR text recognition is not available on this host.".to_string(), - )) - } - - /// Read all visible text from the authorized target window without a search - /// query. Coordinates refer to the captured frame's global bounds. - async fn read_screen_text(&self) -> OpenBitFunResult> { - Err(OpenBitFunError::tool( - "[OCR_READ_UNSUPPORTED] Full-frame text reading is not available on this host.", - )) - } - - /// Best-effort accessibility element at a global screen point (native hit-test). - /// Desktop uses AX (macOS) / UIA (Windows). Returns `None` when unavailable or on miss. - async fn accessibility_hit_at_global_point( - &self, - _gx: f64, - _gy: f64, - ) -> OpenBitFunResult> { - Ok(None) - } - - /// JPEG crop (no pointer overlay) around `(gx, gy)` for OCR candidate previews. - async fn ocr_preview_crop_jpeg( - &self, - _gx: f64, - _gy: f64, - _half_extent_native: u32, - ) -> OpenBitFunResult> { - Err(OpenBitFunError::tool( - "OCR preview crops are not available on this host.".to_string(), - )) - } - - /// Map `(x, y)` from the **last** screenshot's image pixel grid to global pointer pixels. - /// Fails if no screenshot was taken in this process since startup (or since last host reset). - fn map_image_coords_to_pointer(&self, x: i32, y: i32) -> OpenBitFunResult<(i32, i32)>; - - /// Same as `map_image_coords_to_pointer` but **sub-point** precision (macOS: use for the `mouse_move` action). - fn map_image_coords_to_pointer_f64(&self, x: i32, y: i32) -> OpenBitFunResult<(f64, f64)> { - let (a, b) = self.map_image_coords_to_pointer(x, y)?; - Ok((a as f64, b as f64)) - } - - /// Map `(x, y)` with each axis in `0..=1000` to the captured display in native pointer pixels. - /// `(0,0)` ≈ top-left of capture, `(1000,1000)` ≈ bottom-right (inclusive mapping). - fn map_normalized_coords_to_pointer(&self, x: i32, y: i32) -> OpenBitFunResult<(i32, i32)>; - - fn map_normalized_coords_to_pointer_f64(&self, x: i32, y: i32) -> OpenBitFunResult<(f64, f64)> { - let (a, b) = self.map_normalized_coords_to_pointer(x, y)?; - Ok((a as f64, b as f64)) - } - - /// Absolute move in host global display coordinates (on macOS: CG space, **double** precision). - async fn mouse_move_global_f64(&self, gx: f64, gy: f64) -> OpenBitFunResult<()> { - self.mouse_move(gx.round() as i32, gy.round() as i32).await - } - - async fn mouse_move(&self, x: i32, y: i32) -> OpenBitFunResult<()>; - - /// Move the pointer by `(dx, dy)` in **global screen pixels** (same space as absolute `mouse_move` globals). - async fn pointer_move_relative(&self, dx: i32, dy: i32) -> OpenBitFunResult<()>; - - /// Click at the **current** pointer position only (does not move). Use `mouse_move` / `move_to_text` / `pointer_move_rel` first. - /// `button`: "left" | "right" | "middle" - /// On desktop, enforces the vision fine-screenshot guard (unlike [`mouse_click_authoritative`](Self::mouse_click_authoritative)). - async fn mouse_click(&self, button: &str) -> OpenBitFunResult<()>; - - /// Click at the current pointer after the host has moved it to a **trusted** target (`click_element`, `move_to_text`). - /// Skips the vision fine-screenshot / stale-pointer guard that [`mouse_click`](Self::mouse_click) applies after a pointer move. - /// Default: delegates to [`mouse_click`](Self::mouse_click). - async fn mouse_click_authoritative(&self, button: &str) -> OpenBitFunResult<()> { - self.mouse_click(button).await - } - - /// Press a mouse button and hold it at the current pointer position. - /// `button`: "left" | "right" | "middle" - async fn mouse_down(&self, _button: &str) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "mouse_down is not supported on this host.".to_string(), - )) - } - - /// Release a mouse button at the current pointer position. - /// `button`: "left" | "right" | "middle" - async fn mouse_up(&self, _button: &str) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "mouse_up is not supported on this host.".to_string(), - )) - } - - /// Press-drag-release gesture from `from` to `to` in **global screen - /// coordinates** with the given `button` over `duration_ms`. - /// - /// Default implementation composes the foreground `mouse_move_global_f64` / - /// `mouse_down` / `mouse_up` primitives (visible cursor movement). Hosts - /// that can drag without moving the user's cursor (e.g. the desktop host's - /// background `PostMessage` / CGEvent paths) override this. - async fn drag( - &self, - from: (f64, f64), - to: (f64, f64), - button: &str, - duration_ms: u64, - ) -> OpenBitFunResult<()> { - self.mouse_move_global_f64(from.0, from.1).await?; - self.mouse_down(button).await?; - let half = (duration_ms / 2).min(2_000); - if half > 0 { - self.wait_ms(half).await?; - } - self.mouse_move_global_f64(to.0, to.1).await?; - if half > 0 { - self.wait_ms(half).await?; - } - self.mouse_up(button).await - } - - async fn scroll(&self, delta_x: i32, delta_y: i32) -> OpenBitFunResult<()>; - - /// Press key combination; names like "command", "control", "shift", "alt", "return", "tab", "escape", "space", or single letters. - async fn key_chord(&self, keys: Vec) -> OpenBitFunResult<()>; - - /// Type Unicode text (synthesized key events; may be imperfect for some IMEs). - async fn type_text(&self, text: &str) -> OpenBitFunResult<()>; - - async fn wait_ms(&self, ms: u64) -> OpenBitFunResult<()>; - - /// Current frontmost app and global pointer position for tool-result JSON (`computer_use_context`). - /// Default: empty. Desktop overrides with platform queries (typically after each tool action). - async fn computer_use_session_snapshot(&self) -> ComputerUseSessionSnapshot { - ComputerUseSessionSnapshot::default() - } - - /// After a successful `screenshot_display`, the model may `mouse_click` (until the pointer moves again). - fn computer_use_after_screenshot(&self) {} - - /// After `mouse_move` / `pointer_move_rel` pointer moves: the next `mouse_click` must be preceded by a new screenshot. - fn computer_use_after_pointer_mutation(&self) {} - - /// After `mouse_click`, require a fresh screenshot before the next click (unless pointer moved, which also invalidates). - fn computer_use_after_click(&self) {} - - /// After a committed UI action that should be **visually confirmed** on the next `screenshot` - /// (Cowork-style: observe → act → verify). Desktop sets a pending flag; cleared when `screenshot_display` runs. - fn computer_use_after_committed_ui_action(&self) {} - - /// Record what the most recent action *was* (Click, Scroll, KeyChord …) - /// so the next `interaction_state.last_mutation` reports it. Hosts that - /// don't track this can leave the default no-op. - fn computer_use_record_mutation(&self, _kind: ComputerUseLastMutationKind) {} - - /// After `move_to_text` positioned the pointer with **trusted global OCR coordinates** (not JPEG guesses), - /// clear the stale-capture guard so the next **`click`** or Enter **`key_chord`** may proceed without another `screenshot`. - fn computer_use_trust_pointer_after_ocr_move(&self) {} - - /// After `type_text`: the pointer did not move; clear the stale-capture guard so Enter **`key_chord`** - /// is not blocked solely because of a prior click / scroll. - fn computer_use_trust_pointer_after_text_input(&self) {} - - /// Clear the stale-capture guard because it **cannot be satisfied** on this - /// run, not because the pointer became trustworthy. - /// - /// The guard exists to force a fresh look before a committing action. That - /// only means something for a model that can look. When the primary model - /// is text-only, `screenshot` returns no image and never reaches - /// `transition_after_screenshot`, so the guard latches on forever: the - /// error says "call `screenshot` first", the model calls `screenshot`, - /// nothing changes, and every `click` / Enter `key_chord` is refused for the - /// rest of the session. Text-only observation (`describe_screen`) is the - /// real equivalent of a capture there, so it waives the guard instead. - fn computer_use_waive_fresh_capture_guard(&self) {} - - /// Refuse `mouse_click` if the pointer moved (or a click happened) since the last screenshot, - /// or if the latest capture is not a valid “fine” basis (desktop: ~500×500 point crop **or** - /// quadrant navigation region with longest side < [`COMPUTER_USE_QUADRANT_CLICK_READY_MAX_LONG_EDGE`]). - fn computer_use_guard_click_allowed(&self) -> OpenBitFunResult<()> { - Ok(()) - } - - /// Relaxed click guard for AX-based `click_element`: skips the fine-screenshot requirement. - /// AX coordinates are authoritative, so no quadrant drill or point crop is needed. - fn computer_use_guard_click_allowed_relaxed(&self) -> OpenBitFunResult<()> { - Ok(()) - } - - /// What the **last** `screenshot_display` captured (e.g. coordinate hints for the model). - /// Default: unknown (`None`). Desktop sets after each `screenshot_display`. - fn last_screenshot_refinement(&self) -> Option { - None - } - - /// Derive structured interaction readiness and guidance from the current session state. - /// Default: empty/default state. Desktop overrides with state-driven implementation. - fn computer_use_interaction_state(&self) -> ComputerUseInteractionState { - ComputerUseInteractionState::default() - } - - /// Search the frontmost app’s accessibility tree (macOS AX) for a matching control and return a stable center. - /// Default: unsupported outside the desktop host / non-macOS. - async fn locate_ui_element_screen_center( - &self, - _query: UiElementLocateQuery, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "Native UI element (accessibility) lookup is not available on this host.".to_string(), - )) - } - - /// Enumerate the condensed UI tree text representation for the screenshot context. - /// Default: no UI tree text. - async fn enumerate_ui_tree_text(&self) -> Option { - None - } - - /// Record a completed action for loop detection and history tracking. - /// Default: no-op. Desktop host overrides with optimizer integration. - fn record_action(&self, _action_type: &str, _action_params: &str, _success: bool) {} - - /// Update the screenshot hash for visual change detection. - /// Default: no-op. Desktop host overrides with optimizer integration. - fn update_screenshot_hash(&self, _hash: u64) {} - - /// Check if the agent is stuck in a repeating action loop. - /// Returns a detection result with suggestions if a loop is found. - /// Default: no loop detected. - fn detect_action_loop(&self) -> LoopDetectionResult { - LoopDetectionResult { - is_loop: false, - pattern_length: 0, - repetitions: 0, - suggestion: String::new(), - } - } - - /// Get action history for context and backtracking. - /// Default: empty history. - fn get_action_history(&self) -> Vec { - vec![] - } - - /// Launch a macOS/Windows/Linux application by name and return its PID. - /// Default: unsupported. Desktop host overrides with platform-specific implementation. - async fn open_app(&self, _app_name: &str) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "open_app is not available on this host.".to_string(), - )) - } - - /// Enumerate all physical displays attached to the host. The returned - /// list is what the model sees in `interaction_state.displays` and what - /// `ControlHub` exposes via `desktop.list_displays`. - /// - /// Default: empty (non-desktop hosts can't enumerate displays). - async fn list_displays(&self) -> OpenBitFunResult> { - Ok(vec![]) - } - - /// Pin subsequent screenshots / clicks / locates to the display with - /// `display_id`. Pass `None` to clear the preference and fall back to - /// "screen under the pointer". Hosts that don't track a preferred - /// display can leave the default no-op. - /// - /// This is the explicit fix for the original bug — instead of guessing - /// the target display from the cursor (which is wrong whenever the user - /// has the keyboard focus on a different screen), the model can - /// announce "I am working on display N" and the host will commit to it. - async fn focus_display(&self, _display_id: Option) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "focus_display is not available on this host.".to_string(), - )) - } - - /// Currently pinned display id, if any. Surfaced to the model via - /// `interaction_state.active_display_id`. - fn focused_display_id(&self) -> Option { - None - } - - // ------------------------------------------------------------------- - // Codex-style AX-first desktop API (Phase 1: trait surface only). - // - // All methods default to `not available` so existing platform hosts - // (macOS/Linux/Windows desktop, headless test hosts) continue to - // compile and behave exactly as before. Concrete implementations are - // landed in subsequent phases (macos_ax_dump, desktop_host PID-events, - // linux/windows AT-SPI/UIA, ControlHub dispatch). - // ------------------------------------------------------------------- - - /// Whether this host can dispatch synthetic input events to a target - /// application **without** stealing the user's foreground focus or - /// moving their physical cursor. macOS desktop will set this to true - /// once the `CGEventPostToPid` + private-source path is wired and the - /// startup self-check passes; non-macOS hosts stay `false` for now. - fn supports_background_input(&self) -> bool { - false - } - - /// Whether this host can dump a structured accessibility tree per - /// running application (Codex-style `` payload). macOS uses - /// AX, Linux uses AT-SPI2, Windows uses UIA. Hosts without an AX - /// backend stay `false` so the model falls back to the screenshot path. - fn supports_ax_tree(&self) -> bool { - false - } - - /// Enumerate running applications, sorted by recency / launch count - /// (Codex's `list_apps`). Default: empty list — callers should treat an - /// empty result as "not available on this host". - async fn list_apps(&self, _include_hidden: bool) -> OpenBitFunResult> { - Ok(vec![]) - } - - /// Native window inventory. Omit `app` to discover windows across process - /// boundaries; explicit selectors filter the inventory without binding it. - async fn list_windows( - &self, - _app: Option, - ) -> OpenBitFunResult> { - Err(OpenBitFunError::tool( - "[WINDOW_DISCOVERY_UNSUPPORTED] This host cannot enumerate native windows; use list_apps and supported app observations", - )) - } - - /// Dump the accessibility tree of a target application, returning a - /// stable [`AppStateSnapshot`] (Codex's `get_app_state`). Default: - /// unsupported. Implementations cache `idx → element` so - /// [`Self::app_click`] etc. can address nodes by index. - async fn get_app_state( - &self, - _app: AppSelector, - _max_depth: u32, - _focus_window_only: bool, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "get_app_state is not available on this host.".to_string(), - )) - } - - /// Select whether an observation needs pixels. Older providers keep their - /// existing capture behavior, then omit the image from the result. Native - /// providers can override this to avoid capture and encoding altogether. - /// Omitting the tool option retains the original image-bearing observation. - async fn get_app_state_with_options( - &self, - app: AppSelector, - max_depth: u32, - focus_window_only: bool, - include_image: bool, - ) -> OpenBitFunResult { - let mut snapshot = self - .get_app_state(app, max_depth, focus_window_only) - .await?; - if !include_image { - snapshot.screenshot = None; - } - Ok(snapshot) - } - - /// Whether this host can enumerate a target application's menu-bar - /// keyboard shortcuts (Codex-adjacent `get_app_shortcuts`). This is the - /// **read** counterpart to [`Self::key_chord`] / [`Self::app_key_chord`] - /// (which only **send** keys): macOS reads `AXMenuBar` / - /// `AXMenuItemCmd*`, Windows reads the UIA menu tree's - /// `AcceleratorKey` property. Hosts without a menu-introspection - /// backend stay `false`. - fn supports_app_shortcuts(&self) -> bool { - false - } - - /// Enumerate the keyboard shortcuts registered in a target - /// application's menu bar. Unlike [`Self::get_app_state`], this does - /// **not** require the app to be frontmost on macOS (menu structure is - /// queryable from any running app's AX element); on Windows it - /// resolves a top-level window owned by the target app. Default: - /// unsupported. - async fn get_app_shortcuts(&self, _app: AppSelector) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "get_app_shortcuts is not available on this host.".to_string(), - )) - } - - /// Click inside a target application. When [`ClickTarget::NodeIdx`] is - /// used, the host first tries the AX action path - /// (`AXUIElementPerformAction`) and falls back to a PID-scoped - /// synthetic mouse event. Returns the after-state snapshot so the - /// model can verify the change in a single round-trip. - /// Submit one app input without taking an observation. Batch orchestration - /// observes once after the sequence; unsupported older providers fail explicitly. - async fn dispatch_app_input( - &self, - _app: AppSelector, - _action: AppInputAction, - ) -> OpenBitFunResult<()> { - Err(OpenBitFunError::tool( - "[APP_INPUT_UNSUPPORTED] This provider does not expose observation-free app input", - )) - } - - /// Wait, without sending input, until the app's bound window stops - /// repainting after submitted input, within `policy`. Providers without a - /// live frame stream report `Unavailable`; the caller still observes. - async fn settle_after_input( - &self, - _app: AppSelector, - _policy: AppInputSettlePolicy, - ) -> OpenBitFunResult { - Ok(AppInputSettle::unavailable( - "This provider cannot measure window repaint after input", - )) - } - - /// Poll an application's AX tree until `pred` matches or `timeout_ms` - /// elapses. Returns the matching snapshot. Default: unsupported. - async fn app_wait_for( - &self, - _app: AppSelector, - _pred: AppWaitPredicate, - _timeout_ms: u32, - _poll_ms: u32, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "app_wait_for is not available on this host.".to_string(), - )) - } - - // ------------------------------------------------------------------- - // Interactive-View (Set-of-Mark) API — TuriX-CUA inspired. - // - // Goal: collapse the model's "where do I click?" decision into a single - // numeric index `i` that is rendered as a coloured numbered box on top - // of a focused-window screenshot. The model picks `i`, the host - // resolves it back to an authoritative AX action — no coordinate - // guessing, no JPEG-pixel arithmetic. - // - // Defaults are `not available` so non-desktop / non-AX hosts continue - // to compile and behave exactly as before. - // ------------------------------------------------------------------- - - /// Whether this host can build a Set-of-Mark interactive view (filtered - /// AX elements + numbered overlay screenshot). Hosts without an AX - /// backend stay `false`. - fn supports_interactive_view(&self) -> bool { - false - } - - /// Build a Set-of-Mark view for the given application: filters the AX - /// tree to interactive elements, assigns a dense `i` index per element, - /// and overlays numbered colour-coded boxes on the focused-window - /// screenshot. The returned [`InteractiveView`] is the **default** input - /// surface the model should use for desktop GUI work. - async fn build_interactive_view( - &self, - _app: AppSelector, - _opts: InteractiveViewOpts, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "build_interactive_view is not available on this host.".to_string(), - )) - } - - /// Click an element by its [`InteractiveElement::i`] index from the most - /// recent [`InteractiveView`] of the same application. Returns the - /// after-state view (re-built post-action) when `return_view=true`, else - /// just the bare [`AppStateSnapshot`] for cheaper polling. - async fn interactive_click( - &self, - _app: AppSelector, - _params: InteractiveClickParams, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "interactive_click is not available on this host.".to_string(), - )) - } - - /// Type text into an element by its `i` index (focuses first via AX, - /// then dispatches PID-scoped key events / paste). When `i` is `None`, - /// types into the currently focused element. - async fn interactive_type_text( - &self, - _app: AppSelector, - _params: InteractiveTypeTextParams, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "interactive_type_text is not available on this host.".to_string(), - )) - } - - /// Scroll inside (or over) an element by its `i` index. Pass `i=None` - /// to scroll over the focused window. - async fn interactive_scroll( - &self, - _app: AppSelector, - _params: InteractiveScrollParams, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "interactive_scroll is not available on this host.".to_string(), - )) - } - - /// Whether this host can build a generic visual mark view for arbitrary - /// non-AX/non-OCR surfaces. Unlike [`Self::build_interactive_view`], this - /// does not require accessibility nodes; it marks candidate points in the - /// screenshot itself. - fn supports_visual_mark_view(&self) -> bool { - false - } - - async fn build_visual_mark_view( - &self, - _app: AppSelector, - _opts: VisualMarkViewOpts, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "build_visual_mark_view is not available on this host.".to_string(), - )) - } - - async fn visual_click( - &self, - _app: AppSelector, - _params: VisualClickParams, - ) -> OpenBitFunResult { - Err(OpenBitFunError::tool( - "visual_click is not available on this host.".to_string(), - )) - } -} - -pub type ComputerUseHostRef = std::sync::Arc; +//! Compatibility import path for the portable Computer Use provider contract. +pub use openbitfun_agent_tools::computer_use_host::*; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_actions.rs b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_actions.rs index 3d035ae481..6c6ff00bec 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_actions.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_actions.rs @@ -239,7 +239,7 @@ impl ComputerUseActions { ) -> OpenBitFunResult> { let host = context.computer_use_host.as_ref().ok_or_else(|| { OpenBitFunError::tool( - "Desktop control is only available in the OpenBitFun desktop app".to_string(), + "Computer Use requires a native provider on the executing host".to_string(), ) })?; @@ -1786,12 +1786,12 @@ fn error_code_from_local(code: &str) -> ErrorCode { #[cfg(test)] mod tests { - use super::{ComputerUseActions, OpenBitFunError, ToolResult}; + use super::{ComputerUseActions, ToolResult}; use super::{OPEN_FILE_ROUTING_NOTE, OPEN_URL_ROUTING_NOTE}; + use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use serde_json::json; use crate::agentic::tools::computer_use_host as h; - use crate::util::errors::OpenBitFunResult; use std::sync::{Arc, Mutex}; #[test] diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_locate.rs b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_locate.rs index edbc379ea6..d98fe6fb0a 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_locate.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_locate.rs @@ -1,6 +1,6 @@ //! Accessibility tree locate -- invoked as `ComputerUse` **`action: "locate"`** (same tool as screenshot / keys). -use crate::agentic::tools::computer_use_capability::computer_use_desktop_available; +use crate::agentic::tools::computer_use_capability::computer_use_host_available; use crate::agentic::tools::computer_use_host::{ suggested_point_crop_half_extent_from_native_bounds, UiElementLocateQuery, }; @@ -22,7 +22,7 @@ pub(crate) async fn execute_computer_use_locate( .to_string(), )); } - if !computer_use_desktop_available() { + if !computer_use_host_available() { return Err(OpenBitFunError::tool( "Computer use is not available on this host.".to_string(), )); @@ -32,9 +32,11 @@ pub(crate) async fn execute_computer_use_locate( "Computer use configuration is unavailable.".to_string(), )); }; - let ai: crate::service::config::types::AIConfig = - service.get_config(Some("ai")).await.unwrap_or_default(); - if !ai.computer_use_enabled { + let enabled = service + .get_config::(Some("ai.computer_use_enabled")) + .await + .map_err(|_| OpenBitFunError::tool("Computer use configuration is unavailable."))?; + if !enabled { return Err(OpenBitFunError::tool( "Computer use is disabled in OpenBitFun settings.".to_string(), )); @@ -42,7 +44,7 @@ pub(crate) async fn execute_computer_use_locate( let host = context.computer_use_host.as_ref().ok_or_else(|| { OpenBitFunError::tool( - "Computer use is only available in the OpenBitFun desktop app.".to_string(), + "Computer Use requires a native provider on the executing host.".to_string(), ) })?; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_tool.rs index 0cd293e625..df76d19e15 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/computer_use_tool.rs @@ -2,7 +2,7 @@ use super::computer_use_locate::execute_computer_use_locate; use super::control_hub::{coded_tool_error, ErrorCode}; -use crate::agentic::tools::computer_use_capability::computer_use_desktop_available; +use crate::agentic::tools::computer_use_capability::computer_use_host_available; use crate::agentic::tools::computer_use_host::{ AppSelector, ComputerScreenshot, ComputerUseHost, OcrRegionNative, UiElementLocateQuery, }; @@ -1106,8 +1106,10 @@ Use ExecCommand for genuine shell work, never ad hoc GUI capture, clipboard or i } if coordinate_mode(input) == "normalized" { host.map_normalized_coords_to_pointer_f64(x, y) + .map_err(Into::into) } else { host.map_image_coords_to_pointer_f64(x, y) + .map_err(Into::into) } } @@ -1726,15 +1728,18 @@ Use ExecCommand for genuine shell work, never ad hoc GUI capture, clipboard or i } async fn is_enabled(&self) -> bool { - if !computer_use_desktop_available() { + if !computer_use_host_available() { return false; } let Ok(service) = GlobalConfigManager::get_service().await else { return false; }; - let ai: crate::service::config::types::AIConfig = - service.get_config(Some("ai")).await.unwrap_or_default(); - ai.computer_use_enabled + // Missing legacy fields are defaulted by the config owner. A failed + // read must not turn that default into authorization. + service + .get_config::(Some("ai.computer_use_enabled")) + .await + .unwrap_or(false) } async fn is_available_in_context(&self, context: Option<&ToolUseContext>) -> bool { @@ -1825,7 +1830,11 @@ impl ComputerUseTool { { return Err((error, SurfaceRecovery::NotAttempted)); } - match host.restore_window(app.clone()).await { + match host + .restore_window(app.clone()) + .await + .map_err(OpenBitFunError::from) + { Ok(true) => {} Ok(false) => return Err((error, SurfaceRecovery::NothingToRestore)), Err(restore_error) => { @@ -1862,7 +1871,7 @@ impl ComputerUseTool { )), _ = tokio::time::sleep(std::time::Duration::from_millis(150)) => {} } - match host.prepare_control_target(app.clone()).await { + match host.prepare_control_target(app.clone()).await.map_err(OpenBitFunError::from) { Ok(()) => return Ok(true), Err(error) if Self::surface_unavailable(&error) @@ -2003,10 +2012,9 @@ impl ComputerUseTool { "[CONTROL_ACTION_INVALID] Unknown ComputerUse action: {action}" )) })?; - let host = context - .computer_use_host - .as_ref() - .ok_or_else(|| OpenBitFunError::tool("Desktop control provider unavailable"))?; + let host = context.computer_use_host.as_ref().ok_or_else(|| { + OpenBitFunError::tool("Native Computer Use provider unavailable on the executing host") + })?; if action == "activate_app" && !host .control_snapshot() @@ -2086,7 +2094,7 @@ impl ComputerUseTool { }; let explicit_target = !app.is_empty(); let exact_window = app.window_id.is_some(); - let prepared = match host.prepare_control_target(app.clone()).await { + let prepared = match host.prepare_control_target(app.clone()).await.map_err(OpenBitFunError::from) { Err(error) if action == "activate_app" => { Self::restore_and_prepare(host, &app, error, context).await } @@ -2289,7 +2297,7 @@ impl ComputerUseTool { let host = context.computer_use_host.as_ref().ok_or_else(|| { OpenBitFunError::tool( - "Computer use is only available in the OpenBitFun desktop app.".to_string(), + "Computer Use requires a native provider on the executing host.".to_string(), ) })?; @@ -3197,7 +3205,7 @@ mod tests { ComputerUsePermissionSnapshot, ComputerUseScreenshotParams, ComputerUseSessionSnapshot, }; use crate::agentic::tools::framework::{Tool, ToolExposure, ToolResult, ToolUseContext}; - use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use serde_json::{json, Value}; #[test] @@ -4415,7 +4423,8 @@ mod tests { "image_rect":{"left":320,"top":0,"width":320,"height":240}, "global_bounds":{"left":50.0,"top":0.0,"width":60.0,"height":50.0} }] - }))?) + })) + .expect("valid fixture")) } async fn restore_window(&self, app: AppSelector) -> OpenBitFunResult { self.events @@ -4456,14 +4465,18 @@ mod tests { serde_json::from_value(json!({ "app":{"name":"Requested target","pid":421,"running":true}, "tree_text":"AXMenuBar target menu", "digest":"target-ax", "captured_at_ms":1 - }))?; + })) + .expect("valid fixture"); if self.observation_image { snapshot.observation_id = Some("fixture-current".into()); - snapshot.screenshot = Some(serde_json::from_value(json!({ - "screenshot_id":"fixture-image", "bytes":[1,2,3], "mime_type":"image/jpeg", - "image_width":16,"image_height":12,"native_width":16,"native_height":12, - "display_origin_x":0,"display_origin_y":0,"vision_scale":1.0 - }))?); + snapshot.screenshot = Some( + serde_json::from_value(json!({ + "screenshot_id":"fixture-image", "bytes":[1,2,3], "mime_type":"image/jpeg", + "image_width":16,"image_height":12,"native_width":16,"native_height":12, + "display_origin_x":0,"display_origin_y":0,"vision_scale":1.0 + })) + .expect("valid fixture"), + ); } Ok(snapshot) } @@ -4480,7 +4493,8 @@ mod tests { Ok(serde_json::from_value(json!({ "app":{"name":"Requested target","pid":421,"running":true}, "shortcuts":[],"captured_at_ms":1 - }))?) + })) + .expect("valid fixture")) } fn control_snapshot(&self) -> ControlSnapshot { self.state.lock().unwrap().clone() @@ -5696,11 +5710,13 @@ mod tests { "SCREEN_CAPTURE_PERMISSION_REQUIRED", ] { assert!(ComputerUseTool::capture_failure_allows_ax_observation( - &OpenBitFunError::tool(format!("{code}: details")) + &crate::util::errors::OpenBitFunError::tool(format!("{code}: details")) )); } assert!(!ComputerUseTool::capture_failure_allows_ax_observation( - &OpenBitFunError::tool("LOCAL_AUTHORIZATION_REQUIRED: approve access") + &crate::util::errors::OpenBitFunError::tool( + "LOCAL_AUTHORIZATION_REQUIRED: approve access" + ) )); } #[tokio::test] diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs index c2d406f951..b12896b74d 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs @@ -52,10 +52,9 @@ static BROWSER_SESSIONS: std::sync::OnceLock> = /// the headed browser sitting on that port. const DEFAULT_HEADLESS_CDP_PORT: u16 = DEFAULT_CDP_PORT + 1; -/// Computer Use is an independent switch from browser control (`ai.computer_use_enabled` -/// defaults to off, and there is no desktop host outside the desktop app), so ControlHub +/// Computer Use has an independent setting and native provider from browser control, so ControlHub /// must never route recovery through a tool that is absent from the agent's tool list. -const COMPUTER_USE_UNAVAILABLE_HINT: &str = "Desktop automation is unavailable in this session (Computer Use is off in Settings, or there is no desktop host). Do not call ComputerUse — it is not in your tool list. Use ControlHub browser.navigate for http(s) URLs on a Desktop host and ExecCommand for local files and scripts; ask the user to enable Computer Use in Settings if desktop control is genuinely required."; +const COMPUTER_USE_UNAVAILABLE_HINT: &str = "Desktop automation is unavailable in this session (Computer Use is disabled, or the executing host has no native graphical provider). Do not call ComputerUse — it is not in your tool list. Use an available ControlHub browser target for http(s) URLs and ExecCommand for local files and scripts. A disabled setting can be changed in Settings or with `openbitfun computer-use enable`; native control also requires a graphical login session on the executing host."; fn browser_sessions() -> Arc { BROWSER_SESSIONS @@ -628,14 +627,12 @@ Results: `{ok, domain, action, data? , error?: {code, message, hints}}`. Check o ) -> OpenBitFunResult> { match action { "capabilities" => { - // `terminal` (TerminalApi) is delivered through a global - // registry rather than a field on the context, so we can't be - // 100% sure here without round-tripping. We report "likely - // available iff a desktop host is present" because that bridge - // only exists in OpenBitFun's desktop runtime; the actual call will - // surface a clean error if the bridge is offline. + // CLI and Desktop register terminal and GUI providers separately. + // Read the same terminal registry used by the action dispatcher; + // this probe neither initializes the service nor opens a session. let is_remote = context.is_remote(); - let likely_terminal_available = !is_remote && context.computer_use_host.is_some(); + let terminal_available = + !is_remote && crate::service::terminal::TerminalApi::from_singleton().is_ok(); let browser_session_ids = if is_remote { Vec::new() } else { @@ -745,7 +742,7 @@ Results: `{ok, domain, action, data? , error?: {code, message, hints}}`. Check o "default_target": selection.as_ref().map(|s| s.target.as_str()).unwrap_or(if builtin_host_available { "builtin" } else { "external" }), "shared_action_contract": true, }, - "terminal": { "available": likely_terminal_available, "reason": if likely_terminal_available { Value::Null } else { json!("TerminalApi is only available in contexts that registered it") } }, + "terminal": { "available": terminal_available, "reason": if terminal_available { Value::Null } else { json!("TerminalApi is only available in local workspace contexts that registered it") } }, "meta": { "available": true }, }, "local_client": { @@ -762,7 +759,7 @@ Results: `{ok, domain, action, data? , error?: {code, message, hints}}`. Check o } else if is_remote { json!("Not available in remote workspace sessions") } else { - json!("Computer Use is disabled (ai.computer_use_enabled = false) or no desktop host is present") + json!("Computer Use is disabled (ai.computer_use_enabled = false) or the executing host has no native provider") }, }, "schema_version": "1.6", diff --git a/src/crates/assembly/core/src/util/errors.rs b/src/crates/assembly/core/src/util/errors.rs index dec93ad77d..453151fd31 100644 --- a/src/crates/assembly/core/src/util/errors.rs +++ b/src/crates/assembly/core/src/util/errors.rs @@ -407,3 +407,14 @@ mod tests { ); } } + +#[cfg(feature = "agent-runtime")] +impl From for OpenBitFunError { + fn from(error: openbitfun_agent_tools::computer_use_host::error::ComputerUseError) -> Self { + use openbitfun_agent_tools::computer_use_host::error::ComputerUseError; + match error { + ComputerUseError::Tool(message) => Self::Tool(message), + ComputerUseError::Service(message) => Self::Service(message), + } + } +} diff --git a/src/crates/contracts/config-contracts/src/types.rs b/src/crates/contracts/config-contracts/src/types.rs index ad9e630f1d..775906c05d 100644 --- a/src/crates/contracts/config-contracts/src/types.rs +++ b/src/crates/contracts/config-contracts/src/types.rs @@ -1349,8 +1349,9 @@ pub struct AIConfig { #[serde(default = "default_true")] pub allow_tool_json_repair: bool, - /// Allow Computer use (desktop automation) when the desktop host is available (all session modes). - #[serde(default)] + /// Allow Computer Use when the executing host has a native provider. + /// System consent and tool approval remain independent; persisted opt-outs win. + #[serde(default = "default_true")] pub computer_use_enabled: bool, /// Preferred browser for CDP browser control. Empty/default uses the system default browser. @@ -2310,7 +2311,7 @@ impl Default for AIConfig { enable_context_compression_prefetch: true, enable_edit_constraint_guard: false, allow_tool_json_repair: true, - computer_use_enabled: false, + computer_use_enabled: true, browser_control_preferred_browser: String::new(), web_search: WebSearchConfig::default(), browser_control_auto_connect_on_startup: false, @@ -3753,6 +3754,45 @@ mod tests { ); } + #[test] + fn computer_use_defaults_on_and_preserves_persisted_choices() { + assert!(AIConfig::default().computer_use_enabled); + let legacy: AIConfig = + serde_json::from_value(serde_json::json!({"max_rounds": 42})).unwrap(); + assert!(legacy.computer_use_enabled); + let reloaded: AIConfig = + serde_json::from_value(serde_json::to_value(&legacy).unwrap()).unwrap(); + assert!(reloaded.computer_use_enabled); + assert_eq!(reloaded.max_rounds, 42); + + // Only an absent legacy field takes the default; damaged preferences + // must remain errors instead of silently enabling native control. + for invalid in [ + serde_json::json!("false"), + serde_json::Value::Null, + serde_json::json!(1), + ] { + assert!(serde_json::from_value::(serde_json::json!({ + "computer_use_enabled": invalid + })) + .is_err()); + } + + for enabled in [false, true] { + let config: AIConfig = serde_json::from_value(serde_json::json!({ + "computer_use_enabled": enabled, + "max_rounds": 42 + })) + .unwrap(); + assert_eq!(config.computer_use_enabled, enabled); + let payload = serde_json::to_value(&config).unwrap(); + assert_eq!(payload["computer_use_enabled"], enabled); + let reloaded: AIConfig = serde_json::from_value(payload).unwrap(); + assert_eq!(reloaded.computer_use_enabled, enabled); + assert_eq!(reloaded.max_rounds, 42); + } + } + #[test] fn edit_constraint_guard_defaults_off_and_round_trips_explicit_opt_in() { assert!(!AIConfig::default().enable_edit_constraint_guard); diff --git a/src/crates/execution/tool-contracts/src/computer_use_host.rs b/src/crates/execution/tool-contracts/src/computer_use_host.rs new file mode 100644 index 0000000000..648e5ba205 --- /dev/null +++ b/src/crates/execution/tool-contracts/src/computer_use_host.rs @@ -0,0 +1,740 @@ +//! Portable native automation provider contract, shared by Desktop and CLI hosts. + +// Re-export optimizer types so downstream crates can import from computer_use_host. + +pub use crate::computer_use::{ + app_input_settle_decision, app_input_settle_next_wait_ms, clamp_point_crop_half_extent, + parse_windows_accelerator_display, suggested_point_crop_half_extent_from_native_bounds, + AppClickParams, AppInfo, AppInputAction, AppInputSettle, AppInputSettlePolicy, + AppInputSettleStatus, AppMenuShortcut, AppSelector, AppShortcutsSnapshot, AppStateSnapshot, + AppWaitPredicate, AppWindowInfo, AxNode, CaptureFrameInfo, ClickIndexTarget, ClickTarget, + ComputerScreenshot, ComputerUseAuxiliaryWindow, ComputerUseDisplayInfo, + ComputerUseForegroundApplication, ComputerUseImageContentRect, ComputerUseImageGlobalBounds, + ComputerUseImplicitScreenshotCenter, ComputerUseInteractionScreenshotKind, + ComputerUseInteractionState, ComputerUseLastMutationKind, ComputerUseNavigateQuadrant, + ComputerUseNavigationRect, ComputerUsePermissionSnapshot, ComputerUsePointerGlobal, + ComputerUseScreenshotParams, ComputerUseScreenshotRefinement, ComputerUseSessionSnapshot, + ComputerUseZoomRegion, InteractiveActionResult, InteractiveClickParams, InteractiveElement, + InteractiveScrollParams, InteractiveTypeTextParams, InteractiveView, InteractiveViewOpts, + OcrAccessibilityHit, OcrRegionNative, OcrTextMatch, OpenAppResult, ScreenshotCropCenter, + UiElementLocateQuery, UiElementLocateResult, VisualActionResult, VisualClickParams, + VisualImageRegion, VisualMark, VisualMarkView, VisualMarkViewOpts, + COMPUTER_USE_POINT_CROP_HALF_DEFAULT, COMPUTER_USE_POINT_CROP_HALF_MAX, + COMPUTER_USE_POINT_CROP_HALF_MIN, COMPUTER_USE_QUADRANT_CLICK_READY_MAX_LONG_EDGE, + COMPUTER_USE_QUADRANT_EDGE_EXPAND_PX, +}; + +use async_trait::async_trait; +use error::{OpenBitFunError, OpenBitFunResult}; +use serde::{Deserialize, Serialize}; + +/// Action record for history tracking +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ActionRecord { + pub timestamp_ms: u64, + pub action_type: String, + pub action_params: String, + pub success: bool, + pub screenshot_hash: Option, +} + +/// Loop detection result +#[derive(Debug, Clone)] +pub struct LoopDetectionResult { + pub is_loop: bool, + pub pattern_length: usize, + pub repetitions: usize, + pub suggestion: String, +} + +pub use crate::computer_use_control::{ControlMode, ControlSnapshot, ControlStartRequest}; + +/// A host resource lease. Dropping an unfinished lease cancels native control. +pub trait ComputerUseActionLease: Send + Sync { + fn complete(&mut self); +} + +#[async_trait] +pub trait ComputerUseHost: Send + Sync + std::fmt::Debug { + /// Scope of the current native capture. None preserves older host behavior. + /// This is an observation fact, independent of the legacy navigation enum. + fn capture_scope(&self) -> Option<&'static str> { + None + } + + /// Validate an opaque observation reference against the prepared target. + /// Older hosts must reject explicit references they cannot validate. + fn validate_observation(&self, _observation_id: &str) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "[OBSERVATION_REFERENCE_UNSUPPORTED] This host cannot validate observation_id", + )) + } + + async fn prepare_control_target(&self, _app: AppSelector) -> OpenBitFunResult<()> { + Ok(()) + } + /// Foreground-only activation of the prepared native window. Capability + /// negotiation prevents an older/portal host from ignoring an exact target. + async fn activate_app(&self, _app: AppSelector) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "[ACTIVATION_UNSUPPORTED] This host cannot activate a native window. On Linux use the consented portal surface and verify focus before seat input.", + )) + } + /// Capture a rectangle of an earlier observation of the bound window again + /// at higher detail (app-zoom-v1). The result is a new image observation + /// with its own screenshot_id; image_xy on it maps into that rectangle. + async fn zoom_observation( + &self, + _app: AppSelector, + _region: ComputerUseZoomRegion, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "[ZOOM_UNSUPPORTED] This host does not advertise app-zoom-v1; observe the full window instead", + )) + } + /// Foreground-only recovery of a selected window that has no live surface: + /// unhide its application and un-minimize the window. Returns whether a + /// window state was changed; the caller prepares the target again. + async fn restore_window(&self, _app: AppSelector) -> OpenBitFunResult { + Ok(false) + } + async fn start_control( + &self, + _owner: &str, + _request: ControlStartRequest, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "[CONTROL_UNSUPPORTED] This host has no control-session provider", + )) + } + fn control_snapshot(&self) -> ControlSnapshot { + ControlSnapshot::default() + } + async fn stop_control(&self, _owner: &str) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "[CONTROL_UNSUPPORTED] This host has no control-session provider", + )) + } + async fn stop_control_generation( + &self, + owner: &str, + generation: u64, + ) -> OpenBitFunResult { + let _ = (owner, generation); + Err(OpenBitFunError::tool( + "[CONTROL_UNSUPPORTED] Conditional stop is unavailable on this host", + )) + } + async fn acquire_control_action( + &self, + _owner: &str, + _action: &str, + ) -> OpenBitFunResult>> { + Ok(None) + } + async fn permission_snapshot(&self) -> OpenBitFunResult; + + /// Platform-specific prompt (e.g. macOS accessibility dialog). + async fn request_accessibility_permission(&self) -> OpenBitFunResult<()>; + + /// Open settings or trigger OS screen-capture permission flow where supported. + async fn request_screen_capture_permission(&self) -> OpenBitFunResult<()>; + + /// Capture the display that contains `(0,0)`. See [`ComputerUseScreenshotParams`]: point crop, optional quadrant drill, refresh, reset. + async fn screenshot_display( + &self, + params: ComputerUseScreenshotParams, + ) -> OpenBitFunResult; + + /// Full-screen capture for **UI / human verification only**. Must **not** replace + /// `last_pointer_map`, navigation focus, or `last_screenshot_refinement` (unlike [`screenshot_display`](Self::screenshot_display)). + /// Desktop overrides with a side-effect-free capture; default delegates to a plain full-frame `screenshot_display` (may still advance navigation on naive embedders — override on desktop). + async fn screenshot_peek_full_display(&self) -> OpenBitFunResult { + self.screenshot_display(ComputerUseScreenshotParams::default()) + .await + } + + /// OCR on **raw display pixels** (no pointer overlay). Desktop captures only the relevant region: + /// optional `region_native`, else on macOS the frontmost window from Accessibility, else the primary display. + /// Default returns a "not implemented" error. Desktop overrides with Vision (macOS), WinRT OCR (Windows), or Tesseract (Linux). + async fn ocr_find_text_matches( + &self, + text_query: &str, + region_native: Option, + ) -> OpenBitFunResult> { + let _ = (text_query, region_native); + Err(OpenBitFunError::tool( + "OCR text recognition is not available on this host.".to_string(), + )) + } + + /// Read all visible text from the authorized target window without a search + /// query. Coordinates refer to the captured frame's global bounds. + async fn read_screen_text(&self) -> OpenBitFunResult> { + Err(OpenBitFunError::tool( + "[OCR_READ_UNSUPPORTED] Full-frame text reading is not available on this host.", + )) + } + + /// Best-effort accessibility element at a global screen point (native hit-test). + /// Desktop uses AX (macOS) / UIA (Windows). Returns `None` when unavailable or on miss. + async fn accessibility_hit_at_global_point( + &self, + _gx: f64, + _gy: f64, + ) -> OpenBitFunResult> { + Ok(None) + } + + /// JPEG crop (no pointer overlay) around `(gx, gy)` for OCR candidate previews. + async fn ocr_preview_crop_jpeg( + &self, + _gx: f64, + _gy: f64, + _half_extent_native: u32, + ) -> OpenBitFunResult> { + Err(OpenBitFunError::tool( + "OCR preview crops are not available on this host.".to_string(), + )) + } + + /// Map `(x, y)` from the **last** screenshot's image pixel grid to global pointer pixels. + /// Fails if no screenshot was taken in this process since startup (or since last host reset). + fn map_image_coords_to_pointer(&self, x: i32, y: i32) -> OpenBitFunResult<(i32, i32)>; + + /// Same as `map_image_coords_to_pointer` but **sub-point** precision (macOS: use for the `mouse_move` action). + fn map_image_coords_to_pointer_f64(&self, x: i32, y: i32) -> OpenBitFunResult<(f64, f64)> { + let (a, b) = self.map_image_coords_to_pointer(x, y)?; + Ok((a as f64, b as f64)) + } + + /// Map `(x, y)` with each axis in `0..=1000` to the captured display in native pointer pixels. + /// `(0,0)` ≈ top-left of capture, `(1000,1000)` ≈ bottom-right (inclusive mapping). + fn map_normalized_coords_to_pointer(&self, x: i32, y: i32) -> OpenBitFunResult<(i32, i32)>; + + fn map_normalized_coords_to_pointer_f64(&self, x: i32, y: i32) -> OpenBitFunResult<(f64, f64)> { + let (a, b) = self.map_normalized_coords_to_pointer(x, y)?; + Ok((a as f64, b as f64)) + } + + /// Absolute move in host global display coordinates (on macOS: CG space, **double** precision). + async fn mouse_move_global_f64(&self, gx: f64, gy: f64) -> OpenBitFunResult<()> { + self.mouse_move(gx.round() as i32, gy.round() as i32).await + } + + async fn mouse_move(&self, x: i32, y: i32) -> OpenBitFunResult<()>; + + /// Move the pointer by `(dx, dy)` in **global screen pixels** (same space as absolute `mouse_move` globals). + async fn pointer_move_relative(&self, dx: i32, dy: i32) -> OpenBitFunResult<()>; + + /// Click at the **current** pointer position only (does not move). Use `mouse_move` / `move_to_text` / `pointer_move_rel` first. + /// `button`: "left" | "right" | "middle" + /// On desktop, enforces the vision fine-screenshot guard (unlike [`mouse_click_authoritative`](Self::mouse_click_authoritative)). + async fn mouse_click(&self, button: &str) -> OpenBitFunResult<()>; + + /// Click at the current pointer after the host has moved it to a **trusted** target (`click_element`, `move_to_text`). + /// Skips the vision fine-screenshot / stale-pointer guard that [`mouse_click`](Self::mouse_click) applies after a pointer move. + /// Default: delegates to [`mouse_click`](Self::mouse_click). + async fn mouse_click_authoritative(&self, button: &str) -> OpenBitFunResult<()> { + self.mouse_click(button).await + } + + /// Press a mouse button and hold it at the current pointer position. + /// `button`: "left" | "right" | "middle" + async fn mouse_down(&self, _button: &str) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "mouse_down is not supported on this host.".to_string(), + )) + } + + /// Release a mouse button at the current pointer position. + /// `button`: "left" | "right" | "middle" + async fn mouse_up(&self, _button: &str) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "mouse_up is not supported on this host.".to_string(), + )) + } + + /// Press-drag-release gesture from `from` to `to` in **global screen + /// coordinates** with the given `button` over `duration_ms`. + /// + /// Default implementation composes the foreground `mouse_move_global_f64` / + /// `mouse_down` / `mouse_up` primitives (visible cursor movement). Hosts + /// that can drag without moving the user's cursor (e.g. the desktop host's + /// background `PostMessage` / CGEvent paths) override this. + async fn drag( + &self, + from: (f64, f64), + to: (f64, f64), + button: &str, + duration_ms: u64, + ) -> OpenBitFunResult<()> { + self.mouse_move_global_f64(from.0, from.1).await?; + self.mouse_down(button).await?; + let half = (duration_ms / 2).min(2_000); + if half > 0 { + self.wait_ms(half).await?; + } + self.mouse_move_global_f64(to.0, to.1).await?; + if half > 0 { + self.wait_ms(half).await?; + } + self.mouse_up(button).await + } + + async fn scroll(&self, delta_x: i32, delta_y: i32) -> OpenBitFunResult<()>; + + /// Press key combination; names like "command", "control", "shift", "alt", "return", "tab", "escape", "space", or single letters. + async fn key_chord(&self, keys: Vec) -> OpenBitFunResult<()>; + + /// Type Unicode text (synthesized key events; may be imperfect for some IMEs). + async fn type_text(&self, text: &str) -> OpenBitFunResult<()>; + + async fn wait_ms(&self, ms: u64) -> OpenBitFunResult<()>; + + /// Current frontmost app and global pointer position for tool-result JSON (`computer_use_context`). + /// Default: empty. Desktop overrides with platform queries (typically after each tool action). + async fn computer_use_session_snapshot(&self) -> ComputerUseSessionSnapshot { + ComputerUseSessionSnapshot::default() + } + + /// After a successful `screenshot_display`, the model may `mouse_click` (until the pointer moves again). + fn computer_use_after_screenshot(&self) {} + + /// After `mouse_move` / `pointer_move_rel` pointer moves: the next `mouse_click` must be preceded by a new screenshot. + fn computer_use_after_pointer_mutation(&self) {} + + /// After `mouse_click`, require a fresh screenshot before the next click (unless pointer moved, which also invalidates). + fn computer_use_after_click(&self) {} + + /// After a committed UI action that should be **visually confirmed** on the next `screenshot` + /// (Cowork-style: observe → act → verify). Desktop sets a pending flag; cleared when `screenshot_display` runs. + fn computer_use_after_committed_ui_action(&self) {} + + /// Record what the most recent action *was* (Click, Scroll, KeyChord …) + /// so the next `interaction_state.last_mutation` reports it. Hosts that + /// don't track this can leave the default no-op. + fn computer_use_record_mutation(&self, _kind: ComputerUseLastMutationKind) {} + + /// After `move_to_text` positioned the pointer with **trusted global OCR coordinates** (not JPEG guesses), + /// clear the stale-capture guard so the next **`click`** or Enter **`key_chord`** may proceed without another `screenshot`. + fn computer_use_trust_pointer_after_ocr_move(&self) {} + + /// After `type_text`: the pointer did not move; clear the stale-capture guard so Enter **`key_chord`** + /// is not blocked solely because of a prior click / scroll. + fn computer_use_trust_pointer_after_text_input(&self) {} + + /// Clear the stale-capture guard because it **cannot be satisfied** on this + /// run, not because the pointer became trustworthy. + /// + /// The guard exists to force a fresh look before a committing action. That + /// only means something for a model that can look. When the primary model + /// is text-only, `screenshot` returns no image and never reaches + /// `transition_after_screenshot`, so the guard latches on forever: the + /// error says "call `screenshot` first", the model calls `screenshot`, + /// nothing changes, and every `click` / Enter `key_chord` is refused for the + /// rest of the session. Text-only observation (`describe_screen`) is the + /// real equivalent of a capture there, so it waives the guard instead. + fn computer_use_waive_fresh_capture_guard(&self) {} + + /// Refuse `mouse_click` if the pointer moved (or a click happened) since the last screenshot, + /// or if the latest capture is not a valid “fine” basis (desktop: ~500×500 point crop **or** + /// quadrant navigation region with longest side < [`COMPUTER_USE_QUADRANT_CLICK_READY_MAX_LONG_EDGE`]). + fn computer_use_guard_click_allowed(&self) -> OpenBitFunResult<()> { + Ok(()) + } + + /// Relaxed click guard for AX-based `click_element`: skips the fine-screenshot requirement. + /// AX coordinates are authoritative, so no quadrant drill or point crop is needed. + fn computer_use_guard_click_allowed_relaxed(&self) -> OpenBitFunResult<()> { + Ok(()) + } + + /// What the **last** `screenshot_display` captured (e.g. coordinate hints for the model). + /// Default: unknown (`None`). Desktop sets after each `screenshot_display`. + fn last_screenshot_refinement(&self) -> Option { + None + } + + /// Derive structured interaction readiness and guidance from the current session state. + /// Default: empty/default state. Desktop overrides with state-driven implementation. + fn computer_use_interaction_state(&self) -> ComputerUseInteractionState { + ComputerUseInteractionState::default() + } + + /// Search the frontmost app’s accessibility tree (macOS AX) for a matching control and return a stable center. + /// Default: unsupported outside the desktop host / non-macOS. + async fn locate_ui_element_screen_center( + &self, + _query: UiElementLocateQuery, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "Native UI element (accessibility) lookup is not available on this host.".to_string(), + )) + } + + /// Enumerate the condensed UI tree text representation for the screenshot context. + /// Default: no UI tree text. + async fn enumerate_ui_tree_text(&self) -> Option { + None + } + + /// Record a completed action for loop detection and history tracking. + /// Default: no-op. Desktop host overrides with optimizer integration. + fn record_action(&self, _action_type: &str, _action_params: &str, _success: bool) {} + + /// Update the screenshot hash for visual change detection. + /// Default: no-op. Desktop host overrides with optimizer integration. + fn update_screenshot_hash(&self, _hash: u64) {} + + /// Check if the agent is stuck in a repeating action loop. + /// Returns a detection result with suggestions if a loop is found. + /// Default: no loop detected. + fn detect_action_loop(&self) -> LoopDetectionResult { + LoopDetectionResult { + is_loop: false, + pattern_length: 0, + repetitions: 0, + suggestion: String::new(), + } + } + + /// Get action history for context and backtracking. + /// Default: empty history. + fn get_action_history(&self) -> Vec { + vec![] + } + + /// Launch a macOS/Windows/Linux application by name and return its PID. + /// Default: unsupported. Desktop host overrides with platform-specific implementation. + async fn open_app(&self, _app_name: &str) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "open_app is not available on this host.".to_string(), + )) + } + + /// Enumerate all physical displays attached to the host. The returned + /// list is what the model sees in `interaction_state.displays` and what + /// `ControlHub` exposes via `desktop.list_displays`. + /// + /// Default: empty (non-desktop hosts can't enumerate displays). + async fn list_displays(&self) -> OpenBitFunResult> { + Ok(vec![]) + } + + /// Pin subsequent screenshots / clicks / locates to the display with + /// `display_id`. Pass `None` to clear the preference and fall back to + /// "screen under the pointer". Hosts that don't track a preferred + /// display can leave the default no-op. + /// + /// This is the explicit fix for the original bug — instead of guessing + /// the target display from the cursor (which is wrong whenever the user + /// has the keyboard focus on a different screen), the model can + /// announce "I am working on display N" and the host will commit to it. + async fn focus_display(&self, _display_id: Option) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "focus_display is not available on this host.".to_string(), + )) + } + + /// Currently pinned display id, if any. Surfaced to the model via + /// `interaction_state.active_display_id`. + fn focused_display_id(&self) -> Option { + None + } + + // ------------------------------------------------------------------- + // Codex-style AX-first desktop API (Phase 1: trait surface only). + // + // All methods default to `not available` so existing platform hosts + // (macOS/Linux/Windows desktop, headless test hosts) continue to + // compile and behave exactly as before. Concrete implementations are + // landed in subsequent phases (macos_ax_dump, desktop_host PID-events, + // linux/windows AT-SPI/UIA, ControlHub dispatch). + // ------------------------------------------------------------------- + + /// Whether this host can dispatch synthetic input events to a target + /// application **without** stealing the user's foreground focus or + /// moving their physical cursor. macOS desktop will set this to true + /// once the `CGEventPostToPid` + private-source path is wired and the + /// startup self-check passes; non-macOS hosts stay `false` for now. + fn supports_background_input(&self) -> bool { + false + } + + /// Whether this host can dump a structured accessibility tree per + /// running application (Codex-style `` payload). macOS uses + /// AX, Linux uses AT-SPI2, Windows uses UIA. Hosts without an AX + /// backend stay `false` so the model falls back to the screenshot path. + fn supports_ax_tree(&self) -> bool { + false + } + + /// Enumerate running applications, sorted by recency / launch count + /// (Codex's `list_apps`). Default: empty list — callers should treat an + /// empty result as "not available on this host". + async fn list_apps(&self, _include_hidden: bool) -> OpenBitFunResult> { + Ok(vec![]) + } + + /// Native window inventory. Omit `app` to discover windows across process + /// boundaries; explicit selectors filter the inventory without binding it. + async fn list_windows( + &self, + _app: Option, + ) -> OpenBitFunResult> { + Err(OpenBitFunError::tool( + "[WINDOW_DISCOVERY_UNSUPPORTED] This host cannot enumerate native windows; use list_apps and supported app observations", + )) + } + + /// Dump the accessibility tree of a target application, returning a + /// stable [`AppStateSnapshot`] (Codex's `get_app_state`). Default: + /// unsupported. Implementations cache `idx → element` so + /// [`Self::app_click`] etc. can address nodes by index. + async fn get_app_state( + &self, + _app: AppSelector, + _max_depth: u32, + _focus_window_only: bool, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "get_app_state is not available on this host.".to_string(), + )) + } + + /// Select whether an observation needs pixels. Older providers keep their + /// existing capture behavior, then omit the image from the result. Native + /// providers can override this to avoid capture and encoding altogether. + /// Omitting the tool option retains the original image-bearing observation. + async fn get_app_state_with_options( + &self, + app: AppSelector, + max_depth: u32, + focus_window_only: bool, + include_image: bool, + ) -> OpenBitFunResult { + let mut snapshot = self + .get_app_state(app, max_depth, focus_window_only) + .await?; + if !include_image { + snapshot.screenshot = None; + } + Ok(snapshot) + } + + /// Whether this host can enumerate a target application's menu-bar + /// keyboard shortcuts (Codex-adjacent `get_app_shortcuts`). This is the + /// **read** counterpart to [`Self::key_chord`] / [`Self::app_key_chord`] + /// (which only **send** keys): macOS reads `AXMenuBar` / + /// `AXMenuItemCmd*`, Windows reads the UIA menu tree's + /// `AcceleratorKey` property. Hosts without a menu-introspection + /// backend stay `false`. + fn supports_app_shortcuts(&self) -> bool { + false + } + + /// Enumerate the keyboard shortcuts registered in a target + /// application's menu bar. Unlike [`Self::get_app_state`], this does + /// **not** require the app to be frontmost on macOS (menu structure is + /// queryable from any running app's AX element); on Windows it + /// resolves a top-level window owned by the target app. Default: + /// unsupported. + async fn get_app_shortcuts(&self, _app: AppSelector) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "get_app_shortcuts is not available on this host.".to_string(), + )) + } + + /// Click inside a target application. When [`ClickTarget::NodeIdx`] is + /// used, the host first tries the AX action path + /// (`AXUIElementPerformAction`) and falls back to a PID-scoped + /// synthetic mouse event. Returns the after-state snapshot so the + /// model can verify the change in a single round-trip. + /// Submit one app input without taking an observation. Batch orchestration + /// observes once after the sequence; unsupported older providers fail explicitly. + async fn dispatch_app_input( + &self, + _app: AppSelector, + _action: AppInputAction, + ) -> OpenBitFunResult<()> { + Err(OpenBitFunError::tool( + "[APP_INPUT_UNSUPPORTED] This provider does not expose observation-free app input", + )) + } + + /// Wait, without sending input, until the app's bound window stops + /// repainting after submitted input, within `policy`. Providers without a + /// live frame stream report `Unavailable`; the caller still observes. + async fn settle_after_input( + &self, + _app: AppSelector, + _policy: AppInputSettlePolicy, + ) -> OpenBitFunResult { + Ok(AppInputSettle::unavailable( + "This provider cannot measure window repaint after input", + )) + } + + /// Poll an application's AX tree until `pred` matches or `timeout_ms` + /// elapses. Returns the matching snapshot. Default: unsupported. + async fn app_wait_for( + &self, + _app: AppSelector, + _pred: AppWaitPredicate, + _timeout_ms: u32, + _poll_ms: u32, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "app_wait_for is not available on this host.".to_string(), + )) + } + + // ------------------------------------------------------------------- + // Interactive-View (Set-of-Mark) API — TuriX-CUA inspired. + // + // Goal: collapse the model's "where do I click?" decision into a single + // numeric index `i` that is rendered as a coloured numbered box on top + // of a focused-window screenshot. The model picks `i`, the host + // resolves it back to an authoritative AX action — no coordinate + // guessing, no JPEG-pixel arithmetic. + // + // Defaults are `not available` so non-desktop / non-AX hosts continue + // to compile and behave exactly as before. + // ------------------------------------------------------------------- + + /// Whether this host can build a Set-of-Mark interactive view (filtered + /// AX elements + numbered overlay screenshot). Hosts without an AX + /// backend stay `false`. + fn supports_interactive_view(&self) -> bool { + false + } + + /// Build a Set-of-Mark view for the given application: filters the AX + /// tree to interactive elements, assigns a dense `i` index per element, + /// and overlays numbered colour-coded boxes on the focused-window + /// screenshot. The returned [`InteractiveView`] is the **default** input + /// surface the model should use for desktop GUI work. + async fn build_interactive_view( + &self, + _app: AppSelector, + _opts: InteractiveViewOpts, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "build_interactive_view is not available on this host.".to_string(), + )) + } + + /// Click an element by its [`InteractiveElement::i`] index from the most + /// recent [`InteractiveView`] of the same application. Returns the + /// after-state view (re-built post-action) when `return_view=true`, else + /// just the bare [`AppStateSnapshot`] for cheaper polling. + async fn interactive_click( + &self, + _app: AppSelector, + _params: InteractiveClickParams, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "interactive_click is not available on this host.".to_string(), + )) + } + + /// Type text into an element by its `i` index (focuses first via AX, + /// then dispatches PID-scoped key events / paste). When `i` is `None`, + /// types into the currently focused element. + async fn interactive_type_text( + &self, + _app: AppSelector, + _params: InteractiveTypeTextParams, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "interactive_type_text is not available on this host.".to_string(), + )) + } + + /// Scroll inside (or over) an element by its `i` index. Pass `i=None` + /// to scroll over the focused window. + async fn interactive_scroll( + &self, + _app: AppSelector, + _params: InteractiveScrollParams, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "interactive_scroll is not available on this host.".to_string(), + )) + } + + /// Whether this host can build a generic visual mark view for arbitrary + /// non-AX/non-OCR surfaces. Unlike [`Self::build_interactive_view`], this + /// does not require accessibility nodes; it marks candidate points in the + /// screenshot itself. + fn supports_visual_mark_view(&self) -> bool { + false + } + + async fn build_visual_mark_view( + &self, + _app: AppSelector, + _opts: VisualMarkViewOpts, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "build_visual_mark_view is not available on this host.".to_string(), + )) + } + + async fn visual_click( + &self, + _app: AppSelector, + _params: VisualClickParams, + ) -> OpenBitFunResult { + Err(OpenBitFunError::tool( + "visual_click is not available on this host.".to_string(), + )) + } +} + +pub type ComputerUseHostRef = std::sync::Arc; + +/// Errors retain the legacy host boundary's category and display text. +pub mod error { + #[derive(Debug, Clone, PartialEq, Eq)] + pub enum ComputerUseError { + Tool(String), + Service(String), + } + impl ComputerUseError { + pub fn tool(message: impl Into) -> Self { + Self::Tool(message.into()) + } + pub fn service(message: impl Into) -> Self { + Self::Service(message.into()) + } + } + impl std::fmt::Display for ComputerUseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Tool(message) => write!(f, "Tool error: {message}"), + Self::Service(message) => write!(f, "Service error: {message}"), + } + } + } + impl std::error::Error for ComputerUseError {} + impl From for ComputerUseError { + fn from(error: crate::computer_use::ComputerUseContractError) -> Self { + Self::Tool(error.to_string()) + } + } + impl From for ComputerUseError { + fn from(message: String) -> Self { + Self::Service(message) + } + } + impl From for String { + fn from(error: ComputerUseError) -> Self { + error.to_string() + } + } + // Preserve implementation spelling while removing the upward Core dependency. + pub type OpenBitFunError = ComputerUseError; + pub type OpenBitFunResult = Result; +} diff --git a/src/crates/execution/tool-contracts/src/lib.rs b/src/crates/execution/tool-contracts/src/lib.rs index 34b127be22..3ccd092d94 100644 --- a/src/crates/execution/tool-contracts/src/lib.rs +++ b/src/crates/execution/tool-contracts/src/lib.rs @@ -143,3 +143,6 @@ pub use tool_snapshot::{ ToolCancellationContract, ToolEffectFacts, ToolEffectFactsSource, ToolEffectFilter, ToolProviderIdentity, ToolSnapshotCallError, ToolSnapshotItem, }; + +#[cfg(feature = "computer-use-contract")] +pub mod computer_use_host; diff --git a/src/crates/execution/tool-execution/Cargo.toml b/src/crates/execution/tool-execution/Cargo.toml index afcde39daf..11004b4009 100644 --- a/src/crates/execution/tool-execution/Cargo.toml +++ b/src/crates/execution/tool-execution/Cargo.toml @@ -11,7 +11,7 @@ web-readable = ["dep:htmd", "dep:legible", "dep:readability-js"] [dependencies] anydoc = { workspace = true, optional = true } -openbitfun-agent-tools = { path = "../tool-contracts" } +openbitfun-agent-tools = { path = "../tool-contracts", features = ["computer-use-contract"] } openbitfun-core-types = { path = "../../contracts/core-types" } openbitfun-events = { path = "../../contracts/events" } openbitfun-runtime-ports = { path = "../../contracts/runtime-ports", features = ["workspace-ports"] } @@ -30,7 +30,7 @@ roxmltree = { workspace = true, features = ["std", "positions"], optional = true serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true, optional = true } -tokio = { workspace = true, features = ["io-util", "rt", "sync", "time"] } +tokio = { workspace = true, features = ["io-util", "macros", "rt", "sync", "time"] } tokio-util = { workspace = true, features = ["io-util"] } vte = { workspace = true, features = ["ansi"] } zip = { workspace = true, optional = true } diff --git a/src/crates/execution/tool-execution/src/computer_use.rs b/src/crates/execution/tool-execution/src/computer_use.rs index bda7693758..9eff642b61 100644 --- a/src/crates/execution/tool-execution/src/computer_use.rs +++ b/src/crates/execution/tool-execution/src/computer_use.rs @@ -8,24 +8,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// Maximum actions to track in history const MAX_HISTORY_SIZE: usize = 50; -/// Action record for history tracking -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ActionRecord { - pub timestamp_ms: u64, - pub action_type: String, - pub action_params: String, - pub success: bool, - pub screenshot_hash: Option, -} - -/// Loop detection result -#[derive(Debug, Clone)] -pub struct LoopDetectionResult { - pub is_loop: bool, - pub pattern_length: usize, - pub repetitions: usize, - pub suggestion: String, -} +pub use openbitfun_agent_tools::computer_use_host::{ActionRecord, LoopDetectionResult}; /// Computer Use session optimizer #[derive(Debug)] diff --git a/src/crates/services/AGENTS-CN.md b/src/crates/services/AGENTS-CN.md index bbf721940c..96d9a53f66 100644 --- a/src/crates/services/AGENTS-CN.md +++ b/src/crates/services/AGENTS-CN.md @@ -8,6 +8,7 @@ | Crate | 职责 | 本地文档 | |---|---|---| +| `computer-use` | Desktop 与 CLI 共用的原生截图、无障碍、输入、权限和控制会话服务 | [AGENTS.md](computer-use/AGENTS.md) | | `services-core` | 不包含产品组装决策的本地 service primitive,包括 session storage、metadata store CRUD/index rebuild、metadata 构造/计数/索引/字段 mutation、lineage 规则和 JSON file IO | [AGENTS.md](services-core/AGENTS.md) | | `services-integrations` | MCP、git、remote、file watch、MiniApp runtime、产品领域 port 具体实现,以及平台无关的 Remote Connect primitives | [AGENTS.md](services-integrations/AGENTS.md) | | `legacy-migration` | 离线旧产品发现、加锁、一致性 SQLite 快照、暂存、journal 恢复和 owner adapter 编排 | — | diff --git a/src/crates/services/AGENTS.md b/src/crates/services/AGENTS.md index cf1f85a738..7c90d6227f 100644 --- a/src/crates/services/AGENTS.md +++ b/src/crates/services/AGENTS.md @@ -11,6 +11,7 @@ OS/network capabilities. | Crate | Responsibility | Local doc | |---|---|---| +| `computer-use` | Native screenshot, accessibility, input, permission and control-session providers shared by Desktop and CLI | [AGENTS.md](computer-use/AGENTS.md) | | `services-core` | Reusable local service primitives, process-wide TLS provider selection, managed process-tree lifecycle, filesystem helpers, session storage layout/indexing/deletion, metadata store CRUD/index rebuild, metadata construction/counter/index/field mutation/lineage rules, and JSON file IO without product assembly decisions | [AGENTS.md](services-core/AGENTS.md) | | `services-integrations` | Concrete MCP, git, remote, file-watch, MiniApp runtime, review-platform provider service, product-domain port implementations, and platform-neutral Remote Connect primitives | [AGENTS.md](services-integrations/AGENTS.md) | | `legacy-migration-adapters` | Offline legacy-data converters against shared configuration/storage owners, without Core | [AGENTS.md](legacy-migration-adapters/AGENTS.md) | diff --git a/src/crates/services/computer-use/AGENTS.md b/src/crates/services/computer-use/AGENTS.md new file mode 100644 index 0000000000..da5eb88ebf --- /dev/null +++ b/src/crates/services/computer-use/AGENTS.md @@ -0,0 +1,389 @@ +# Native Computer Use service + +## Scope + +Platform-specific automation for the unified `computer_use` tool lives under +`src/crates/services/computer-use/src/computer_use/`. Shared contracts and tool orchestration +are in `src/crates/assembly/core` and `src/crates/execution/tool-contracts`. + +Desktop and CLI inject the same `NativeComputerUseHost` through the portable +`ComputerUseHost` contract in `openbitfun-agent-tools`. Keep configuration, +product capability selection and tool orchestration outside this crate; never +import Core, Tauri or the CLI. Desktop's old module is only a compatibility +facade and its full Tool fixtures remain there. + +`host_runtime` owns CLI graphical-session admission and the macOS main run loop. +It must not request OS permissions, activate an application or begin capture at +startup. Host exit stops native resources before the main loop goes away. +Both executable build scripts must weak-link ScreenCaptureKit: Cargo does not +propagate a library build script's `rustc-link-arg` to dependent executables. + +Linux capture/OCR use a small C adapter compiled against GStreamer/Tesseract +headers and loaded with `dlopen` only at use. Missing libraries must leave normal +CLI startup usable, with explicit capture/OCR errors. Keep all function and +layout definitions checked against vendor headers; no hand-written ABI guesses. +X11 monitor discovery and Enigo use x11rb without mandatory Xlib/libxdo linkage. + +## Platform maturity + +| Platform | Tier | Capabilities | +|---|---|---| +| **macOS** | AX-first | Accessibility tree, directed background input, persistent ScreenCaptureKit window capture, menu shortcuts, interactive/visual views | +| **Windows** | AX-first | UI Automation patterns/tree, persistent WGC window capture, MSAA observation for legacy VCL, targeted message input | +| **Linux** | Portal + AT-SPI | Consented PipeWire capture, foreground portal input, background semantic activation and EditableText, AT-SPI application trees | + +### Ubuntu / Linux control + +Wayland capture and seat input use one xdg-desktop-portal session. Never use an +XWayland `DISPLAY` as evidence that X11 desktop input is supported. Portal denial, +revocation, missing plugins, and stream geometry changes fail explicitly; they +must not trigger X11 input or whole-desktop capture fallback. GStreamer consumes +the portal's authorized PipeWire FD, not a default unrestricted connection. + +AT-SPI provides `list_apps`, `get_app_state`, `app_click` with a cached `NodeIdx`, +and `app_type_text` with an explicit EditableText node. These semantic operations +do not change compositor focus. Arbitrary background coordinates, app-scoped key +chords, interactive/visual cached views, and menu shortcuts are unavailable. +Portal-selected pixels are not automatically attached to a PID-selected tree. + +Run the real native portal fixture in the desktop user's Ubuntu session (requires +`python3-gi`, GTK 3, GStreamer PipeWire/base/good plugins and portal services): + +```bash +cargo check --locked -p openbitfun-computer-use --tests +node scripts/test-linux-computer-use-native.mjs -- --test-threads=1 +bash scripts/test-linux-computer-use-atspi.sh +bash scripts/test-linux-computer-use-portal.sh +``` + +Select only the dedicated **OpenBitFun Portal Fixture** window. The fixture checks +real PipeWire frames, observation-only input rejection and stop revocation. It +does not prove foreground input delivery or remote behavior. +For headless AT-SPI verification, use +`dbus-run-session -- xvfb-run -a bash -lc 'export NO_AT_BRIDGE=0; bash scripts/test-linux-computer-use-atspi.sh'`. +The AT-SPI fixture checks one GTK button activation and UTF-8 EditableText insertion +while preserving existing text; +it does not establish compatibility with every application. Run the SPEC's +remaining native acceptance scenarios separately. + +## Module map + +- `desktop_host/` — `ComputerUseHost` trait impl; entry for all actions +- `control_session/admission.rs` — pure mode/owner/lease/start/stop state machine +- `control_session/sharing.rs`, `desktop_host/sharing.rs` — user-selected window, observe-first sharing and revocable input grant +- `permissions.rs`, `process_identity.rs`, `grants.rs`, `share_grants.rs` — explicit OS requests and executable-bound remembered preferences +- `desktop_host/shared_preview.rs` — scoped manual preview input through the same native host/lease as the Agent +- `desktop_host/background_guard.rs` — before/after desktop witnesses; no focus restoration or replay +- `desktop_host/foreground.rs` — explicit exact-window activation and global input destination checks +- `desktop_host/linux_launch.rs` — literal executable/desktop-entry launch with bounded helper waits +- `desktop_host/observation.rs`, `observation_cache.rs` — observation identity and bounded screenshot geometry; never input authority +- `desktop_host/state.rs` — derived host feedback and view caches +- `macos_*` / `windows_*` — platform AX, capture, list-apps, shortcuts +- `macos_ax_dispatch` — per-element AX thread routing and native exception boundary +- `windows_capture.rs` — WGC frame conversion and authoritative window bounds +- `windows_wgc_capture.rs` — Windows.Graphics.Capture (Direct3D11) +- `windows_window_target.rs` — Win32 window facts and portable default-target policy +- `linux_ax_ui.rs` — AT-SPI locate +- `linux_control.rs` — portal lifetime, PipeWire frame consumption, foreground seat input +- `linux_control_ax.rs` — AT-SPI background semantic operations +- `linux_control_policy.rs` — pure session classification and keysym encoding +- `screen_ocr.rs`, `ui_locate_common.rs` — shared OCR/locate helpers + +## Native capture boundaries + +The implementation contract is [Computer Use control-session SPEC](../../../../docs/architecture/computer-use-control.md). +macOS and Windows retain a real native single-window capture session. Never fall +back to desktop pixels when window capture fails or the target is obscured. +Background input must not activate a window or use the global input seat. +For an ordinary user-requested GUI task, the Agent may explicitly change to +foreground mode when background delivery is unsupported or verified ineffective, +unless the user required background-only/no-disruption. This is a new tool +decision, never a native retry or implicit escalation. macOS/Windows +`activate-app-v1` activates the exact bound window and returns a fresh observation; +global input must validate the foreground destination. Linux retains its separate +portal consent/surface identity. Preserve user Stop, cancellation and OS denial. + +Surface errors name the state the host established (minimized, hidden, cloaked, +off-Space, display affinity) for the exact window; keep the codes stable and +the wording free of recovery advice, which the tool adds per mode. A bound +stream that loses its surface reports that state too, never "closed": macOS +per-window `CGWindowList` queries omit minimized and other-Space windows, so a +window counts as closed only when the full list lacks it, and Windows checks +the bound HWND's surface state before reusing its stream. Native status reports +a lost surface as status 2 without querying Accessibility; describe it with +`obf_capture_describe_surface` only after releasing `CAPTURE`, so Stop never +waits on the target. Target validation and stream start hold `CAPTURE` by +design. +`restore_window` (unhide, un-minimize) runs only for foreground `activate_app`, +requires `foreground_allowed` and `target_admissible`, and restores the window +the surface error named: the requested or bound one, else the window capture +selects for the process (Windows: its first minimized window). An unreadable +minimized state is a restore failure, never "nothing to restore". On macOS +activation sets the capture input barrier so the next observation is a +post-activation frame. +`app-zoom-v1` re-captures the bound window only: macOS 14+ uses a one-shot +desktop-independent window filter at backing scale, older macOS and Windows +crop the live frame. Zoomed pointer maps are marked zoomed and keep their +window offset and size; never re-anchor them on raw region bounds, infer zoom +from region size, or let a zoom read pixels outside the bound window. Only +inputs that can name a screenshot_id require one after a zoom. + +## Target-local macOS focus acceptance + +AX walks and cached-node operations run on a blocking worker. Route each native +message by the element's serving PID through `macos_ax_dispatch`: same-process +AppKit callbacks require main, while WebKit subprocess messages need main free +to answer synchronous IPC, including AX client authentication. Never dispatch an +entire walk based on its root PID; a single tree spans both processes. +`AXUIElementGetPid` reports the presenter for WebKit descendants; thread routing +uses dynamically resolved `_AXUIElementGetActualPid`. Keep the presenter PID for +target/permission validation. If the serving-PID SPI is unavailable, report an +explicit unsupported state instead of guessing a thread. Keep the +control token across same-process dispatch and catch Objective-C exceptions on +the executing thread. Recheck input authority there before actions or user +attribute writes, because Stop may revoke a queued message. Observation-only +AX enablement does not acquire input authority. Enigo / HIToolbox input retains +its main-thread wrapper. + +Cross-process AX proxies can advertise a writable `AXSelectedText` whose setter +does nothing (WebKit). Select the existing directed-keyboard route before +submission for these proxies; native controls retain AX insertion at the current +selection. Never retry a submitted text write based only on unchanged AX state. + +The directed-input route can change a target application's internal +focus without changing the human foreground application. Its window-addressed +focus pair at local `(-8,-8)` must remain outside content; the requested gesture +must reach content exactly once with unchanged modifiers. Do not validate it +using a fixture that overrides `acceptsFirstMouse`. Record dequeued mouse events +so standard controls' tracking loops cannot hide a delivered mouse-up. Record observer active/key, +frontmost PID, stacking order, real text destination and content event counts. +Do not use missing AX key-state attributes as a substitute for native focus +validation: fixtures inspect their own `NSWindow.keyWindow`. Preparation caches +must include generation, PID, window ID, human foreground identity and activation +epoch plus a passive target-local loss epoch, and must not add app-name rules or +content-coordinate guesses. Target-local event monitoring must be listen-only; +unavailable monitoring disables cache reuse, not background input. An off-frame routing +position is distinct from the actual user-requested content target. +No after-action raise/restore is allowed. Stop may deactivate a target only when +it is not the user's actual foreground application. Prototype success is not +production acceptance; the complete native Tool pipeline must pass separately. +Mouse events use CombinedSessionState and explicit requested flags; keyboard +events retain a private source. Preserve field 58 as window-routing metadata, +not a click-group counter. Cleanup validates process-serial identity before +target deactivation; it does not require the original window to remain open. + +## Verification + +```bash +cargo test --locked -p openbitfun-computer-use --lib +cargo test --locked -p openbitfun-computer-use --lib native_generated_stream_captures_and_stops -- --ignored +node scripts/test-windows-computer-use-native.mjs --check --target x86_64-pc-windows-msvc +``` + +The generated-stream test requires Linux GStreamer base/good plugins, uses no +user screen or portal, and verifies the real optional C adapter. Windows +`--check` uses the entire production Rust library and its declared dependencies, +but omits native C compilation/linking; it is not a Windows execution test. + + +For observation payloads, OCR projection, AX filtering/digests, and browser +snapshot context, use the isolated compiler harness first. It compiles the +production Rust files by path, with the actual DTO source and no replacement +algorithms or native-host mocks. Cargo dependencies must already be cached +(`cargo fetch --locked` on a fresh machine). + +```bash +node scripts/test-computer-use-context.mjs +cargo test -p openbitfun-computer-use --lib context_integrity_tests +``` + +Native black-box fixtures use only a dedicated test window / rendered image: + +```bash +# Node 22/24 and installed workspace dependencies; installed Chrome required. +# CHROME_PATH can select another Chromium executable. +node scripts/test-browser-snapshot.mjs --native-ocr +# macOS + Accessibility permission; creates and closes its own AppKit window. +node scripts/test-native-ax-context.mjs +# Same disposable target observed/captured/stopped by a real CLI process and Tool. +node scripts/test-native-ax-context.mjs --cli +# macOS + Screen Recording permission; captures only its own obscured test window. +node scripts/test-macos-control-capture.mjs +# Locked-host rejection only; never wakes or unlocks the desktop. +node scripts/test-macos-control-capture.mjs --locked +# macOS passive cursor lifecycle; no capture or accessibility permission required. +node scripts/test-macos-control-pointer.mjs +# Shared macOS/Windows presentation math; also runnable on Linux without a GUI. +node scripts/test-computer-use-pointer-motion.mjs +# macOS + Accessibility and Screen Recording permissions; clicks only its dedicated fixture process. +node scripts/test-macos-directed-input.mjs +# Covered standard controls: exact native AX hit + semantic action + fresh capture. +node scripts/test-macos-input-controls.mjs --semantic +# Full Tool image-coordinate button activation/text focus and wrong-field guard. +# Target/observer have distinct app bundles; AppKit initializes before the +# foreground baseline. Activation history catches transient focus changes. +# Also induces target-local loss while foreground stays fixed, then verifies +# the next ordinary input prepares focus again without another content click. +node scripts/test-macos-input-controls.mjs --orchestration +# Real AX messaging timeout in a stopped disposable process, then one directed +# click after resumption; retains exact delivery and foreground/cursor checks. +node scripts/test-macos-input-controls.mjs --busy-ax +# Explicit foreground transition on disposable windows; wrong-focus rejection, +# exact activation and native Unicode/shortcut delivery. +node scripts/test-macos-input-controls.mjs --foreground +# Identical five-input sequence: five tool calls vs one batch, with default +# images and AX-only observations. Fresh isolated app/host per case. +node scripts/test-macos-input-controls.mjs --latency +# Diagnostic raw-pointer contract, including ordinary non-AX first click and +# unchanged modifiers/z-order. Both this raw runner and the full Tool five-action +# fixture passed; do not substitute a permissive first-click implementation. +node scripts/test-macos-input-controls.mjs +# Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop. +node scripts/test-macos-control-roundtrip.mjs +# Same-process AppKit + real WebKit subtree: observe, capture, image/node clicks, +# exact text, actual DOM results, shortcuts and Stop; external deadlock watchdog. +node scripts/test-macos-computer-use-self.mjs +# Same-process popup panel over a dedicated window, once as an attached child +# window (inherits layer 0) and once at the pop-up menu level: composited pixels +# and auxiliary metadata, popup-routed press without focus preparation +# dismissing it, and an outside press reaching the bound window. +node scripts/test-macos-popup-overlay.mjs +``` + +For explicitly selected disposable real applications, the devtools JSONL probe +uses the same production Tool path and main-thread run loop. It accepts only one +startup PID (optionally one window), background observations and app actions; +it rejects activation, global input, clipboard and scripts. Do not use personal +application windows or infer delivery from `ok: true`. Observe after errors +before choosing another action; the probe never retries input automatically. + +```bash +cargo test -p openbitfun-desktop --features devtools --test computer_use_native_roundtrip --no-run --message-format=json +# Use the executable path emitted above; EOF or the total deadline stops control. +OPENBITFUN_CUA_PROBE_PID= OPENBITFUN_CUA_PROBE_OUTPUT_DIR=/tmp/cua-probe +# stdin JSONL: {"id":"observe","input":{"action":"get_app_state","include_image":true}} +cargo test -p openbitfun-desktop --features devtools --lib native_control_roundtrip::probe +# Independent read-only witness; no app launch, permission prompts or input. +clang -fobjc-arc -fblocks -Wall -Wextra -Werror -framework AppKit -framework ApplicationServices scripts/fixtures/computer-use-background-witness.m -o /tmp/cua-witness +/tmp/cua-witness --target-pid --target-window --output /tmp/cua-witness.json +``` + +Wait for the witness's baseline before input. `SIGUSR1` requests a new baseline; +wait for its sequence to advance. `SIGTERM` flushes the final record. Check +sampling gaps and unknown AX reads, and separate concurrent human activity from +backend-caused changes. The witness records IDs/coordinates, not titles, text or +pixels; it cannot independently prove key-window state or causal attribution. + +The browser fixture runs production snapshot/resolver JavaScript in Chromium, +then passes the actual DOM payload to compiled Rust presentation tests. The +optional OCR step compiles the Desktop test target and invokes macOS Vision on +the rendered JPEG. The AX fixture compiles the Desktop test target and checks +native AX nodes, text, states, parent indices, cache entries, filtering, and DTO +round trips. These are local macOS checks, not Windows/Linux or remote evidence. + +The latency fixture reports actual returned observations/images, AX node counts +and native tool wall time including one separately timed fixture JSON check. +It checks exact Unicode text, immediate shortcut delivery, +fresh AX-only node identities, recovery of default screenshot observations, +and the same foreground/cursor invariants as the orchestration fixture. It does +not invoke a model. Startup and cleanup are outside the reported measurement; +timings are diagnostic evidence, not machine-dependent pass/fail thresholds. +The native fixture requires an unlocked desktop; its read-only startup gate +reports a locked screen as inconclusive without waking or unlocking it. + +Observation invariants: + +- Rectangle containment does not prove two controls have the same action. +- Projection uses content padding and authoritative global bounds; invalid + geometry and OCR matches outside the content are not actionable coordinates. +- AX snapshot digests cover state and geometry as well as labels. A state-only + change must not be mistaken for a failed action and trigger duplicate input. +- Stale interactive/visual indices must be returned to the caller for a fresh + choice, never silently reused after rebuilding a different view. +- Element-budget omissions are reported in `omitted_element_count`, including + when text rendering is disabled; focused controls survive budget selection. + +```bash +cargo test -p openbitfun-desktop --lib computer_use +cargo build -p openbitfun-desktop +``` + +Windows-only paths (`windows_wgc_capture`, UIA) compile on CI (`windows-latest`). +The Windows job also runs the isolated native-module unit suite independently +of the Tauri test loader; interactive native delivery fixtures remain ignored. +UIA observation, semantic input, locate, hit-test and shortcut discovery share +one MTA worker. `provider_worker.rs` bounds admission and caller waits: a request +has a ten-second deadline and polls control cancellation every 50 ms. UIA also +uses two-second connection and five-second transaction limits with automatic +focus disabled. Never release the occupied slot, spawn replacement workers, or +queue another input just because a caller timed out. Foreign code may still be +running. Input that has crossed its submission fence has an unknown outcome on +failure; do not retry it or switch to a coordinate click. Stop fences input still +in preflight, while already submitted input can complete later. After the native +call returns, discard abandoned observations and require a fresh read. A provider +that never returns leaves UIA explicitly busy until it recovers or the host is +restarted; status and Stop must remain independent of that worker. + +The focused desktop `computer_use` tests include portable blocking-provider +regressions for deadlines, cancellation, late input, busy admission and recovery. +They simulate foreign-call stalls and do not establish real Windows delivery. +The isolated native-module harness compiles the production control owner, UIA, +MSAA, WGC and pointer modules. Its portable error-envelope adapter replaces no +native APIs or algorithms. Cross-compilation is type-checking, not Windows +execution; full Desktop compilation and native fixtures still belong on Windows. + +```bash +# Native Windows: unit tests; native delivery fixtures remain opt-in/ignored. +node scripts/test-windows-computer-use-native.mjs +# Other hosts with the target installed: compile production native modules only. +node scripts/test-windows-computer-use-native.mjs --check --target x86_64-pc-windows-msvc +# Interactive Windows: own-process main + topmost companion selection and real WGC pixels. +node scripts/test-windows-computer-use-native.mjs default_window_captures_main_beside_topmost_companion -- --ignored --test-threads=1 +``` + +For default Windows target selection, run +`node scripts/test-computer-use-context.mjs windows_window_target`. +The portable regression includes issue #3291's reported HWNDs, styles and bounds; +it is not evidence of WGC execution. Native default selection must prefer content +over floating utility windows without app-name rules. Explicit HWNDs and existing +bindings bypass ranking. WGC rejection reports the selected HWND and window facts; +never probe another target or substitute desktop pixels after a failure. The +interactive fixture captures only its own Win32 window; it does not establish +Tauri/WebView2 compatibility on every Windows build. + +Observation IDs and target revisions are additive wire fields. Keep accepting +legacy payloads, advertise `observation-id-v1`, and reject explicit stale IDs +before input. New observations invalidate prior AX/view indices even when the +content digest is unchanged. Do not replace namespace identity with a digest. + +Agent native fixtures must discover and address their target through production +tools without manual share selection or a separate input grant. Cover explicit +`start_control` and implicit first-action startup. Optional manual-share fixtures +exercise target inventory, observe-first capture and grants separately; they must +not hide an Agent regression by performing those UI steps in fixture setup. +Permission probes never prompt. Desktop-state witnesses record concurrent human +activity without revoking Agent control or replaying input. + +The Web preview's deterministic cursor is verified against Rust-generated +`computer-use-rust` samples retained in the repository. The reference source is +not required to build or run tests. After preview, sharing or permission UI edits: + +```bash +pnpm --dir src/web-ui run test:run src/app/components/ComputerUseControlCard.test.tsx src/app/components/computer-use src/infrastructure/api/adapters/peer-device-adapter.test.ts +``` + +These UI tests cover permission requests, stale device/grant responses, geometry, +gesture cancellation and cursor math. They do not establish native delivery or +remote end-to-end behavior. The strict macOS fixture also exercises native shared +preview capture/input and stale preview rejection after revocation. + +Native pointer presentation uses `pointer_motion.h` for both AppKit and Win32. +Keep elapsed-time spring math free of OS/input dependencies. AppKit's visibility +refresh must never snap an in-flight movement; Win32 reuses one worker/window, +coalesces only visual targets and wakes on Stop. The native click pulse follows +visual arrival without delaying input. Linux/Wayland uses the shared Web preview; +do not introduce an X11/global pointer fallback. After native-motion changes run +the portable math fixture plus the platform fixture above. The Windows +`--check` command validates types only; its native test mode links the shared C +model. Browser tests and portable math on macOS are not native Windows/Linux +or remote-session evidence. diff --git a/src/crates/services/computer-use/Cargo.toml b/src/crates/services/computer-use/Cargo.toml new file mode 100644 index 0000000000..8f8ded5b22 --- /dev/null +++ b/src/crates/services/computer-use/Cargo.toml @@ -0,0 +1,101 @@ +[package] +name = "openbitfun-computer-use" +version.workspace = true +edition.workspace = true +authors.workspace = true +description = "Native Computer Use providers shared by OpenBitFun product hosts" + +[features] +default = [] +test-support = [] + +[build-dependencies] +cc = { workspace = true } +pkg-config = { workspace = true } + +[dependencies] +openbitfun-agent-tools = { path = "../../execution/tool-contracts", features = ["computer-use-contract", "element-token"] } +openbitfun-core-types = { path = "../../contracts/core-types" } +openbitfun-services-core = { path = "../services-core", features = ["process-runtime"] } +tool-runtime = { path = "../../execution/tool-execution" } +async-trait = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } +base64 = { workspace = true } +chrono = { workspace = true } +dirs = { workspace = true } +log = { workspace = true } +sha1 = { workspace = true } +sha2 = { workspace = true } +enigo = { workspace = true } +image = { workspace = true, features = ["jpeg", "png"] } + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] } + +[target.'cfg(target_os = "macos")'.dependencies] +core-foundation = { workspace = true } +core-graphics = { workspace = true } +dispatch = { workspace = true } +foreign-types = { workspace = true } +libc = { workspace = true } +objc2 = { workspace = true, features = ["exception"] } +block2 = { workspace = true } +objc2-foundation = { workspace = true, features = ["std", "NSArray", "NSEnumerator", "NSData", "NSDictionary", "NSError", "NSGeometry", "NSNotification", "NSOperation", "NSString", "block2"] } +objc2-app-kit = { workspace = true, features = ["std", "libc", "NSAnimationContext", "NSButton", "NSControl", "NSResponder", "NSView", "NSWindow", "NSWorkspace", "NSRunningApplication"] } +objc2-vision = { workspace = true, features = ["std", "VNRecognizeTextRequest", "VNRequest", "VNObservation", "VNRequestHandler", "VNUtils", "VNTypes", "objc2-core-foundation"] } + +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = [ + "Foundation", + "Globalization", + "Graphics_Capture", + "Graphics_DirectX", + "Graphics_DirectX_Direct3D11", + "Graphics_Imaging", + "Media_Ocr", + "Storage_Streams", + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D11", + "Win32_Graphics_Dwm", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", + "Win32_Graphics_Gdi", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_LibraryLoader", + "Win32_System_SystemServices", + "Win32_System_Threading", + "Win32_System_Com", + "Win32_System_StationsAndDesktops", + "Win32_System_Com_StructuredStorage", + "Win32_System_Ole", + "Win32_System_Variant", + "Win32_System_WinRT", + "Win32_System_WinRT_Direct3D11", + "Win32_System_WinRT_Graphics", + "Win32_System_WinRT_Graphics_Capture", + "Win32_UI_Accessibility", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Shell", + "Win32_UI_Shell_PropertiesSystem", + "Win32_UI_WindowsAndMessaging", +] } +windows-core = { workspace = true } + + +[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies] +screenshots = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +enigo = { workspace = true, features = ["x11rb"] } +x11rb = { workspace = true, features = ["randr"] } +libc = { workspace = true } +atspi = { workspace = true, features = ["zbus"] } +futures = { workspace = true } + +[lints] +workspace = true diff --git a/src/crates/services/computer-use/build.rs b/src/crates/services/computer-use/build.rs new file mode 100644 index 0000000000..5cac02d015 --- /dev/null +++ b/src/crates/services/computer-use/build.rs @@ -0,0 +1,52 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") { + println!("cargo:rerun-if-changed=src/computer_use/linux_native.c"); + let mut build = cc::Build::new(); + for library in ["gstreamer-1.0", "gstreamer-app-1.0", "tesseract", "lept"] { + // Headers only: runtime libraries remain optional and are dlopened + // at the capture/OCR boundary, never when the CLI starts. + let headers = pkg_config::Config::new() + .cargo_metadata(false) + .probe(library) + .unwrap_or_else(|error| { + panic!("Missing Computer Use build headers for {library}: {error}") + }); + build.includes(headers.include_paths); + } + build + .file("src/computer_use/linux_native.c") + .std("gnu11") + .warnings(true) + .compile("computer_use_linux"); + println!("cargo:rustc-link-lib=dl"); + } + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.h"); + println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.c"); + cc::Build::new() + .file("src/computer_use/pointer_motion.c") + .std("c11") + .compile("computer_use_pointer_motion"); + } + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rerun-if-changed=src/computer_use/macos_capture.m"); + println!("cargo:rerun-if-changed=src/computer_use/pointer_motion.h"); + cc::Build::new() + .file("src/computer_use/macos_capture.m") + .flag("-fobjc-arc") + .flag("-fblocks") + .compile("computer_use_capture"); + // Older macOS installs must reach the runtime unsupported-version guard. + println!("cargo:rustc-link-arg=-Wl,-weak_framework,ScreenCaptureKit"); + for framework in [ + "CoreMedia", + "CoreVideo", + "CoreImage", + "AppKit", + "ApplicationServices", + ] { + println!("cargo:rustc-link-lib=framework={framework}"); + } + } +} diff --git a/src/apps/desktop/src/computer_use/ax_snapshot_digest.rs b/src/crates/services/computer-use/src/computer_use/ax_snapshot_digest.rs similarity index 97% rename from src/apps/desktop/src/computer_use/ax_snapshot_digest.rs rename to src/crates/services/computer-use/src/computer_use/ax_snapshot_digest.rs index 341ca149ab..95315f9e4a 100644 --- a/src/apps/desktop/src/computer_use/ax_snapshot_digest.rs +++ b/src/crates/services/computer-use/src/computer_use/ax_snapshot_digest.rs @@ -1,5 +1,5 @@ //! Canonical AX observation digest shared by the native host adapters. -use openbitfun_core::agentic::tools::computer_use_host::AxNode; +use openbitfun_agent_tools::computer_use_host::AxNode; use sha1::{Digest, Sha1}; /// Hash the complete observed payload, including enabled/focus/selection and diff --git a/src/apps/desktop/src/computer_use/control_session.rs b/src/crates/services/computer-use/src/computer_use/control_session.rs similarity index 97% rename from src/apps/desktop/src/computer_use/control_session.rs rename to src/crates/services/computer-use/src/computer_use/control_session.rs index aa1c430766..ee98938d20 100644 --- a/src/apps/desktop/src/computer_use/control_session.rs +++ b/src/crates/services/computer-use/src/computer_use/control_session.rs @@ -2,7 +2,7 @@ use openbitfun_agent_tools::computer_use_control::{ ControlClick, ControlMode, ControlPointer, ControlSnapshot, ObservationScope, }; -use openbitfun_core::agentic::tools::computer_use_host::ComputerUseActionLease; +use openbitfun_agent_tools::computer_use_host::ComputerUseActionLease; use std::cell::Cell; use std::sync::{Mutex, OnceLock}; @@ -15,9 +15,9 @@ pub(crate) use admission::ControlToken; #[cfg(target_os = "macos")] pub(crate) use sharing::shared_target_allowed; pub(crate) use sharing::{ - acquire_shared, begin_share, finish_share, grant_preference_result, request_share, - set_share_control, shared_process, + acquire_shared, begin_share, finish_share, grant_preference_result, shared_process, }; +pub use sharing::{request_share, set_share_control}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Executor { @@ -205,7 +205,7 @@ fn projected(r: &Resource) -> ControlSnapshot { } s } -pub(crate) fn snapshot() -> ControlSnapshot { +pub fn snapshot() -> ControlSnapshot { locked() .map(|r| projected(&r)) .unwrap_or_else(|e| ControlSnapshot { @@ -237,10 +237,10 @@ fn revoke(r: &mut Resource, reason: &str) -> u64 { fn finish_cleanup(r: &mut Resource, ticket: u64) { r.admission.finish_cleanup(ticket); } -pub(crate) fn stop(owner: Option<&str>, reason: &str) -> Result { +pub fn stop(owner: Option<&str>, reason: &str) -> Result { stop_checked(owner, None, reason) } -pub(crate) fn stop_checked( +pub fn stop_checked( owner: Option<&str>, generation: Option, reason: &str, @@ -449,10 +449,7 @@ pub(crate) fn record_pointer(x: f64, y: f64, click: bool) { #[cfg(target_os = "linux")] let _ = target; } -pub(crate) fn acquire( - owner: &str, - action: &str, -) -> Result, String> { +pub fn acquire(owner: &str, action: &str) -> Result, String> { let token = locked()?.admission.admit(owner, action, executor())?; Ok(Box::new(Lease { token, @@ -590,7 +587,7 @@ pub(crate) fn publish_jpeg( } } } -pub(crate) fn preview(generation: u64) -> Result, String> { +pub fn preview(generation: u64) -> Result, String> { let r = locked()?; if r.admission.snapshot.generation != generation || !active(&r) { return Err("[CONTROL_STALE] Control session changed".into()); diff --git a/src/apps/desktop/src/computer_use/control_session/admission.rs b/src/crates/services/computer-use/src/computer_use/control_session/admission.rs similarity index 100% rename from src/apps/desktop/src/computer_use/control_session/admission.rs rename to src/crates/services/computer-use/src/computer_use/control_session/admission.rs diff --git a/src/apps/desktop/src/computer_use/control_session/sharing.rs b/src/crates/services/computer-use/src/computer_use/control_session/sharing.rs similarity index 98% rename from src/apps/desktop/src/computer_use/control_session/sharing.rs rename to src/crates/services/computer-use/src/computer_use/control_session/sharing.rs index ba7ed43d62..5404579c28 100644 --- a/src/apps/desktop/src/computer_use/control_session/sharing.rs +++ b/src/crates/services/computer-use/src/computer_use/control_session/sharing.rs @@ -1,7 +1,7 @@ //! User-owned sharing transitions around the existing native resource owner. use super::*; -pub(crate) fn request_share(owner: &str, mode: ControlMode) -> Result { +pub fn request_share(owner: &str, mode: ControlMode) -> Result { { let r = locked()?; if r.admission.snapshot.owner.as_deref() != Some(owner) @@ -72,7 +72,7 @@ pub(crate) fn finish_share(generation: u64, revision: u64) -> Result OpenBitFunResult<()> { super::background_guard::run(self.dispatch_app_click_native(params)).await } @@ -390,7 +390,7 @@ impl DesktopComputerUseHost { let _ = self .settle_after_input_impl( app.clone(), - openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy::default(), + openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy::default(), ) .await; self.get_app_state(app, 32, true).await.map_err(|error| { @@ -1723,7 +1723,7 @@ mod app_wait_tests { /// noise. #[cfg(any(target_os = "macos", target_os = "windows"))] fn compute_interactive_view_digest( - elements: &[openbitfun_core::agentic::tools::computer_use_host::InteractiveElement], + elements: &[openbitfun_agent_tools::computer_use_host::InteractiveElement], ) -> String { use sha1::{Digest, Sha1}; const BUCKET: f64 = 8.0; @@ -1846,11 +1846,11 @@ fn build_regular_visual_marks( #[cfg(any(target_os = "macos", target_os = "windows"))] fn visual_marks_to_overlay_elements( marks: &[VisualMark], -) -> Vec { +) -> Vec { marks .iter() .map( - |mark| openbitfun_core::agentic::tools::computer_use_host::InteractiveElement { + |mark| openbitfun_agent_tools::computer_use_host::InteractiveElement { i: mark.i, node_idx: mark.i, role: "VisualMark".to_string(), @@ -2140,7 +2140,7 @@ fn top_regular_positions( /// error text rather than introducing a typed error enum because every /// `OpenBitFunError::tool` is already string-based throughout the host /// surface; adding a new variant would ripple through ~40 callers. -impl DesktopComputerUseHost { +impl NativeComputerUseHost { /// Return the image-pixel center `(x, y)` of the cached interactive /// element with the given `i`, when its `frame_image` is known. Used /// as a pointer-click fallback in `interactive_click` when AXPress diff --git a/src/apps/desktop/src/computer_use/desktop_host/background_guard.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/background_guard.rs similarity index 100% rename from src/apps/desktop/src/computer_use/desktop_host/background_guard.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/background_guard.rs diff --git a/src/apps/desktop/src/computer_use/desktop_host/foreground.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs similarity index 97% rename from src/apps/desktop/src/computer_use/desktop_host/foreground.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs index 45e45831bc..734830b344 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/foreground.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs @@ -1,6 +1,6 @@ //! Explicit foreground recovery. Activation never runs inside an input retry. -use super::DesktopComputerUseHost; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use super::NativeComputerUseHost; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; pub(super) fn parse_native_target(target: &str) -> Option<(i32, u64)> { let (pid, window) = target.strip_prefix("pid:")?.split_once("/window:")?; @@ -9,7 +9,7 @@ pub(super) fn parse_native_target(target: &str) -> Option<(i32, u64)> { (pid > 0 && window > 0).then_some((pid, window)) } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { pub(super) fn ensure_foreground_target() -> OpenBitFunResult<()> { crate::computer_use::control_session::foreground_allowed() .map_err(OpenBitFunError::tool)?; diff --git a/src/apps/desktop/src/computer_use/desktop_host/linux_launch.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/linux_launch.rs similarity index 92% rename from src/apps/desktop/src/computer_use/desktop_host/linux_launch.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/linux_launch.rs index 674808e994..9d920ea8d8 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/linux_launch.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/linux_launch.rs @@ -1,7 +1,7 @@ //! Linux application launch, separate from opening documents/URLs. //! A GUI process outlives its launch request; never wait for that process to exit. -use openbitfun_core::agentic::tools::computer_use_host::OpenAppResult; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::OpenAppResult; use std::process::Stdio; fn result(name: &str, pid: Option, path: &str) -> OpenAppResult { @@ -24,7 +24,7 @@ pub(super) async fn open(name: &str) -> OpenBitFunResult { )); } if !name.ends_with(".desktop") { - let mut command = openbitfun_core::util::process_manager::create_tokio_command(name); + let mut command = openbitfun_services_core::process_manager::create_tokio_command(name); command .stdin(Stdio::null()) .stdout(Stdio::null()) @@ -48,7 +48,7 @@ pub(super) async fn open(name: &str) -> OpenBitFunResult { } } let (program, args) = desktop_launcher(name); - let mut command = openbitfun_core::util::process_manager::create_tokio_command(program); + let mut command = openbitfun_services_core::process_manager::create_tokio_command(program); command .args(args) .stdin(Stdio::null()) diff --git a/src/apps/desktop/src/computer_use/desktop_host/macos.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/macos.rs similarity index 100% rename from src/apps/desktop/src/computer_use/desktop_host/macos.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/macos.rs diff --git a/src/apps/desktop/src/computer_use/desktop_host/mod.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/mod.rs similarity index 95% rename from src/apps/desktop/src/computer_use/desktop_host/mod.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/mod.rs index cabf73095b..5db21ba2bc 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/mod.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/mod.rs @@ -7,7 +7,7 @@ mod foreground; #[cfg(any(target_os = "linux", test))] mod linux_launch; mod observation; -pub(crate) mod shared_preview; +pub mod shared_preview; pub(crate) mod sharing; mod state; #[cfg(target_os = "windows")] @@ -16,10 +16,12 @@ use state::ComputerUseSessionMutableState; #[cfg(any(target_os = "macos", target_os = "windows"))] use state::{CachedInteractiveView, CachedVisualMarkView}; +use crate::computer_use::displays::Screen; use async_trait::async_trait; #[cfg(any(target_os = "macos", target_os = "windows"))] use log::debug; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ ActionRecord, AppInfo, AppSelector, AppShortcutsSnapshot, AppStateSnapshot, AppWaitPredicate, AppWindowInfo, ComputerScreenshot, ComputerUseDisplayInfo, ComputerUseHost, ComputerUseInteractionState, ComputerUseLastMutationKind, ComputerUsePermissionSnapshot, @@ -30,11 +32,9 @@ use openbitfun_core::agentic::tools::computer_use_host::{ VisualMarkView, VisualMarkViewOpts, }; #[cfg(any(target_os = "macos", target_os = "windows"))] -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::{ ComputerUseForegroundApplication, ComputerUsePointerGlobal, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; -use screenshots::Screen; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; @@ -76,7 +76,7 @@ const OSASCRIPT_TIMEOUT_MS: u64 = 10_000; fn run_osascript_bounded(script: &str, timeout_ms: u64) -> std::io::Result { use std::process::Stdio; - let mut child = openbitfun_core::util::process_manager::create_command("/usr/bin/osascript") + let mut child = openbitfun_services_core::process_manager::create_command("/usr/bin/osascript") .args(["-e", script]) .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -128,7 +128,7 @@ mod visual_grid_tests { use super::*; use image::codecs::jpeg::JpegEncoder; use image::{DynamicImage, Rgb, RgbImage}; - use openbitfun_core::agentic::tools::computer_use_host::ComputerUseImageContentRect; + use openbitfun_agent_tools::computer_use_host::ComputerUseImageContentRect; #[test] fn detects_regular_grid_rect_from_synthetic_screenshot() { @@ -206,7 +206,7 @@ mod macos_applescript_tests { /// reports the same syntax errors `osascript` would, so this checks that a /// template is valid AppleScript with no side effects. fn compiles(script: &str) -> Result<(), String> { - let out = std::process::Command::new("/usr/bin/osacompile") + let out = openbitfun_services_core::process_manager::create_command("/usr/bin/osacompile") .args(["-o", "/dev/null", "-e", script]) .output() .map_err(|e| format!("spawn osacompile: {e}"))?; @@ -307,7 +307,7 @@ end tell"#; #[test] #[ignore] fn frontmost_application_resolves_in_a_gui_session() { - let app = DesktopComputerUseHost::macos_foreground_application() + let app = NativeComputerUseHost::macos_foreground_application() .expect("a GUI session always has a frontmost application"); assert!(app.process_id.unwrap_or(0) > 0); assert!( @@ -323,7 +323,7 @@ mod windows_foreground_tests { #[test] fn foreground_app_reports_executable_separately_from_window_title() { - let app = DesktopComputerUseHost::windows_foreground_application( + let app = NativeComputerUseHost::windows_foreground_application( "Search".to_string(), 4242, Some("explorer.exe".to_string()), @@ -336,11 +336,8 @@ mod windows_foreground_tests { #[test] fn foreground_app_falls_back_to_title_only_when_process_lookup_fails() { - let app = DesktopComputerUseHost::windows_foreground_application( - "Search".to_string(), - 4242, - None, - ); + let app = + NativeComputerUseHost::windows_foreground_application("Search".to_string(), 4242, None); assert_eq!(app.name.as_deref(), Some("Search")); assert_eq!(app.process_name, None); @@ -348,7 +345,7 @@ mod windows_foreground_tests { #[test] fn foreground_app_drops_empty_title_and_empty_executable() { - let app = DesktopComputerUseHost::windows_foreground_application( + let app = NativeComputerUseHost::windows_foreground_application( String::new(), 0, Some(String::new()), @@ -359,24 +356,24 @@ mod windows_foreground_tests { } } -pub struct DesktopComputerUseHost { +pub struct NativeComputerUseHost { state: Mutex, } -impl std::fmt::Debug for DesktopComputerUseHost { +impl std::fmt::Debug for NativeComputerUseHost { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("DesktopComputerUseHost") + f.debug_struct("NativeComputerUseHost") .finish_non_exhaustive() } } -impl Default for DesktopComputerUseHost { +impl Default for NativeComputerUseHost { fn default() -> Self { Self::new() } } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { fn state_for_scope( &self, scope: &openbitfun_agent_tools::computer_use_control::ObservationScope, @@ -459,11 +456,11 @@ impl DesktopComputerUseHost { fn open_app_macos( name: String, background: bool, - ) -> OpenBitFunResult { + ) -> OpenBitFunResult { use crate::computer_use::macos_bg_input::{ pid_for_bundle_id_macos, running_app_identity_macos, }; - use openbitfun_core::agentic::tools::computer_use_host::OpenAppResult; + use openbitfun_agent_tools::computer_use_host::OpenAppResult; let failure = |err: String| OpenAppResult { app_name: name.clone(), @@ -517,7 +514,7 @@ impl DesktopComputerUseHost { crate::computer_use::control_session::input_allowed().map_err(OpenBitFunError::tool)?; let opened = if background { let mut command = - openbitfun_core::util::process_manager::create_command("/usr/bin/open"); + openbitfun_services_core::process_manager::create_command("/usr/bin/open"); command.arg("-g"); if std::path::Path::new(&name).is_absolute() { // A caller-provided app path stays authoritative even before @@ -575,7 +572,7 @@ Inspect its process and current application state before choosing another operat crate::computer_use::control_session::input_allowed() .map_err(OpenBitFunError::tool)?; let mut command = - openbitfun_core::util::process_manager::create_command("/usr/bin/open"); + openbitfun_services_core::process_manager::create_command("/usr/bin/open"); if background { command.arg("-g"); } @@ -796,7 +793,7 @@ mod macos; mod pointer_input; mod settle; -impl DesktopComputerUseHost { +impl NativeComputerUseHost { /// Enumerate the registered keyboard shortcuts in `app`'s menu bar. /// Read-only counterpart to `key_chord` / `app_key_chord` (which only /// **send** keys). Unlike `get_app_state_inner`, macOS does not need @@ -889,11 +886,11 @@ fn require_macos_background_input() -> OpenBitFunResult<()> { } #[async_trait] -impl ComputerUseHost for DesktopComputerUseHost { +impl ComputerUseHost for NativeComputerUseHost { async fn dispatch_app_input( &self, app: AppSelector, - action: openbitfun_core::agentic::tools::computer_use_host::AppInputAction, + action: openbitfun_agent_tools::computer_use_host::AppInputAction, ) -> OpenBitFunResult<()> { self.dispatch_app_input_impl(app, action).await } @@ -901,8 +898,8 @@ impl ComputerUseHost for DesktopComputerUseHost { async fn settle_after_input( &self, app: AppSelector, - policy: openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy, - ) -> OpenBitFunResult { + policy: openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy, + ) -> OpenBitFunResult { self.settle_after_input_impl(app, policy).await } @@ -1032,7 +1029,7 @@ impl ComputerUseHost for DesktopComputerUseHost { async fn zoom_observation( &self, app: AppSelector, - region: openbitfun_core::agentic::tools::computer_use_host::ComputerUseZoomRegion, + region: openbitfun_agent_tools::computer_use_host::ComputerUseZoomRegion, ) -> OpenBitFunResult { self.zoom_observation_impl(app, region).await } @@ -1101,8 +1098,8 @@ impl ComputerUseHost for DesktopComputerUseHost { async fn start_control( &self, owner: &str, - request: openbitfun_core::agentic::tools::computer_use_host::ControlStartRequest, - ) -> OpenBitFunResult { + request: openbitfun_agent_tools::computer_use_host::ControlStartRequest, + ) -> OpenBitFunResult { let snapshot = crate::computer_use::control_session::start(owner, request.mode) .map_err(OpenBitFunError::tool)?; let scope = @@ -1129,15 +1126,13 @@ impl ComputerUseHost for DesktopComputerUseHost { Ok(crate::computer_use::control_session::snapshot()) } - fn control_snapshot( - &self, - ) -> openbitfun_core::agentic::tools::computer_use_host::ControlSnapshot { + fn control_snapshot(&self) -> openbitfun_agent_tools::computer_use_host::ControlSnapshot { crate::computer_use::control_session::snapshot() } async fn stop_control( &self, owner: &str, - ) -> OpenBitFunResult { + ) -> OpenBitFunResult { crate::computer_use::control_session::stop(Some(owner), "agent_stopped") .map_err(OpenBitFunError::tool) } @@ -1145,7 +1140,7 @@ impl ComputerUseHost for DesktopComputerUseHost { &self, owner: &str, generation: u64, - ) -> OpenBitFunResult { + ) -> OpenBitFunResult { crate::computer_use::control_session::stop_checked( Some(owner), Some(generation), @@ -1158,7 +1153,7 @@ impl ComputerUseHost for DesktopComputerUseHost { owner: &str, action: &str, ) -> OpenBitFunResult< - Option>, + Option>, > { let policy = openbitfun_agent_tools::computer_use_control::ControlActionPolicy::for_action(action) @@ -1280,17 +1275,15 @@ impl ComputerUseHost for DesktopComputerUseHost { async fn read_screen_text( &self, - ) -> OpenBitFunResult> - { + ) -> OpenBitFunResult> { self.read_screen_text_impl().await } async fn ocr_find_text_matches( &self, text_query: &str, - region_native: Option, - ) -> OpenBitFunResult> - { + region_native: Option, + ) -> OpenBitFunResult> { self.ocr_find_text_matches_impl(text_query, region_native) .await } @@ -1299,9 +1292,8 @@ impl ComputerUseHost for DesktopComputerUseHost { &self, gx: f64, gy: f64, - ) -> OpenBitFunResult< - Option, - > { + ) -> OpenBitFunResult> + { #[cfg(target_os = "macos")] { let pid = resolve_pid_macos(self, &AppSelector::default()).await?; @@ -1427,9 +1419,9 @@ impl ComputerUseHost for DesktopComputerUseHost { async fn open_app( &self, app_name: &str, - ) -> OpenBitFunResult { + ) -> OpenBitFunResult { #[cfg(any(target_os = "macos", target_os = "windows"))] - use openbitfun_core::agentic::tools::computer_use_host::OpenAppResult; + use openbitfun_agent_tools::computer_use_host::OpenAppResult; let name = app_name.to_string(); crate::computer_use::control_session::input_allowed().map_err(OpenBitFunError::tool)?; let background = crate::computer_use::control_session::snapshot().mode @@ -1946,7 +1938,7 @@ fn control_target_pid() -> Option { /// macOS: `pid > bundle_id > name`. Windows: `pid > name` (exact, then /// substring); empty selector resolves to the foreground window's pid. #[cfg(any(target_os = "macos", target_os = "windows"))] -async fn resolve_pid(host: &DesktopComputerUseHost, app: &AppSelector) -> OpenBitFunResult { +async fn resolve_pid(host: &NativeComputerUseHost, app: &AppSelector) -> OpenBitFunResult { #[cfg(target_os = "macos")] { resolve_pid_macos(host, app).await @@ -1955,7 +1947,7 @@ async fn resolve_pid(host: &DesktopComputerUseHost, app: &AppSelector) -> OpenBi { if app_selector_is_unspecified(app) { return Ok( - control_target_pid().unwrap_or_else(DesktopComputerUseHost::windows_foreground_pid) + control_target_pid().unwrap_or_else(NativeComputerUseHost::windows_foreground_pid) ); } if let Some(pid) = app.pid { @@ -1988,7 +1980,7 @@ async fn resolve_pid(host: &DesktopComputerUseHost, app: &AppSelector) -> OpenBi /// precedence (Codex parity): `pid > bundle_id > name`. #[cfg(target_os = "macos")] async fn resolve_pid_macos( - host: &DesktopComputerUseHost, + host: &NativeComputerUseHost, app: &AppSelector, ) -> OpenBitFunResult { if let Some(pid) = app.pid { @@ -2074,7 +2066,7 @@ async fn resolve_pid_macos( /// `get_app_shortcuts` should never fail just because the display name /// couldn't be resolved. #[cfg(any(target_os = "macos", target_os = "windows"))] -async fn app_info_for_pid(host: &DesktopComputerUseHost, pid: i32) -> AppInfo { +async fn app_info_for_pid(host: &NativeComputerUseHost, pid: i32) -> AppInfo { host.list_apps(true) .await .ok() diff --git a/src/apps/desktop/src/computer_use/desktop_host/observation.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/observation.rs similarity index 99% rename from src/apps/desktop/src/computer_use/desktop_host/observation.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/observation.rs index 8638aa7cb6..ca71349a24 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/observation.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/observation.rs @@ -1,7 +1,7 @@ //! Observation lifecycle shared by AX, UIA and AT-SPI providers. use super::*; -impl DesktopComputerUseHost { +impl NativeComputerUseHost { pub(crate) async fn get_app_state_inner( &self, app: AppSelector, diff --git a/src/apps/desktop/src/computer_use/desktop_host/pointer_input.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/pointer_input.rs similarity index 98% rename from src/apps/desktop/src/computer_use/desktop_host/pointer_input.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/pointer_input.rs index b38aa4ba27..6784386f53 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/pointer_input.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/pointer_input.rs @@ -10,20 +10,18 @@ #[cfg(target_os = "macos")] use super::macos; -use super::{DesktopComputerUseHost, PointerMap}; +use super::{NativeComputerUseHost, PointerMap}; use enigo::{Axis, Button, Coordinate, Direction, Enigo, Key, Keyboard, Mouse, Settings}; use log::debug; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; #[cfg(target_os = "windows")] -use openbitfun_core::agentic::tools::computer_use_host::AppSelector; +use openbitfun_agent_tools::computer_use_host::AppSelector; #[cfg(any(target_os = "macos", target_os = "windows"))] -use openbitfun_core::agentic::tools::computer_use_host::ClickTarget; -use openbitfun_core::agentic::tools::computer_use_host::{ - ComputerUseHost, ComputerUseLastMutationKind, -}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::ClickTarget; +use openbitfun_agent_tools::computer_use_host::{ComputerUseHost, ComputerUseLastMutationKind}; use std::time::Duration; -impl DesktopComputerUseHost { +impl NativeComputerUseHost { pub(super) fn ensure_input_automation_allowed() -> OpenBitFunResult<()> { Self::ensure_foreground_target()?; #[cfg(target_os = "macos")] @@ -247,7 +245,7 @@ impl DesktopComputerUseHost { } } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { /// Perform a physical click at the current pointer without running [`ComputerUseHost::computer_use_guard_click_allowed`]. /// Used after `mouse_move_global_f64` when coordinates came from AX or OCR (not from vision model image coords). async fn mouse_click_at_current_pointer(&self, button: &str) -> OpenBitFunResult<()> { @@ -430,7 +428,7 @@ fn flash_click_highlight_cg(gx: f64, gy: f64) { crate::computer_use::control_session::record_pointer(gx, gy, true); } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { #[cfg(target_os = "windows")] pub(super) async fn windows_target(&self, app: &AppSelector) -> OpenBitFunResult<(i32, isize)> { app.validate_window_target() @@ -600,7 +598,7 @@ impl DesktopComputerUseHost { /// Inherent implementations backing the [`ComputerUseHost`] trait's pointer, /// keyboard, and coordinate-mapping methods (see `mod.rs`'s thin trait-method /// delegators). -impl DesktopComputerUseHost { +impl NativeComputerUseHost { pub(super) fn map_image_coords_to_pointer_f64_impl( &self, x: i32, diff --git a/src/apps/desktop/src/computer_use/desktop_host/screenshot.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/screenshot.rs similarity index 98% rename from src/apps/desktop/src/computer_use/desktop_host/screenshot.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/screenshot.rs index f316c076d6..63f12604cb 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/screenshot.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/screenshot.rs @@ -4,20 +4,20 @@ #[cfg(target_os = "macos")] use super::macos; -use super::DesktopComputerUseHost; +use super::NativeComputerUseHost; +use crate::computer_use::displays::Screen; use image::codecs::jpeg::JpegEncoder; #[cfg(any(test, target_os = "macos", target_os = "windows"))] use image::DynamicImage; use image::RgbImage; use openbitfun_agent_tools::computer_use_geometry::CaptureGeometry; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; #[cfg(any(test, target_os = "macos", target_os = "windows"))] -use openbitfun_core::agentic::tools::computer_use_host::ComputerUseZoomRegion; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::ComputerUseZoomRegion; +use openbitfun_agent_tools::computer_use_host::{ ComputerScreenshot, ComputerUseDisplayInfo, ComputerUseImageContentRect, ComputerUseImageGlobalBounds, ComputerUseScreenshotParams, OcrRegionNative, OcrTextMatch, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; -use screenshots::Screen; #[cfg(any(test, target_os = "macos", target_os = "windows"))] fn bound_window_identity(target: &str) -> OpenBitFunResult<(i32, isize)> { @@ -168,7 +168,7 @@ impl PointerMap { } } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { fn encode_jpeg(rgb: &RgbImage, quality: u8) -> OpenBitFunResult> { let mut buf = Vec::new(); let mut enc = JpegEncoder::new_with_quality(&mut buf, quality); @@ -288,7 +288,7 @@ impl DesktopComputerUseHost { } } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { #[cfg(target_os = "macos")] pub(super) async fn screenshot_for_app_pid( &self, @@ -494,13 +494,13 @@ type DetailFrame = ( ); #[cfg(any(target_os = "macos", target_os = "windows"))] -impl DesktopComputerUseHost { +impl NativeComputerUseHost { /// A zoomed observation of the bound window: a fresh capture at the /// highest native detail, cut to a region of an earlier observation. It is /// recorded as the latest image with its own window-relative mapping. pub(super) async fn zoom_observation_impl( &self, - app: openbitfun_core::agentic::tools::computer_use_host::AppSelector, + app: openbitfun_agent_tools::computer_use_host::AppSelector, region: ComputerUseZoomRegion, ) -> OpenBitFunResult { crate::computer_use::control_session::capture_allowed().map_err(OpenBitFunError::tool)?; @@ -639,7 +639,7 @@ impl DesktopComputerUseHost { /// Inherent implementations backing the ComputerUseHost trait's screenshot /// and OCR-capture methods (see `mod.rs`'s thin trait-method delegators). -impl DesktopComputerUseHost { +impl NativeComputerUseHost { #[cfg(target_os = "linux")] async fn screenshot_portal( &self, @@ -832,7 +832,7 @@ impl DesktopComputerUseHost { pub(super) async fn ocr_find_text_matches_impl( &self, text_query: &str, - region_native: Option, + region_native: Option, ) -> OpenBitFunResult> { let shot = self.control_ocr_capture(region_native).await?; let query = text_query.to_string(); @@ -856,7 +856,7 @@ impl DesktopComputerUseHost { Ok(desktop_matches .into_iter() .map( - |m| openbitfun_core::agentic::tools::computer_use_host::OcrTextMatch { + |m| openbitfun_agent_tools::computer_use_host::OcrTextMatch { text: m.text, confidence: m.confidence, center_x: m.center_x, @@ -885,10 +885,10 @@ impl DesktopComputerUseHost { #[cfg(test)] mod window_projection_tests { #[cfg(target_os = "macos")] - use super::DesktopComputerUseHost; + use super::NativeComputerUseHost; use super::{bound_window_identity, CaptureGeometry, PointerMap}; #[cfg(target_os = "macos")] - use openbitfun_core::agentic::tools::computer_use_host::ComputerUseHost; + use openbitfun_agent_tools::computer_use_host::ComputerUseHost; #[test] fn native_capture_identity_never_accepts_an_unbound_or_partial_target() { @@ -932,7 +932,7 @@ mod window_projection_tests { #[cfg(target_os = "macos")] #[test] fn relative_movement_after_capture_uses_geometry_without_ocr_navigation_gate() { - let host = DesktopComputerUseHost::new(); + let host = NativeComputerUseHost::new(); let map = capture_map(); host.state .lock() diff --git a/src/apps/desktop/src/computer_use/desktop_host/settle.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/settle.rs similarity index 94% rename from src/apps/desktop/src/computer_use/desktop_host/settle.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/settle.rs index aa44cca84d..36057e2bb1 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/settle.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/settle.rs @@ -1,10 +1,10 @@ //! Post-input repaint settling on the bound window stream. Waiting never sends //! input, activates a window or substitutes another capture source. -use super::DesktopComputerUseHost; -use openbitfun_core::agentic::tools::computer_use_host::{ +use super::NativeComputerUseHost; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ AppInputSettle, AppInputSettlePolicy, AppSelector, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; #[cfg(any(target_os = "macos", target_os = "windows"))] fn bound_window(app: &AppSelector) -> Result<(i32, u64), AppInputSettle> { @@ -27,7 +27,7 @@ fn bound_window(app: &AppSelector) -> Result<(i32, u64), AppInputSettle> { Ok((pid, window)) } -impl DesktopComputerUseHost { +impl NativeComputerUseHost { pub(super) async fn settle_after_input_impl( &self, app: AppSelector, diff --git a/src/apps/desktop/src/computer_use/desktop_host/shared_preview.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/shared_preview.rs similarity index 95% rename from src/apps/desktop/src/computer_use/desktop_host/shared_preview.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/shared_preview.rs index 314ae1cd5c..f1cf695495 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/shared_preview.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/shared_preview.rs @@ -3,16 +3,16 @@ use super::*; use crate::computer_use::control_session; use openbitfun_agent_tools::computer_use_control::{ControlSnapshot, ObservationScope}; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::{ AppInputAction, ClickTarget, ComputerUseActionLease, ComputerUseImageContentRect, ComputerUseImageGlobalBounds, }; use serde::{Deserialize, Serialize}; use std::sync::OnceLock; -pub(crate) fn host() -> &'static DesktopComputerUseHost { - static HOST: OnceLock = OnceLock::new(); - HOST.get_or_init(DesktopComputerUseHost::new) +pub fn host() -> &'static NativeComputerUseHost { + static HOST: OnceLock = OnceLock::new(); + HOST.get_or_init(NativeComputerUseHost::new) } #[derive(Debug, Deserialize)] @@ -71,7 +71,7 @@ fn pid(control: &ControlSnapshot) -> Result { .ok_or_else(|| "[TARGET_REQUIRED] Shared target has no application process".into()) } -pub(crate) async fn observe(request: SharedPreviewRequest) -> Result { +pub async fn observe(request: SharedPreviewRequest) -> Result { let (control, mut lease) = request.acquire("get_app_state")?; let result = capture(&control).await; lease.complete(); @@ -187,7 +187,7 @@ fn validate_preview_input(input: &AppInputAction) -> Result<(), String> { } } -pub(crate) async fn input(request: SharedInputRequest) -> Result { +pub async fn input(request: SharedInputRequest) -> Result { validate_preview_input(&request.input)?; let (control, mut lease) = request.scope.acquire(request.input.name())?; #[cfg(target_os = "linux")] diff --git a/src/apps/desktop/src/computer_use/desktop_host/sharing.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/sharing.rs similarity index 98% rename from src/apps/desktop/src/computer_use/desktop_host/sharing.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/sharing.rs index f5cb9ef44e..11d57a2ac3 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/sharing.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/sharing.rs @@ -72,7 +72,7 @@ struct Choice { } static CHOICES: OnceLock>> = OnceLock::new(); -pub(crate) async fn targets() -> Result, String> { +pub async fn targets() -> Result, String> { let mut targets = native_targets().await?; let result = tokio::task::spawn_blocking(move || { let mut choices = CHOICES @@ -103,8 +103,8 @@ pub(crate) async fn targets() -> Result, String> { result } -impl DesktopComputerUseHost { - pub(crate) async fn share_selected_target( +impl NativeComputerUseHost { + pub async fn share_selected_target( &self, generation: u64, target_id: &str, diff --git a/src/apps/desktop/src/computer_use/desktop_host/state.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/state.rs similarity index 94% rename from src/apps/desktop/src/computer_use/desktop_host/state.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/state.rs index 06790b029b..4692e7aa7e 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/state.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/state.rs @@ -1,9 +1,9 @@ //! Host-local observations and interaction feedback; control authority lives in control_session. use super::PointerMap; -use openbitfun_core::agentic::tools::computer_use_host::ComputerUseLastMutationKind; +use openbitfun_agent_tools::computer_use_host::ComputerUseLastMutationKind; #[cfg(any(target_os = "macos", target_os = "windows"))] -use openbitfun_core::agentic::tools::computer_use_host::VisualMark; -use openbitfun_core::agentic::tools::computer_use_optimizer::ComputerUseOptimizer; +use openbitfun_agent_tools::computer_use_host::VisualMark; +use tool_runtime::computer_use::ComputerUseOptimizer; /// Unified mutable session state for computer use — one mutex instead of five. /// State transitions are applied centrally after each action (screenshot, pointer move, click, etc.). @@ -43,8 +43,7 @@ pub(super) struct ComputerUseSessionMutableState { pub(super) struct CachedInteractiveView { pub(super) digest: String, /// `i` → `node_idx` map (dense, indexed by `i`). - pub(super) elements: - Vec, + pub(super) elements: Vec, } #[derive(Debug, Clone)] diff --git a/src/apps/desktop/src/computer_use/desktop_host/windows_launch.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/windows_launch.rs similarity index 93% rename from src/apps/desktop/src/computer_use/desktop_host/windows_launch.rs rename to src/crates/services/computer-use/src/computer_use/desktop_host/windows_launch.rs index ba593e3177..a376297b2c 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/windows_launch.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/windows_launch.rs @@ -1,6 +1,6 @@ //! Literal Shell launch with an explicit activation policy; no cmd.exe parsing. -use openbitfun_core::agentic::tools::computer_use_host::OpenAppResult; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::OpenAppResult; use windows::core::{w, HSTRING}; use windows::Win32::Foundation::RPC_E_CHANGED_MODE; use windows::Win32::System::Com::{ diff --git a/src/crates/services/computer-use/src/computer_use/displays.rs b/src/crates/services/computer-use/src/computer_use/displays.rs new file mode 100644 index 0000000000..51ffbb6b6b --- /dev/null +++ b/src/crates/services/computer-use/src/computer_use/displays.rs @@ -0,0 +1,153 @@ +//! Display geometry only. Linux uses X11 protocol IO without a mandatory Xlib +//! dependency; Wayland coordinates remain owned by the consented portal stream. +#[cfg(not(target_os = "linux"))] +pub(super) use screenshots::{display_info::DisplayInfo, Screen}; + +#[cfg(target_os = "linux")] +pub(super) use linux::{DisplayInfo, Screen}; + +#[cfg(target_os = "linux")] +mod linux { + use x11rb::{ + connection::Connection, + protocol::{ + randr::{ConnectionExt as _, MonitorInfo}, + xproto::{AtomEnum, ConnectionExt as _}, + }, + }; + #[derive(Clone, Debug)] + pub(in crate::computer_use) struct DisplayInfo { + pub id: u32, + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, + pub scale_factor: f32, + pub is_primary: bool, + } + pub(in crate::computer_use) struct Screen { + pub display_info: DisplayInfo, + } + impl Screen { + pub(in crate::computer_use) fn all() -> Result, String> { + super::super::linux_control::require_legacy_x11()?; + let (connection, screen) = x11rb::connect(None).map_err(|e| e.to_string())?; + let root = &connection.setup().roots[screen]; + // Preserve the prior display-info logical-coordinate/DPI contract. + let scale = connection + .get_property( + false, + root.root, + AtomEnum::RESOURCE_MANAGER, + AtomEnum::STRING, + 0, + 1024, + ) + .ok() + .and_then(|request| request.reply().ok()) + .map(|reply| scale_from_resources(&reply.value)) + .unwrap_or(1.0); + let monitors = connection + .randr_get_monitors(root.root, true) + .map_err(|e| e.to_string())? + .reply() + .map_err(|e| e.to_string())?; + monitors + .monitors + .iter() + .map(|monitor| { + display_from_monitor(monitor, scale).map(|display_info| Self { display_info }) + }) + .collect() + } + pub(in crate::computer_use) fn from_point(x: i32, y: i32) -> Result { + Self::all()? + .into_iter() + .find(|screen| { + let d = &screen.display_info; + i64::from(x) >= i64::from(d.x) + && i64::from(y) >= i64::from(d.y) + && i64::from(x) < i64::from(d.x) + i64::from(d.width) + && i64::from(y) < i64::from(d.y) + i64::from(d.height) + }) + .ok_or_else(|| { + "[DISPLAY_UNAVAILABLE] Point is outside the available X11 monitors".into() + }) + } + } + fn scale_from_resources(resources: &[u8]) -> f32 { + std::str::from_utf8(resources) + .ok() + .and_then(|text| { + text.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + (name.trim() == "Xft.dpi") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + }) + .filter(|dpi| dpi.is_finite() && *dpi > 0.0) + .map(|dpi| dpi / 96.0) + .unwrap_or(1.0) + } + + fn display_from_monitor(monitor: &MonitorInfo, scale: f32) -> Result { + Ok(DisplayInfo { + id: monitor + .outputs + .first() + .copied() + .ok_or("[DISPLAY_UNAVAILABLE] X11 monitor has no output identity")?, + x: (f32::from(monitor.x) / scale) as i32, + y: (f32::from(monitor.y) / scale) as i32, + width: (f32::from(monitor.width) / scale) as u32, + height: (f32::from(monitor.height) / scale) as u32, + scale_factor: scale, + is_primary: monitor.primary, + }) + } + + #[cfg(test)] + mod tests { + #[test] + fn x11_dpi_keeps_negative_origin_and_logical_geometry() { + use super::*; + let scale = scale_from_resources(b"Xcursor.size: 24\nXft.dpi:\t192\n"); + let monitor = MonitorInfo { + name: 9, + primary: false, + automatic: true, + x: -1920, + y: -1080, + width: 1920, + height: 1080, + width_in_millimeters: 500, + height_in_millimeters: 300, + outputs: vec![42], + }; + let display = display_from_monitor(&monitor, scale).unwrap(); + assert_eq!((display.id, display.x, display.y), (42, -960, -540)); + assert_eq!( + (display.width, display.height, display.scale_factor), + (960, 540, 2.0) + ); + let mut anonymous = monitor.clone(); + anonymous.outputs.clear(); + assert!(display_from_monitor(&anonymous, scale).is_err()); + for invalid in [ + b"Xft.dpi: NaN".as_slice(), + b"Xft.dpi: 0", + b"Xft.dpi: -96", + b"unrelated: 192", + ] { + assert_eq!(scale_from_resources(invalid), 1.0); + } + } + } + + impl DisplayInfo { + pub(in crate::computer_use) fn from_point(x: i32, y: i32) -> Result { + Screen::from_point(x, y).map(|s| s.display_info) + } + } +} diff --git a/src/apps/desktop/src/computer_use/grants.rs b/src/crates/services/computer-use/src/computer_use/grants.rs similarity index 100% rename from src/apps/desktop/src/computer_use/grants.rs rename to src/crates/services/computer-use/src/computer_use/grants.rs diff --git a/src/apps/desktop/src/computer_use/integration_e2e.rs b/src/crates/services/computer-use/src/computer_use/integration_e2e.rs similarity index 99% rename from src/apps/desktop/src/computer_use/integration_e2e.rs rename to src/crates/services/computer-use/src/computer_use/integration_e2e.rs index b80956fe22..4a6157ea98 100644 --- a/src/apps/desktop/src/computer_use/integration_e2e.rs +++ b/src/crates/services/computer-use/src/computer_use/integration_e2e.rs @@ -333,9 +333,7 @@ mod tests { fn complete_flow_type_compatibility() { // Verify that the AxNode type from the host trait can be constructed // with the fields that macos_ax_dump produces. - use openbitfun_core::agentic::tools::computer_use_host::{ - AppInfo, AppStateSnapshot, AxNode, - }; + use openbitfun_agent_tools::computer_use_host::{AppInfo, AppStateSnapshot, AxNode}; let node = AxNode { idx: 0, diff --git a/src/apps/desktop/src/computer_use/interactive_filter.rs b/src/crates/services/computer-use/src/computer_use/interactive_filter.rs similarity index 98% rename from src/apps/desktop/src/computer_use/interactive_filter.rs rename to src/crates/services/computer-use/src/computer_use/interactive_filter.rs index beb95a54f2..6de017cfdf 100644 --- a/src/apps/desktop/src/computer_use/interactive_filter.rs +++ b/src/crates/services/computer-use/src/computer_use/interactive_filter.rs @@ -17,9 +17,7 @@ #![allow(dead_code)] -use openbitfun_core::agentic::tools::computer_use_host::{ - AxNode, ComputerScreenshot, InteractiveElement, -}; +use openbitfun_agent_tools::computer_use_host::{AxNode, ComputerScreenshot, InteractiveElement}; /// Per-host filter knobs. #[derive(Debug, Clone)] @@ -362,7 +360,7 @@ fn project_global_to_image( #[cfg(test)] mod tests { use super::*; - use openbitfun_core::agentic::tools::computer_use_host::ComputerUseImageGlobalBounds; + use openbitfun_agent_tools::computer_use_host::ComputerUseImageGlobalBounds; fn node(idx: u32, role: &str, frame: Option<(f64, f64, f64, f64)>) -> AxNode { AxNode { @@ -522,7 +520,7 @@ mod tests { fn projection_respects_padding_negative_origin_and_partial_intersection() { let mut shot = screenshot(); shot.image_content_rect = Some( - openbitfun_core::agentic::tools::computer_use_host::ComputerUseImageContentRect { + openbitfun_agent_tools::computer_use_host::ComputerUseImageContentRect { left: 100, top: 80, width: 800, diff --git a/src/apps/desktop/src/computer_use/linux_ax_ui.rs b/src/crates/services/computer-use/src/computer_use/linux_ax_ui.rs similarity index 96% rename from src/apps/desktop/src/computer_use/linux_ax_ui.rs rename to src/crates/services/computer-use/src/computer_use/linux_ax_ui.rs index 69ae0570c9..984bf5e272 100644 --- a/src/apps/desktop/src/computer_use/linux_ax_ui.rs +++ b/src/crates/services/computer-use/src/computer_use/linux_ax_ui.rs @@ -8,10 +8,8 @@ use atspi::proxy::accessible::AccessibleProxy; use atspi::proxy::proxy_ext::ProxyExt; use atspi::AccessibilityConnection; use atspi::CoordType; -use openbitfun_core::agentic::tools::computer_use_host::{ - UiElementLocateQuery, UiElementLocateResult, -}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{UiElementLocateQuery, UiElementLocateResult}; use std::collections::VecDeque; async fn component_extents_screen(acc: &AccessibleProxy<'_>) -> Option<(i32, i32, i32, i32)> { diff --git a/src/apps/desktop/src/computer_use/linux_control.rs b/src/crates/services/computer-use/src/computer_use/linux_control.rs similarity index 85% rename from src/apps/desktop/src/computer_use/linux_control.rs rename to src/crates/services/computer-use/src/computer_use/linux_control.rs index a9606b0dbd..298798d856 100644 --- a/src/apps/desktop/src/computer_use/linux_control.rs +++ b/src/crates/services/computer-use/src/computer_use/linux_control.rs @@ -3,13 +3,12 @@ //! Portal input controls the compositor seat, not an isolated background app. //! Never fall back to XTest/enigo when this session fails or is revoked. +use super::linux_native::{self, Pipeline}; use atspi::zbus::{ self, zvariant::{OwnedFd, OwnedObjectPath, OwnedValue, Value}, }; use futures::StreamExt; -use gst::prelude::*; -use gstreamer as gst; use std::{ collections::{HashMap, HashSet}, os::fd::AsRawFd, @@ -136,8 +135,7 @@ pub(super) struct LinuxControlSession { path: OwnedObjectPath, active: Arc, closed_monitor: tokio::task::JoinHandle<()>, - pipeline: gst::Pipeline, - sink: gstreamer_app::AppSink, + pipeline: Pipeline, // Keep the authorized remote open for the complete pipeline lifetime. _pipewire_remote: OwnedFd, stream_id: u32, @@ -164,12 +162,7 @@ impl LinuxControlSession { if display_session() == DisplaySession::Unavailable { return Err("[GUI_UNAVAILABLE] No interactive desktop on this host.".into()); } - gst::init().map_err(|e| format!("[CAPTURE_UNAVAILABLE] GStreamer initialization: {e}"))?; - for factory in ["pipewiresrc", "videoconvert", "jpegenc", "appsink"] { - if gst::ElementFactory::find(factory).is_none() { - return Err(format!("[CAPTURE_UNAVAILABLE] Missing GStreamer plugin {factory}; install gstreamer1.0-pipewire, gstreamer1.0-plugins-base and gstreamer1.0-plugins-good.")); - } - } + linux_native::init_capture()?; let connection = zbus::Connection::session() .await .map_err(|e| format!("[PORTAL_UNAVAILABLE] Session D-Bus: {e}"))?; @@ -206,7 +199,7 @@ impl LinuxControlSession { .await .map_err(|e| e.to_string())?; let setup = Self::configure(&connection, &path, parent_window, allow_input).await; - let (stream_id, logical_size, input_devices, fd, pipeline, sink) = match setup { + let (stream_id, logical_size, input_devices, fd, pipeline) = match setup { Ok(value) => value, Err(error) => { close_session(&connection, &path).await; @@ -218,19 +211,15 @@ impl LinuxControlSession { let monitor_pipeline = pipeline.clone(); let monitor_connection = connection.clone(); let monitor_path = path.clone(); - let bus = pipeline - .bus() - .ok_or("[CAPTURE_UNAVAILABLE] Capture pipeline has no bus")?; - let mut bus_messages = - bus.stream_filtered(&[gst::MessageType::Error, gst::MessageType::Eos]); + let bus_pipeline = pipeline.clone(); let closed_monitor = tokio::spawn(async move { let reason = tokio::select! { _ = closed.next() => "Linux portal sharing stopped or disconnected", - _ = bus_messages.next() => "Linux PipeWire capture ended or failed", + _ = bus_pipeline.ended() => "Linux PipeWire capture ended or failed", }; if monitor_active.swap(false, Ordering::AcqRel) { super::control_session::native_stopped_generation(generation, reason); - let _ = monitor_pipeline.set_state(gst::State::Null); + let _ = monitor_pipeline.stop(); close_session(&monitor_connection, &monitor_path).await; } }); @@ -241,7 +230,6 @@ impl LinuxControlSession { active, closed_monitor, pipeline, - sink, _pipewire_remote: fd, stream_id, logical_size, @@ -257,17 +245,7 @@ impl LinuxControlSession { path: &OwnedObjectPath, parent_window: &str, allow_input: bool, - ) -> Result< - ( - u32, - Option<(i32, i32)>, - u32, - OwnedFd, - gst::Pipeline, - gstreamer_app::AppSink, - ), - String, - > { + ) -> Result<(u32, Option<(i32, i32)>, u32, OwnedFd, Pipeline), String> { if allow_input { let handle = token(); let options = Options::from([ @@ -367,25 +345,8 @@ impl LinuxControlSession { .call("OpenPipeWireRemote", &(path, Options::new())) .await .map_err(|e| format!("[CAPTURE_UNAVAILABLE] PipeWire remote: {e}"))?; - let pipeline = gst::parse::launch(&format!("pipewiresrc name=portal fd={} path={} do-timestamp=true ! videoconvert ! jpegenc ! appsink name=frames max-buffers=1 drop=true sync=false", fd.as_raw_fd(), stream_id)).map_err(|e| format!("[CAPTURE_UNAVAILABLE] {e}"))?.downcast::().map_err(|_| "[CAPTURE_UNAVAILABLE] Invalid GStreamer pipeline")?; - if let Some(serial) = serial { - let source = pipeline - .by_name("portal") - .ok_or("[CAPTURE_UNAVAILABLE] Missing PipeWire source")?; - if source.find_property("target-object").is_none() { - return Err("[CAPTURE_UNAVAILABLE] This PipeWire plugin cannot target stable portal stream identities; upgrade gstreamer1.0-pipewire.".into()); - } - source.set_property("path", Option::::None); - source.set_property("target-object", serial.to_string()); - } - let sink = pipeline - .by_name("frames") - .and_then(|element| element.downcast::().ok()) - .ok_or("[CAPTURE_UNAVAILABLE] Missing frame sink")?; - pipeline - .set_state(gst::State::Playing) - .map_err(|e| format!("[CAPTURE_UNAVAILABLE] Start PipeWire stream: {e}"))?; - Ok((stream_id, logical_size, input_devices, fd, pipeline, sink)) + let pipeline = Pipeline::start(&format!("pipewiresrc name=portal fd={} path={} do-timestamp=true ! videoconvert ! jpegenc ! appsink name=frames max-buffers=1 drop=true sync=false", fd.as_raw_fd(), stream_id), serial)?; + Ok((stream_id, logical_size, input_devices, fd, pipeline)) } pub(super) fn generation(&self) -> u64 { @@ -420,36 +381,19 @@ impl LinuxControlSession { /// Returns a JPEG frame from the authorized PipeWire remote only. pub(super) async fn capture(&self) -> Result, String> { self.ensure_active(0)?; - let sink = self.sink.clone(); + let sink = self.pipeline.clone(); let bytes = super::control_session::spawn_blocking(move || { - let sample = sink - .try_pull_sample(gst::ClockTime::from_mseconds(100)) - .or_else(|| sink.property::>("last-sample")) - .or_else(|| sink.try_pull_sample(gst::ClockTime::from_seconds(5))) - .ok_or("[CAPTURE_UNAVAILABLE] No PipeWire frame within five seconds")?; - let buffer = sample - .buffer() - .ok_or("[CAPTURE_UNAVAILABLE] Empty PipeWire frame")?; - let mapped = buffer - .map_readable() - .map_err(|_| "[CAPTURE_UNAVAILABLE] Cannot map PipeWire frame")?; - let caps = sample - .caps() - .and_then(|caps| caps.structure(0)) - .ok_or("[CAPTURE_INVALID_FRAME] Missing PipeWire frame geometry")?; - let width = caps - .get::("width") - .map_err(|_| "[CAPTURE_INVALID_FRAME] Missing frame width")?; - let height = caps - .get::("height") - .map_err(|_| "[CAPTURE_INVALID_FRAME] Missing frame height")?; - if width <= 0 || height <= 0 { - return Err("[CAPTURE_INVALID_FRAME] Invalid frame dimensions".into()); - } - Ok::<_, String>(( - mapped.as_slice().to_vec(), - ((width as u64) << 32) | height as u64, - )) + let sample = match sink.pull(Duration::from_millis(100))? { + Some(frame) => frame, + None => match sink.last()? { + Some(frame) => frame, + None => sink + .pull(Duration::from_secs(5))? + .ok_or("[CAPTURE_UNAVAILABLE] No PipeWire frame within five seconds")?, + }, + }; + let dimensions = sample.dimensions(); + Ok::<_, String>((sample.bytes, dimensions)) }) .await .map_err(|e| e.to_string())??; @@ -473,30 +417,26 @@ impl LinuxControlSession { /// as a repaint. The newest sample stays available for the next capture. pub(super) async fn wait_settled( &self, - policy: openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy, - ) -> Result { - use openbitfun_core::agentic::tools::computer_use_host::{ + policy: openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy, + ) -> Result { + use openbitfun_agent_tools::computer_use_host::{ app_input_settle_decision, app_input_settle_next_wait_ms, AppInputSettle, AppInputSettleStatus, }; self.ensure_active(0)?; - let sink = self.sink.clone(); + let sink = self.pipeline.clone(); let active = self.active.clone(); super::control_session::spawn_blocking(move || { - let digest = |sample: &gst::Sample| { + let digest = |sample: &linux_native::Frame| { use std::hash::{Hash, Hasher}; let mut hasher = std::collections::hash_map::DefaultHasher::new(); - if let Some(mapped) = sample - .buffer() - .and_then(|buffer| buffer.map_readable().ok()) - { - mapped.as_slice().hash(&mut hasher); - } + sample.bytes.hash(&mut hasher); hasher.finish() }; - let mut previous = sink - .property::>("last-sample") - .map(|sample| digest(&sample)); + let mut previous = match sink.last() { + Ok(frame) => frame.map(|frame| digest(&frame)), + Err(error) => return AppInputSettle::unavailable(error), + }; let started = std::time::Instant::now(); let mut last_change = None; let mut wait_ms = 0; @@ -517,9 +457,11 @@ impl LinuxControlSession { reason: Some("Portal session ended".into()), }; } - if let Some(sample) = - sink.try_pull_sample(gst::ClockTime::from_mseconds(u64::from(wait_ms))) - { + let sample = match sink.pull(Duration::from_millis(u64::from(wait_ms))) { + Ok(sample) => sample, + Err(error) => return AppInputSettle::unavailable(error), + }; + if let Some(sample) = sample { let current = digest(&sample); if previous != Some(current) { previous = Some(current); @@ -548,21 +490,14 @@ impl LinuxControlSession { if self.frame_size.load(Ordering::Acquire) == 0 { return Err("[FRESH_OBSERVATION_REQUIRED] Capture the authorized portal surface before absolute input.".into()); } - if let Some(sample) = self.sink.property::>("last-sample") { - if let Some(caps) = sample.caps().and_then(|caps| caps.structure(0)) { - if let (Ok(width), Ok(height)) = - (caps.get::("width"), caps.get::("height")) - { - let dimensions = ((width as u64) << 32) | height as u64; - if dimensions != self.frame_size.load(Ordering::Acquire) { - self.active.store(false, Ordering::Release); - super::control_session::native_stopped_generation( - self.generation, - "Portal stream geometry changed before input", - ); - return Err("[GEOMETRY_CHANGED] Portal stream resized after the observed frame; restart control.".into()); - } - } + if let Some(sample) = self.pipeline.last()? { + if sample.dimensions() != self.frame_size.load(Ordering::Acquire) { + self.active.store(false, Ordering::Release); + super::control_session::native_stopped_generation( + self.generation, + "Portal stream geometry changed before input", + ); + return Err("[GEOMETRY_CHANGED] Portal stream resized after the observed frame; restart control.".into()); } } if !x.is_finite() || !y.is_finite() || x < 0.0 || y < 0.0 { @@ -715,7 +650,7 @@ impl LinuxControlSession { } let capture_result = self .pipeline - .set_state(gst::State::Null) + .stop() .map_err(|e| format!("[CAPTURE_STOP_FAILED] {e}")); close_session(&self.connection, &self.path).await; self.closed_monitor.abort(); @@ -740,7 +675,7 @@ impl Drop for LinuxControlSession { fn drop(&mut self) { self.active.store(false, Ordering::Release); self.closed_monitor.abort(); - let _ = self.pipeline.set_state(gst::State::Null); + let _ = self.pipeline.stop(); let connection = self.connection.clone(); let path = self.path.clone(); self.runtime.spawn(async move { diff --git a/src/apps/desktop/src/computer_use/linux_control_ax.rs b/src/crates/services/computer-use/src/computer_use/linux_control_ax.rs similarity index 98% rename from src/apps/desktop/src/computer_use/linux_control_ax.rs rename to src/crates/services/computer-use/src/computer_use/linux_control_ax.rs index 6666da8929..448d7b2186 100644 --- a/src/apps/desktop/src/computer_use/linux_control_ax.rs +++ b/src/crates/services/computer-use/src/computer_use/linux_control_ax.rs @@ -3,10 +3,8 @@ use atspi::{ connection::P2P, proxy::proxy_ext::ProxyExt, AccessibilityConnection, CoordType, ObjectRefOwned, State, }; -use openbitfun_core::agentic::tools::computer_use_host::{ - AppInfo, AppSelector, AppStateSnapshot, AxNode, -}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{AppInfo, AppSelector, AppStateSnapshot, AxNode}; use std::{ collections::{HashMap, HashSet, VecDeque}, sync::{Mutex, OnceLock}, @@ -536,7 +534,7 @@ mod native_tests { .unwrap(); let mut lease = super::super::control_session::acquire("native-atspi-fixture", "app_click").unwrap(); - let query = openbitfun_core::agentic::tools::computer_use_host::UiElementLocateQuery { + let query = openbitfun_agent_tools::computer_use_host::UiElementLocateQuery { text_contains: Some("Activate fixture".into()), ..Default::default() }; diff --git a/src/apps/desktop/src/computer_use/linux_control_policy.rs b/src/crates/services/computer-use/src/computer_use/linux_control_policy.rs similarity index 100% rename from src/apps/desktop/src/computer_use/linux_control_policy.rs rename to src/crates/services/computer-use/src/computer_use/linux_control_policy.rs diff --git a/src/crates/services/computer-use/src/computer_use/linux_native.c b/src/crates/services/computer-use/src/computer_use/linux_native.c new file mode 100644 index 0000000000..9d1ff168c9 --- /dev/null +++ b/src/crates/services/computer-use/src/computer_use/linux_native.c @@ -0,0 +1,395 @@ +// Optional Linux capture/OCR libraries are loaded only when used. Linking this +// shim must not make a headless CLI depend on a desktop's installed libraries. +// Compile against the vendor C headers so function signatures and layouts are +// checked by the compiler; retain library handles for the process lifetime. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DECLARE(name) __typeof__(&name) name +#define LOAD(table, library, name) \ + do { \ + *(void **)(&table.name) = dlsym(library, #name); \ + if (!table.name) { \ + snprintf(table.error, sizeof(table.error), "Missing native symbol %s", #name); \ + return; \ + } \ + } while (0) + +static struct { + char error[256]; + DECLARE(gst_init_check); + DECLARE(gst_element_factory_find); + DECLARE(gst_parse_launch); + DECLARE(gst_bin_get_by_name); + DECLARE(gst_element_set_state); + DECLARE(gst_element_get_bus); + DECLARE(gst_bus_pop_filtered); + DECLARE(gst_mini_object_unref); + DECLARE(gst_app_sink_try_pull_sample); + DECLARE(gst_sample_get_buffer); + DECLARE(gst_sample_get_caps); + DECLARE(gst_caps_get_structure); + DECLARE(gst_structure_get_int); + DECLARE(gst_buffer_map); + DECLARE(gst_buffer_unmap); + DECLARE(g_object_get); + DECLARE(g_object_set); + DECLARE(g_object_unref); + DECLARE(g_object_class_find_property); + DECLARE(g_error_free); +} gst; +static pthread_once_t gst_once = PTHREAD_ONCE_INIT; + +static void load_gst(void) { + void *core = dlopen("libgstreamer-1.0.so.0", RTLD_NOW | RTLD_LOCAL); + void *app = dlopen("libgstapp-1.0.so.0", RTLD_NOW | RTLD_LOCAL); + void *object = dlopen("libgobject-2.0.so.0", RTLD_NOW | RTLD_LOCAL); + void *glib = dlopen("libglib-2.0.so.0", RTLD_NOW | RTLD_LOCAL); + if (!core || !app || !object || !glib) { + snprintf( + gst.error, sizeof(gst.error), + "GStreamer is unavailable; install the GStreamer runtime, PipeWire and base/good plugins"); + return; + } + LOAD(gst, core, gst_init_check); + LOAD(gst, core, gst_element_factory_find); + LOAD(gst, core, gst_parse_launch); + LOAD(gst, core, gst_bin_get_by_name); + LOAD(gst, core, gst_element_set_state); + LOAD(gst, core, gst_element_get_bus); + LOAD(gst, core, gst_bus_pop_filtered); + LOAD(gst, core, gst_mini_object_unref); + LOAD(gst, app, gst_app_sink_try_pull_sample); + LOAD(gst, core, gst_sample_get_buffer); + LOAD(gst, core, gst_sample_get_caps); + LOAD(gst, core, gst_caps_get_structure); + LOAD(gst, core, gst_structure_get_int); + LOAD(gst, core, gst_buffer_map); + LOAD(gst, core, gst_buffer_unmap); + LOAD(gst, object, g_object_get); + LOAD(gst, object, g_object_set); + LOAD(gst, object, g_object_unref); + LOAD(gst, object, g_object_class_find_property); + LOAD(gst, glib, g_error_free); +} + +int obf_gst_init(char *error, size_t size) { + pthread_once(&gst_once, load_gst); + if (gst.error[0]) { + snprintf(error, size, "%s", gst.error); + return 0; + } + GError *failure = NULL; + if (!gst.gst_init_check(NULL, NULL, &failure)) { + snprintf(error, size, "%s", failure ? failure->message : "GStreamer initialization failed"); + if (failure) + gst.g_error_free(failure); + return 0; + } + return 1; +} +int obf_gst_has_factory(const char *name) { + GstElementFactory *factory = gst.gst_element_factory_find(name); + if (!factory) + return 0; + gst.g_object_unref(factory); + return 1; +} + +typedef struct { + GstElement *pipeline; + GstElement *sink; + GstBus *bus; +} ObfPipeline; +void obf_gst_release(ObfPipeline *state) { + if (!state) + return; + gst.gst_element_set_state(state->pipeline, GST_STATE_NULL); + if (state->sink) + gst.g_object_unref(state->sink); + if (state->bus) + gst.g_object_unref(state->bus); + gst.g_object_unref(state->pipeline); + free(state); +} +ObfPipeline *obf_gst_start(const char *description, const char *serial, char *error, size_t size) { + if (!obf_gst_init(error, size)) + return NULL; + GError *failure = NULL; + GstElement *pipeline = gst.gst_parse_launch(description, &failure); + if (!pipeline || failure) { + snprintf(error, size, "%s", failure ? failure->message : "No GStreamer pipeline"); + if (failure) + gst.g_error_free(failure); + if (pipeline) + gst.g_object_unref(pipeline); + return NULL; + } + ObfPipeline *state = calloc(1, sizeof(*state)); + if (!state) { + gst.g_object_unref(pipeline); + snprintf(error, size, "Out of memory"); + return NULL; + } + state->pipeline = pipeline; + state->sink = gst.gst_bin_get_by_name((GstBin *)pipeline, "frames"); + state->bus = gst.gst_element_get_bus(pipeline); + if (!state->sink || !state->bus) { + snprintf(error, size, "Missing frame sink or bus"); + goto fail; + } + if (serial) { + GstElement *source = gst.gst_bin_get_by_name((GstBin *)pipeline, "portal"); + if (!source) { + snprintf(error, size, "Missing PipeWire source"); + goto fail; + } + if (!gst.g_object_class_find_property((GObjectClass *)((GTypeInstance *)source)->g_class, + "target-object")) { + gst.g_object_unref(source); + snprintf(error, size, + "PipeWire plugin cannot target stable portal stream identities; upgrade " + "gstreamer1.0-pipewire"); + goto fail; + } + gst.g_object_set(source, "path", NULL, "target-object", serial, NULL); + gst.g_object_unref(source); + } + if (gst.gst_element_set_state(pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) { + snprintf(error, size, "Cannot start PipeWire stream"); + goto fail; + } + return state; +fail: + obf_gst_release(state); + return NULL; +} +int obf_gst_stop(ObfPipeline *state) { + return gst.gst_element_set_state(state->pipeline, GST_STATE_NULL) != GST_STATE_CHANGE_FAILURE; +} +int obf_gst_ended(ObfPipeline *state) { + GstMessage *message = gst.gst_bus_pop_filtered(state->bus, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + if (!message) + return 0; + gst.gst_mini_object_unref((GstMiniObject *)message); + return 1; +} +// 1 = frame, 0 = no sample, -1 = invalid sample. The caller owns returned bytes. +int obf_gst_frame(ObfPipeline *state, uint64_t timeout, int last, unsigned char **bytes, + size_t *length, int *width, int *height, char *error, size_t error_size) { + *bytes = NULL; + *length = 0; + GstSample *sample = NULL; + if (last) + gst.g_object_get(state->sink, "last-sample", &sample, NULL); + else + sample = gst.gst_app_sink_try_pull_sample((GstAppSink *)state->sink, timeout); + if (!sample) + return 0; + int result = -1; + GstCaps *caps = gst.gst_sample_get_caps(sample); + const GstStructure *geometry = caps ? gst.gst_caps_get_structure(caps, 0) : NULL; + if (!geometry || !gst.gst_structure_get_int(geometry, "width", width) || + !gst.gst_structure_get_int(geometry, "height", height) || *width <= 0 || *height <= 0) { + snprintf(error, error_size, "Missing or invalid PipeWire frame dimensions"); + goto done; + } + GstBuffer *buffer = gst.gst_sample_get_buffer(sample); + GstMapInfo map = GST_MAP_INFO_INIT; + if (!buffer || !gst.gst_buffer_map(buffer, &map, GST_MAP_READ)) { + snprintf(error, error_size, "Cannot map PipeWire frame"); + goto done; + } + // Match the bounded native screenshot contract and avoid unbounded copies. + if (map.size == 0 || map.size > 64 * 1024 * 1024) { + snprintf(error, error_size, "Empty or oversized PipeWire frame"); + } else { + *bytes = malloc(map.size); + if (*bytes) { + memcpy(*bytes, map.data, map.size); + *length = map.size; + result = 1; + } else + snprintf(error, error_size, "Out of memory"); + } + gst.gst_buffer_unmap(buffer, &map); +done: + gst.gst_mini_object_unref((GstMiniObject *)sample); + return result; +} +void obf_native_free(void *bytes) { free(bytes); } + +static struct { + char error[256]; + DECLARE(TessBaseAPICreate); + DECLARE(TessBaseAPIInit3); + DECLARE(TessBaseAPISetImage2); + DECLARE(TessBaseAPIRecognize); + DECLARE(TessBaseAPIGetTsvText); + DECLARE(TessBaseAPIDelete); + DECLARE(TessBaseAPIGetComponentImages); + DECLARE(TessBaseAPISetRectangle); + DECLARE(TessBaseAPIGetUTF8Text); + DECLARE(TessBaseAPIMeanTextConf); + DECLARE(TessDeleteText); + DECLARE(pixReadMem); + DECLARE(pixDestroy); + DECLARE(boxaGetCount); + DECLARE(boxaGetBoxGeometry); + DECLARE(boxaDestroy); +} tess; +static pthread_once_t tess_once = PTHREAD_ONCE_INIT; +static void load_tess(void) { + void *api = dlopen("libtesseract.so.5", RTLD_NOW | RTLD_LOCAL); + if (!api) + api = dlopen("libtesseract.so.4", RTLD_NOW | RTLD_LOCAL); + void *lept = dlopen("liblept.so.5", RTLD_NOW | RTLD_LOCAL); + if (!api || !lept) { + snprintf(tess.error, sizeof(tess.error), + "Tesseract is unavailable; install tesseract-ocr and tesseract-ocr-eng"); + return; + } + LOAD(tess, api, TessBaseAPICreate); + LOAD(tess, api, TessBaseAPIInit3); + LOAD(tess, api, TessBaseAPISetImage2); + LOAD(tess, api, TessBaseAPIRecognize); + LOAD(tess, api, TessBaseAPIGetTsvText); + LOAD(tess, api, TessBaseAPIDelete); + LOAD(tess, api, TessBaseAPIGetComponentImages); + LOAD(tess, api, TessBaseAPISetRectangle); + LOAD(tess, api, TessBaseAPIGetUTF8Text); + LOAD(tess, api, TessBaseAPIMeanTextConf); + LOAD(tess, api, TessDeleteText); + LOAD(tess, lept, pixReadMem); + LOAD(tess, lept, pixDestroy); + LOAD(tess, lept, boxaGetCount); + LOAD(tess, lept, boxaGetBoxGeometry); + LOAD(tess, lept, boxaDestroy); +} +typedef struct { + char *text; + int x, y, width, height, confidence; +} ObfOcrWord; +typedef struct { + char *tsv; + ObfOcrWord *words; + size_t count; +} ObfOcr; +void obf_tess_release(ObfOcr *result) { + if (!result) + return; + free(result->tsv); + for (size_t i = 0; i < result->count; ++i) + free(result->words[i].text); + free(result->words); + free(result); +} +ObfOcr *obf_tess_read(const unsigned char *image, size_t length, int words, char *error, + size_t size) { + pthread_once(&tess_once, load_tess); + if (tess.error[0]) { + snprintf(error, size, "%s", tess.error); + return NULL; + } + TessBaseAPI *api = tess.TessBaseAPICreate(); + if (!api) { + snprintf(error, size, "Tesseract allocation failed"); + return NULL; + } + PIX *pix = NULL; + BOXA *boxes = NULL; + ObfOcr *result = NULL; + // Preserve TESSDATA_PREFIX and the existing system-path fallback. + const char *paths[] = {NULL, "/usr/share/tesseract-ocr/5/tessdata/", + "/usr/share/tesseract-ocr/tessdata/", "/usr/share/tessdata/"}; + int initialized = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); ++i) + if (tess.TessBaseAPIInit3(api, paths[i], "eng") == 0) { + initialized = 1; + break; + } + if (!initialized) { + snprintf( + error, size, + "Tesseract initialization failed; install tesseract-ocr-eng or configure TESSDATA_PREFIX"); + goto done; + } + pix = tess.pixReadMem(image, length); + if (!pix) { + snprintf(error, size, "Leptonica could not decode the screenshot"); + goto done; + } + tess.TessBaseAPISetImage2(api, pix); + if (tess.TessBaseAPIRecognize(api, NULL) != 0) { + snprintf(error, size, "Tesseract recognition failed"); + goto done; + } + result = calloc(1, sizeof(*result)); + if (!result) { + snprintf(error, size, "Out of memory"); + goto done; + } + if (!words) { + char *tsv = tess.TessBaseAPIGetTsvText(api, 0); + if (tsv) { + result->tsv = strdup(tsv); + tess.TessDeleteText(tsv); + } + if (!result->tsv) { + snprintf(error, size, "Tesseract returned no TSV text"); + goto failed; + } + } else { + boxes = tess.TessBaseAPIGetComponentImages(api, RIL_WORD, TRUE, NULL, NULL); + if (!boxes) { + snprintf(error, size, "Tesseract returned no word regions"); + goto failed; + } + int count = tess.boxaGetCount(boxes); + if (count < 0 || count > 100000) { + snprintf(error, size, "Invalid word region count"); + goto failed; + } + result->words = calloc((size_t)count + 1, sizeof(ObfOcrWord)); + if (!result->words) { + snprintf(error, size, "Out of memory"); + goto failed; + } + result->count = (size_t)count; + for (int i = 0; i < count; ++i) { + ObfOcrWord *word = &result->words[i]; + if (tess.boxaGetBoxGeometry(boxes, i, &word->x, &word->y, &word->width, &word->height) != 0 || + word->width <= 0 || word->height <= 0) + continue; + tess.TessBaseAPISetRectangle(api, word->x, word->y, word->width, word->height); + char *text = tess.TessBaseAPIGetUTF8Text(api); + if (!text) + continue; + word->text = strdup(text); + tess.TessDeleteText(text); + word->confidence = tess.TessBaseAPIMeanTextConf(api); + if (!word->text) { + snprintf(error, size, "Out of memory"); + goto failed; + } + } + } + goto done; +failed: + obf_tess_release(result); + result = NULL; +done: + if (boxes) + tess.boxaDestroy(&boxes); + tess.TessBaseAPIDelete(api); + if (pix) + tess.pixDestroy(&pix); + return result; +} diff --git a/src/crates/services/computer-use/src/computer_use/linux_native.rs b/src/crates/services/computer-use/src/computer_use/linux_native.rs new file mode 100644 index 0000000000..4923298f4e --- /dev/null +++ b/src/crates/services/computer-use/src/computer_use/linux_native.rs @@ -0,0 +1,258 @@ +//! Safe ownership boundary for the optional, vendor-header-checked C adapters. +use std::{ + ffi::{c_char, c_void, CStr, CString}, + sync::Arc, + time::Duration, +}; + +unsafe extern "C" { + fn obf_gst_init(error: *mut c_char, size: usize) -> i32; + fn obf_gst_has_factory(name: *const c_char) -> i32; + fn obf_gst_start( + description: *const c_char, + serial: *const c_char, + error: *mut c_char, + size: usize, + ) -> *mut c_void; + fn obf_gst_release(pipeline: *mut c_void); + fn obf_gst_stop(pipeline: *mut c_void) -> i32; + fn obf_gst_ended(pipeline: *mut c_void) -> i32; + fn obf_gst_frame( + pipeline: *mut c_void, + timeout: u64, + last: i32, + bytes: *mut *mut u8, + length: *mut usize, + width: *mut i32, + height: *mut i32, + error: *mut c_char, + size: usize, + ) -> i32; + fn obf_native_free(bytes: *mut c_void); + fn obf_tess_read( + image: *const u8, + length: usize, + words: i32, + error: *mut c_char, + size: usize, + ) -> *mut Ocr; + fn obf_tess_release(result: *mut Ocr); +} + +fn message(error: &[c_char]) -> String { + // Every C function writes a bounded, NUL-terminated message on failure. + unsafe { CStr::from_ptr(error.as_ptr()) } + .to_string_lossy() + .into_owned() +} + +pub(super) fn init_capture() -> Result<(), String> { + let mut error = [0; 512]; + if unsafe { obf_gst_init(error.as_mut_ptr(), error.len()) } == 0 { + return Err(format!("[CAPTURE_UNAVAILABLE] {}", message(&error))); + } + for name in [c"pipewiresrc", c"videoconvert", c"jpegenc", c"appsink"] { + if unsafe { obf_gst_has_factory(name.as_ptr()) } == 0 { + return Err(format!("[CAPTURE_UNAVAILABLE] Missing GStreamer plugin {}; install gstreamer1.0-pipewire, gstreamer1.0-plugins-base and gstreamer1.0-plugins-good.", name.to_string_lossy())); + } + } + Ok(()) +} + +struct PipelineInner(*mut c_void); +// GStreamer permits concurrent state, bus and appsink operations. Arc retains +// the complete object graph until the last observer/Stop operation returns. +unsafe impl Send for PipelineInner {} +unsafe impl Sync for PipelineInner {} +impl Drop for PipelineInner { + fn drop(&mut self) { + unsafe { obf_gst_release(self.0) }; + } +} +#[derive(Clone)] +pub(super) struct Pipeline(Arc); +pub(super) struct Frame { + pub bytes: Vec, + pub width: i32, + pub height: i32, +} +impl Frame { + pub(super) fn dimensions(&self) -> u64 { + ((self.width as u64) << 32) | self.height as u64 + } +} +impl Pipeline { + pub(super) fn start(description: &str, serial: Option) -> Result { + let description = + CString::new(description).map_err(|_| "[CAPTURE_UNAVAILABLE] Invalid pipeline")?; + let serial = serial.map(|serial| CString::new(serial.to_string()).unwrap()); + let mut error = [0; 512]; + let pipeline = unsafe { + obf_gst_start( + description.as_ptr(), + serial.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()), + error.as_mut_ptr(), + error.len(), + ) + }; + if pipeline.is_null() { + return Err(format!("[CAPTURE_UNAVAILABLE] {}", message(&error))); + } + Ok(Self(Arc::new(PipelineInner(pipeline)))) + } + pub(super) fn stop(&self) -> Result<(), String> { + if unsafe { obf_gst_stop(self.0 .0) } != 0 { + Ok(()) + } else { + Err("[CAPTURE_STOP_FAILED] Cannot stop the native stream".into()) + } + } + pub(super) async fn ended(&self) { + loop { + if unsafe { obf_gst_ended(self.0 .0) } != 0 { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + pub(super) fn pull(&self, timeout: Duration) -> Result, String> { + self.frame(timeout, false) + } + pub(super) fn last(&self) -> Result, String> { + self.frame(Duration::ZERO, true) + } + fn frame(&self, timeout: Duration, last: bool) -> Result, String> { + let (mut bytes, mut length, mut width, mut height) = (std::ptr::null_mut(), 0, 0, 0); + let mut error = [0; 512]; + let status = unsafe { + obf_gst_frame( + self.0 .0, + timeout.as_nanos().min(u64::MAX as u128) as u64, + i32::from(last), + &mut bytes, + &mut length, + &mut width, + &mut height, + error.as_mut_ptr(), + error.len(), + ) + }; + match status { + 0 => Ok(None), + 1 => { + // The shim guarantees a nonempty bounded allocation on status 1. + let data = unsafe { std::slice::from_raw_parts(bytes, length) }.to_vec(); + unsafe { obf_native_free(bytes.cast()) }; + Ok(Some(Frame { + bytes: data, + width, + height, + })) + } + _ => Err(format!("[CAPTURE_INVALID_FRAME] {}", message(&error))), + } + } +} + +#[repr(C)] +struct OcrWord { + text: *mut c_char, + x: i32, + y: i32, + width: i32, + height: i32, + confidence: i32, +} +#[repr(C)] +struct Ocr { + tsv: *mut c_char, + words: *mut OcrWord, + count: usize, +} +struct OcrOwner(*mut Ocr); +impl Drop for OcrOwner { + fn drop(&mut self) { + unsafe { obf_tess_release(self.0) }; + } +} +pub(super) struct RecognizedWord { + pub text: String, + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, + pub confidence: f32, +} +pub(super) struct Recognition { + pub tsv: String, + pub words: Vec, + pub region_count: usize, +} +pub(super) fn recognize(image: &[u8], words: bool) -> Result { + let mut error = [0; 512]; + let raw = unsafe { + obf_tess_read( + image.as_ptr(), + image.len(), + i32::from(words), + error.as_mut_ptr(), + error.len(), + ) + }; + if raw.is_null() { + return Err(format!("[OCR_UNAVAILABLE] {}", message(&error))); + } + let _owner = OcrOwner(raw); + let result = unsafe { &*raw }; + let mut output = Recognition { + tsv: String::new(), + words: Vec::new(), + region_count: result.count, + }; + let text = |value| { + unsafe { CStr::from_ptr(value) } + .to_str() + .map(str::to_owned) + .map_err(|_| "[OCR_INVALID_TEXT] Invalid UTF-8 from Tesseract".to_owned()) + }; + if !result.tsv.is_null() { + output.tsv = text(result.tsv)?; + } + if !result.words.is_null() { + for word in unsafe { std::slice::from_raw_parts(result.words, result.count) } { + if word.text.is_null() { + continue; + } + output.words.push(RecognizedWord { + text: text(word.text)?, + x: word.x, + y: word.y, + width: word.width, + height: word.height, + confidence: word.confidence as f32 / 100.0, + }); + } + } + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + // A disposable generated stream tests the actual dlopen/C adapter without + // a screen, portal consent, or user content. Optional system packages required. + #[test] + #[ignore = "requires the Linux GStreamer runtime and base/good plugins"] + fn native_generated_stream_captures_and_stops() { + let pipeline = Pipeline::start("videotestsrc num-buffers=4 ! video/x-raw,width=160,height=90 ! jpegenc ! appsink name=frames max-buffers=1 drop=true sync=false", None).unwrap(); + let frame = pipeline.pull(Duration::from_secs(5)).unwrap().unwrap(); + assert_eq!((frame.width, frame.height), (160, 90)); + assert_eq!(image::load_from_memory(&frame.bytes).unwrap().width(), 160); + assert_eq!( + pipeline.last().unwrap().unwrap().dimensions(), + frame.dimensions() + ); + pipeline.stop().unwrap(); + assert!(pipeline.pull(Duration::ZERO).unwrap().is_none()); + } +} diff --git a/src/apps/desktop/src/computer_use/macos_ax_dispatch.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_dispatch.rs similarity index 100% rename from src/apps/desktop/src/computer_use/macos_ax_dispatch.rs rename to src/crates/services/computer-use/src/computer_use/macos_ax_dispatch.rs diff --git a/src/apps/desktop/src/computer_use/macos_ax_dump.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_ax_dump.rs rename to src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs index c34d25649b..1096f36df5 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_dump.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs @@ -29,8 +29,8 @@ use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; use core_foundation::boolean::{CFBoolean, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::string::{CFString, CFStringRef}; use core_graphics::geometry::{CGPoint, CGSize}; -use openbitfun_core::agentic::tools::computer_use_host::{AppStateSnapshot, AxNode}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{AppStateSnapshot, AxNode}; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::sync::{Mutex, OnceLock}; @@ -967,7 +967,7 @@ equivalents, or AXPress the menu first.\n", Ok(AppStateSnapshot { observation_id: None, - app: openbitfun_core::agentic::tools::computer_use_host::AppInfo { + app: openbitfun_agent_tools::computer_use_host::AppInfo { name: window_title.clone().unwrap_or_default(), bundle_id: None, pid: Some(pid), @@ -1271,7 +1271,7 @@ mod tests { "the same native element must not be emitted twice" ); } - let query = openbitfun_core::agentic::tools::computer_use_host::UiElementLocateQuery { + let query = openbitfun_agent_tools::computer_use_host::UiElementLocateQuery { text_contains: Some("Save report".into()), ..Default::default() }; @@ -1339,7 +1339,7 @@ mod tests { serde_json::from_value(serde_json::to_value(&snapshot).unwrap()).unwrap(); assert_eq!(restored, snapshot); } - use openbitfun_core::agentic::tools::computer_use_host::AxNode; + use openbitfun_agent_tools::computer_use_host::AxNode; fn n(idx: u32, parent: Option, role: &str, title: Option<&str>) -> AxNode { AxNode { diff --git a/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_shortcuts.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs rename to src/crates/services/computer-use/src/computer_use/macos_ax_shortcuts.rs index 04669356ce..fc215a0097 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_shortcuts.rs @@ -18,8 +18,8 @@ use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; use core_foundation::boolean::{CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::string::{CFString, CFStringRef}; -use openbitfun_core::agentic::tools::computer_use_host::AppMenuShortcut; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::AppMenuShortcut; use std::ffi::c_void; type CFNumberRef = *const c_void; diff --git a/src/apps/desktop/src/computer_use/macos_ax_ui.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_ui.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_ax_ui.rs rename to src/crates/services/computer-use/src/computer_use/macos_ax_ui.rs index a479cd71bb..64db88c3a4 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_ui.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_ui.rs @@ -1,6 +1,6 @@ //! macOS Accessibility (AX) tree search for stable UI centers (native “DOM”). //! -//! Coordinates match CoreGraphics global space used by [`crate::computer_use::DesktopComputerUseHost`]. +//! Coordinates match CoreGraphics global space used by [`crate::computer_use::NativeComputerUseHost`]. use super::macos_ax_dispatch::{ copy_action_names as AXUIElementCopyActionNames, @@ -14,10 +14,10 @@ use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; use core_foundation::string::{CFString, CFStringRef}; use core_graphics::geometry::{CGPoint, CGSize}; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ OcrAccessibilityHit, UiElementLocateQuery, UiElementLocateResult, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use std::collections::VecDeque; use std::ffi::c_void; @@ -1310,7 +1310,7 @@ pub(super) fn restore_window(pid: i32, window: u32) -> OpenBitFunResult { } /// Native fixtures only: minimize an exact window of a disposable test process. -#[cfg(feature = "devtools")] +#[cfg(feature = "test-support")] pub(super) fn minimize_window_for_fixture(pid: i32, window: u32) -> Result<(), String> { // SAFETY: the created and copied AX elements are null-checked and released // exactly once. diff --git a/src/apps/desktop/src/computer_use/macos_ax_write.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs similarity index 98% rename from src/apps/desktop/src/computer_use/macos_ax_write.rs rename to src/crates/services/computer-use/src/computer_use/macos_ax_write.rs index 58f31de082..8e9dab38f1 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_write.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs @@ -112,8 +112,8 @@ pub(super) fn try_ax_set_value(target: AxRef, value: &str) -> AxWriteOutcome { pub(super) fn insert_selected_text( target: AxRef, text: &str, -) -> openbitfun_core::util::errors::OpenBitFunResult { - use openbitfun_core::util::errors::OpenBitFunError; +) -> openbitfun_agent_tools::computer_use_host::error::OpenBitFunResult { + use openbitfun_agent_tools::computer_use_host::error::OpenBitFunError; if !can_write(target) { return Err(OpenBitFunError::tool( "[CONTROL_TARGET_CHANGED] Text target is outside the active capture", diff --git a/src/apps/desktop/src/computer_use/macos_bg_input.rs b/src/crates/services/computer-use/src/computer_use/macos_bg_input.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_bg_input.rs rename to src/crates/services/computer-use/src/computer_use/macos_bg_input.rs index 189146a394..3e04519acb 100644 --- a/src/apps/desktop/src/computer_use/macos_bg_input.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_bg_input.rs @@ -11,7 +11,7 @@ use core_graphics::event_source::{CGEventSource, CGEventSourceStateID}; use core_graphics::geometry::CGPoint; use foreign_types::ForeignType; use log::{debug, info, warn}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use std::ffi::c_void; use std::thread; use std::time::{Duration, Instant}; diff --git a/src/apps/desktop/src/computer_use/macos_capture.m b/src/crates/services/computer-use/src/computer_use/macos_capture.m similarity index 100% rename from src/apps/desktop/src/computer_use/macos_capture.m rename to src/crates/services/computer-use/src/computer_use/macos_capture.m diff --git a/src/apps/desktop/src/computer_use/macos_capture.rs b/src/crates/services/computer-use/src/computer_use/macos_capture.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_capture.rs rename to src/crates/services/computer-use/src/computer_use/macos_capture.rs index dba68aabb5..9fa6210f49 100644 --- a/src/apps/desktop/src/computer_use/macos_capture.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_capture.rs @@ -600,9 +600,9 @@ impl Drop for RetainedCapture { pub(super) fn wait_settled( pid: i32, window_id: u32, - policy: openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy, -) -> Result { - use openbitfun_core::agentic::tools::computer_use_host::{ + policy: openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy, +) -> Result { + use openbitfun_agent_tools::computer_use_host::{ app_input_settle_decision, app_input_settle_next_wait_ms, AppInputSettle, AppInputSettleStatus, }; diff --git a/src/apps/desktop/src/computer_use/macos_input_focus.rs b/src/crates/services/computer-use/src/computer_use/macos_input_focus.rs similarity index 99% rename from src/apps/desktop/src/computer_use/macos_input_focus.rs rename to src/crates/services/computer-use/src/computer_use/macos_input_focus.rs index 91e35530b3..01e456f587 100644 --- a/src/apps/desktop/src/computer_use/macos_input_focus.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_input_focus.rs @@ -8,7 +8,7 @@ use core_graphics::event::{CGEvent, CGEventFlags, CGEventType, CGMouseButton}; use core_graphics::geometry::CGPoint; use foreign_types::ForeignType; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use std::sync::Mutex; use std::time::Duration; diff --git a/src/apps/desktop/src/computer_use/macos_list_apps.rs b/src/crates/services/computer-use/src/computer_use/macos_list_apps.rs similarity index 98% rename from src/apps/desktop/src/computer_use/macos_list_apps.rs rename to src/crates/services/computer-use/src/computer_use/macos_list_apps.rs index bc5cdbaa0b..27829c43bf 100644 --- a/src/apps/desktop/src/computer_use/macos_list_apps.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_list_apps.rs @@ -9,10 +9,10 @@ use core_foundation::dictionary::CFDictionary; use core_foundation::number::CFNumber; use core_foundation::string::CFString; use objc2_app_kit::{NSApplicationActivationPolicy, NSRunningApplication, NSWorkspace}; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ AppInfo, AppWindowInfo, ComputerUseImageGlobalBounds, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use std::collections::HashSet; use std::ffi::c_void; diff --git a/src/apps/desktop/src/computer_use/macos_skylight.rs b/src/crates/services/computer-use/src/computer_use/macos_skylight.rs similarity index 100% rename from src/apps/desktop/src/computer_use/macos_skylight.rs rename to src/crates/services/computer-use/src/computer_use/macos_skylight.rs diff --git a/src/crates/services/computer-use/src/computer_use/mod.rs b/src/crates/services/computer-use/src/computer_use/mod.rs new file mode 100644 index 0000000000..5781adfa3e --- /dev/null +++ b/src/crates/services/computer-use/src/computer_use/mod.rs @@ -0,0 +1,80 @@ +//! Desktop Computer Use: portable admission/observation lifecycle, native OS providers. + +mod ax_snapshot_digest; +pub mod control_session; +mod debug_overlay; +mod desktop_host; +mod displays; +pub mod grants; +mod interactive_filter; +#[cfg(target_os = "linux")] +mod linux_ax_ui; +#[cfg(target_os = "linux")] +mod linux_control; +#[cfg(target_os = "linux")] +mod linux_control_ax; +#[cfg(target_os = "linux")] +mod linux_native; +#[cfg(target_os = "macos")] +mod macos_ax_dispatch; +#[cfg(target_os = "macos")] +mod macos_ax_dump; +#[cfg(target_os = "macos")] +mod macos_ax_shortcuts; +#[cfg(target_os = "macos")] +mod macos_ax_ui; +#[cfg(target_os = "macos")] +mod macos_ax_write; +#[cfg(target_os = "macos")] +mod macos_bg_input; +#[cfg(target_os = "macos")] +mod macos_capture; +#[cfg(target_os = "macos")] +mod macos_input_focus; +#[cfg(target_os = "macos")] +mod macos_list_apps; +#[cfg(target_os = "macos")] +mod macos_skylight; +mod observation_cache; +mod ocr_context; +#[cfg(any(target_os = "macos", target_os = "windows", test))] +mod overlay_windows; +pub mod permissions; +pub(crate) mod process_identity; +#[cfg(any(target_os = "windows", test))] +mod provider_worker; +mod screen_ocr; +pub mod share_grants; +mod som_overlay; +mod terminal_detect; +mod ui_locate_common; +#[cfg(target_os = "windows")] +mod windows_ax_shortcuts; +#[cfg(target_os = "windows")] +mod windows_ax_ui; +#[cfg(target_os = "windows")] +mod windows_bg_input; +#[cfg(target_os = "windows")] +mod windows_capture; +#[cfg(target_os = "windows")] +mod windows_list_apps; +#[cfg(target_os = "windows")] +mod windows_msaa; +#[cfg(any(target_os = "windows", test))] +mod windows_overlay; +#[cfg(target_os = "windows")] +mod windows_pointer_feedback; +#[cfg(target_os = "windows")] +mod windows_wgc_capture; +#[cfg(any(target_os = "windows", test))] +mod windows_window_target; + +pub use desktop_host::shared_preview; +pub use desktop_host::sharing::targets as share_targets; +pub use desktop_host::NativeComputerUseHost; + +#[cfg(test)] +mod integration_e2e; + +#[cfg(all(feature = "test-support", target_os = "macos"))] +pub mod test_support; diff --git a/src/apps/desktop/src/computer_use/observation_cache.rs b/src/crates/services/computer-use/src/computer_use/observation_cache.rs similarity index 100% rename from src/apps/desktop/src/computer_use/observation_cache.rs rename to src/crates/services/computer-use/src/computer_use/observation_cache.rs diff --git a/src/apps/desktop/src/computer_use/ocr_context.rs b/src/crates/services/computer-use/src/computer_use/ocr_context.rs similarity index 99% rename from src/apps/desktop/src/computer_use/ocr_context.rs rename to src/crates/services/computer-use/src/computer_use/ocr_context.rs index 16a3856486..8bbbcb2958 100644 --- a/src/apps/desktop/src/computer_use/ocr_context.rs +++ b/src/crates/services/computer-use/src/computer_use/ocr_context.rs @@ -1,6 +1,6 @@ //! Pure OCR matching and screenshot-coordinate projection; no OS calls. use super::screen_ocr::OcrTextMatch; -use openbitfun_core::agentic::tools::computer_use_host::ComputerScreenshot; +use openbitfun_agent_tools::computer_use_host::ComputerScreenshot; /// Normalize for substring / fuzzy matching. Strips **all** Unicode whitespace so that /// Vision output like `"尉 怡 青"` or `"尉怡 青"` still matches query `"尉怡青"` (CJK UIs often diff --git a/src/apps/desktop/src/computer_use/overlay_windows.rs b/src/crates/services/computer-use/src/computer_use/overlay_windows.rs similarity index 99% rename from src/apps/desktop/src/computer_use/overlay_windows.rs rename to src/crates/services/computer-use/src/computer_use/overlay_windows.rs index 93ea5766c0..5aefa078b5 100644 --- a/src/apps/desktop/src/computer_use/overlay_windows.rs +++ b/src/crates/services/computer-use/src/computer_use/overlay_windows.rs @@ -3,7 +3,7 @@ //! so a single-window capture omits them while a physical pointer over them //! reaches them instead of the window beneath. Bounds use the same global //! basis as the bound frame: macOS points, Windows physical pixels. -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::{ ComputerScreenshot, ComputerUseAuxiliaryWindow, ComputerUseImageContentRect, ComputerUseImageGlobalBounds, }; diff --git a/src/apps/desktop/src/computer_use/permissions.rs b/src/crates/services/computer-use/src/computer_use/permissions.rs similarity index 98% rename from src/apps/desktop/src/computer_use/permissions.rs rename to src/crates/services/computer-use/src/computer_use/permissions.rs index 3867932ba5..9e2ba66c4b 100644 --- a/src/apps/desktop/src/computer_use/permissions.rs +++ b/src/crates/services/computer-use/src/computer_use/permissions.rs @@ -11,7 +11,7 @@ const KINDS: [Kind; 4] = [ Kind::InputMonitoring, ]; -pub(crate) async fn status() -> ComputerPermissions { +pub async fn status() -> ComputerPermissions { let permissions = platform_status().await; ComputerPermissions { platform: std::env::consts::OS.into(), @@ -24,7 +24,7 @@ pub(crate) async fn status() -> ComputerPermissions { } } -pub(crate) async fn request(kind: Kind) -> Result { +pub async fn request(kind: Kind) -> Result { let before = status().await; let already_granted = before.usable(kind); #[cfg(target_os = "macos")] diff --git a/src/apps/desktop/src/computer_use/pointer_motion.c b/src/crates/services/computer-use/src/computer_use/pointer_motion.c similarity index 100% rename from src/apps/desktop/src/computer_use/pointer_motion.c rename to src/crates/services/computer-use/src/computer_use/pointer_motion.c diff --git a/src/apps/desktop/src/computer_use/pointer_motion.h b/src/crates/services/computer-use/src/computer_use/pointer_motion.h similarity index 100% rename from src/apps/desktop/src/computer_use/pointer_motion.h rename to src/crates/services/computer-use/src/computer_use/pointer_motion.h diff --git a/src/apps/desktop/src/computer_use/process_identity.rs b/src/crates/services/computer-use/src/computer_use/process_identity.rs similarity index 100% rename from src/apps/desktop/src/computer_use/process_identity.rs rename to src/crates/services/computer-use/src/computer_use/process_identity.rs diff --git a/src/apps/desktop/src/computer_use/provider_worker.rs b/src/crates/services/computer-use/src/computer_use/provider_worker.rs similarity index 100% rename from src/apps/desktop/src/computer_use/provider_worker.rs rename to src/crates/services/computer-use/src/computer_use/provider_worker.rs diff --git a/src/apps/desktop/src/computer_use/screen_ocr.rs b/src/crates/services/computer-use/src/computer_use/screen_ocr.rs similarity index 87% rename from src/apps/desktop/src/computer_use/screen_ocr.rs rename to src/crates/services/computer-use/src/computer_use/screen_ocr.rs index 31fa8a85a1..d3321a9c58 100644 --- a/src/apps/desktop/src/computer_use/screen_ocr.rs +++ b/src/crates/services/computer-use/src/computer_use/screen_ocr.rs @@ -1,7 +1,6 @@ use log::{info, warn}; -use openbitfun_core::agentic::tools::computer_use_host::ComputerScreenshot; -use openbitfun_core::infrastructure::try_get_path_manager_arc; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::ComputerScreenshot; use std::fs; use std::io::Write; use std::path::PathBuf; @@ -44,7 +43,36 @@ mod native_fixture_tests { } } -pub(super) use openbitfun_core::agentic::tools::computer_use_host::OcrTextMatch; +#[cfg(all(test, target_os = "linux"))] +mod linux_native_fixture_tests { + use super::*; + + #[test] + #[ignore = "requires OPENBITFUN_OCR_FIXTURE and Tesseract English data"] + fn native_tesseract_reads_rendered_fixture() { + let path = std::env::var("OPENBITFUN_OCR_FIXTURE").expect("rendered OCR fixture path"); + let shot: ComputerScreenshot = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let lines = linux_backend::read_text(&shot).expect("native Tesseract TSV adapter"); + assert!( + lines + .iter() + .any(|line| line.text.to_lowercase().contains("save report")), + "{lines:?}" + ); + let words = linux_backend::find_text_matches(&shot, "Cancel") + .expect("native Tesseract region adapter"); + assert!(!words.is_empty()); + for hit in words { + assert!(hit.text.to_lowercase().contains("cancel")); + assert!((-450.0..-300.0).contains(&hit.center_x), "{hit:?}"); + assert!((250.0..290.0).contains(&hit.center_y), "{hit:?}"); + assert!(hit.bounds_width > 0.0 && hit.bounds_height > 0.0); + } + } +} + +pub(super) use openbitfun_agent_tools::computer_use_host::OcrTextMatch; /// Read the best recognized text for every visible region. No search query, /// candidate ranking, or debug pixel persistence is involved. @@ -133,11 +161,8 @@ mod debug_policy_tests { /// Same directory as agent `screenshot` debug (`workspace/.openbitfun/computer_use_debug`), when PathManager is available. fn computer_use_ocr_debug_dir() -> PathBuf { - if let Ok(pm) = try_get_path_manager_arc() { - return pm - .default_assistant_workspace_dir(None) - .join(openbitfun_core_types::product_identity::hidden_data_directory()) - .join("computer_use_debug"); + if let Some(path) = crate::OCR_DEBUG_DIRECTORY.get() { + return path.clone(); } dirs::home_dir() .map(|h| { @@ -231,8 +256,8 @@ mod macos { VNRecognizeTextRequestRevision3, VNRecognizedTextObservation, VNRequest, VNRequestTextRecognitionLevel, }; - use openbitfun_core::agentic::tools::computer_use_host::ComputerScreenshot; - use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::ComputerScreenshot; /// Top-N candidates per observation; Chinese matches often appear below rank 1. const TOP_CANDIDATES_MAX: usize = 10; @@ -453,8 +478,8 @@ mod windows_backend { filter_and_rank, fuzzy_text_matches_query, image_box_to_global_match, image_content_rect_or_full, normalize_for_match, OcrTextMatch, }; - use openbitfun_core::agentic::tools::computer_use_host::ComputerScreenshot; - use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::ComputerScreenshot; use windows::core::HSTRING; use windows::Graphics::Imaging::BitmapDecoder; use windows::Media::Ocr::{OcrEngine, OcrWord}; @@ -655,7 +680,7 @@ mod windows_backend { } // --------------------------------------------------------------------------- -// Linux: Tesseract OCR via leptess bindings +// Linux: Tesseract OCR through the optional native C provider // --------------------------------------------------------------------------- #[cfg(target_os = "linux")] mod linux_backend { @@ -663,10 +688,8 @@ mod linux_backend { filter_and_rank, fuzzy_text_matches_query, image_box_to_global_match, image_content_rect_or_full, normalize_for_match, tesseract_lines_from_tsv, OcrTextMatch, }; - use leptess::capi::TessPageIteratorLevel_RIL_WORD; - use leptess::{leptonica, tesseract::TessApi}; - use openbitfun_core::agentic::tools::computer_use_host::ComputerScreenshot; - use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; + use openbitfun_agent_tools::computer_use_host::ComputerScreenshot; pub(super) fn read_text(shot: &ComputerScreenshot) -> OpenBitFunResult> { recognize(shot, None) @@ -691,87 +714,23 @@ mod linux_backend { )); } - // Initialize Tesseract API - // Try system default tessdata path first, then common locations - let mut api = match TessApi::new(None, "eng") { - Ok(api) => api, - Err(_) => { - let paths = [ - "/usr/share/tesseract-ocr/5/tessdata/", - "/usr/share/tesseract-ocr/tessdata/", - "/usr/share/tessdata/", - ]; - let mut api = None; - for path in &paths { - if std::path::Path::new(path).exists() { - if let Ok(a) = TessApi::new(Some(path), "eng") { - api = Some(a); - break; - } - } - } - api.ok_or_else(|| OpenBitFunError::tool( - "Linux OCR: Tesseract initialization failed. Please install tesseract-ocr and tesseract-ocr-eng packages, or ensure TESSDATA_PREFIX is set correctly.".to_string() - ))? - } - }; - - let pix = leptonica::pix_read_mem(&shot.bytes).map_err(|e| { - OpenBitFunError::tool(format!( - "Linux OCR: Failed to decode screenshot image with Leptonica: {}", - e - )) - })?; - - api.set_image(&pix); - if api.recognize() != 0 { - return Err(OpenBitFunError::tool( - "Linux OCR: Tesseract recognition failed.".to_string(), - )); - } - + let recognition = super::super::linux_native::recognize(&shot.bytes, query.is_some()) + .map_err(OpenBitFunError::tool)?; let Some(text_query) = query else { - let tsv = api.get_tsv_text(0).map_err(|error| { - OpenBitFunError::tool(format!("Linux OCR: Invalid text encoding: {error}")) - })?; - return Ok(tesseract_lines_from_tsv(shot, &tsv)); + return Ok(tesseract_lines_from_tsv(shot, &recognition.tsv)); }; - - let boxa = api - .get_component_images(TessPageIteratorLevel_RIL_WORD, true) - .ok_or_else(|| { - OpenBitFunError::tool( - "Linux OCR: Tesseract did not return word regions.".to_string(), - ) - })?; - - let word_region_count = boxa.get_n(); + let word_region_count = recognition.region_count; let mut raw_matches = Vec::new(); - - for b in &boxa { - let g = b.get_geometry(); - if g.w <= 0 || g.h <= 0 { - continue; - } - let x1 = g.x; - let y1 = g.y; - let x2 = g.x + g.w; - let y2 = g.y + g.h; - api.set_rectangle(g.x, g.y, g.w, g.h); - let text = match api.get_utf8_text() { - Ok(t) => t, - Err(_) => continue, - }; - let confidence = api.mean_text_conf() as f32 / 100.0; + for word in recognition.words { if let Some(hit) = tesseract_word_to_match( shot, text_query, - &text, - confidence, - x1, - y1, - x2, - y2, + &word.text, + word.confidence, + word.x, + word.y, + word.x + word.width, + word.y + word.height, content_left, content_top, content_width, diff --git a/src/apps/desktop/src/computer_use/share_grants.rs b/src/crates/services/computer-use/src/computer_use/share_grants.rs similarity index 94% rename from src/apps/desktop/src/computer_use/share_grants.rs rename to src/crates/services/computer-use/src/computer_use/share_grants.rs index c20c0bbd82..b98a397893 100644 --- a/src/apps/desktop/src/computer_use/share_grants.rs +++ b/src/crates/services/computer-use/src/computer_use/share_grants.rs @@ -63,7 +63,7 @@ async fn identity(snapshot: &ControlSnapshot) -> Result { Ok(result) } -pub(crate) async fn apply_remembered( +pub async fn apply_remembered( path: PathBuf, snapshot: ControlSnapshot, ) -> Result { @@ -113,10 +113,7 @@ pub(crate) async fn apply_remembered( ) } -pub(crate) async fn remember( - path: PathBuf, - snapshot: ControlSnapshot, -) -> Result { +pub async fn remember(path: PathBuf, snapshot: ControlSnapshot) -> Result { let _operation = PREFERENCES.lock().await; let result = async { let identity = identity(&snapshot).await?; @@ -149,7 +146,7 @@ pub(crate) async fn remember( ) } -pub(crate) async fn list(path: PathBuf) -> Result, String> { +pub async fn list(path: PathBuf) -> Result, String> { tokio::task::spawn_blocking(move || { GrantStore::load(path) .map(|store| store.records().to_vec()) @@ -159,10 +156,7 @@ pub(crate) async fn list(path: PathBuf) -> Result, String> { .map_err(|error| error.to_string())? } -pub(crate) async fn forget( - path: PathBuf, - identity: GrantIdentity, -) -> Result, String> { +pub async fn forget(path: PathBuf, identity: GrantIdentity) -> Result, String> { // Forgetting matching active consent revokes it immediately; disk IO cannot // keep input alive. Unreadable preferences are retained and reported. let snapshot = control_session::snapshot(); diff --git a/src/apps/desktop/src/computer_use/som_overlay.rs b/src/crates/services/computer-use/src/computer_use/som_overlay.rs similarity index 98% rename from src/apps/desktop/src/computer_use/som_overlay.rs rename to src/crates/services/computer-use/src/computer_use/som_overlay.rs index 06a5e74bf1..5f784f7de5 100644 --- a/src/apps/desktop/src/computer_use/som_overlay.rs +++ b/src/crates/services/computer-use/src/computer_use/som_overlay.rs @@ -22,8 +22,8 @@ #![allow(dead_code)] use image::{Rgba, RgbaImage}; -use openbitfun_core::agentic::tools::computer_use_host::InteractiveElement; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::InteractiveElement; use std::io::Cursor; /// Render the SoM overlay onto `jpeg_bytes` and return a fresh JPEG. diff --git a/src/apps/desktop/src/computer_use/terminal_detect.rs b/src/crates/services/computer-use/src/computer_use/terminal_detect.rs similarity index 100% rename from src/apps/desktop/src/computer_use/terminal_detect.rs rename to src/crates/services/computer-use/src/computer_use/terminal_detect.rs diff --git a/src/crates/services/computer-use/src/computer_use/test_support.rs b/src/crates/services/computer-use/src/computer_use/test_support.rs new file mode 100644 index 0000000000..6d77ed0d1b --- /dev/null +++ b/src/crates/services/computer-use/src/computer_use/test_support.rs @@ -0,0 +1,89 @@ +//! Opt-in native fixture assertions; absent from production builds. +pub fn frontmost_pid() -> Option { + super::macos_bg_input::frontmost_pid_macos() +} +pub fn minimize_window(pid: i32, window: u32) -> Result<(), String> { + super::macos_ax_ui::minimize_window_for_fixture(pid, window) +} +pub fn webkit_target_frame(pid: i32, idx: u32) -> (f64, f64, f64, f64) { + let target = super::macos_ax_dump::retained_cached_target(pid, idx).unwrap(); + assert_ne!( + unsafe { super::macos_ax_dispatch::actual_pid(target.reference().0) }.unwrap(), + pid, + "The fixture must exercise a real WebKit subprocess element" + ); + target + .frame_global() + .expect("WebKit button must expose real geometry") +} +pub async fn assert_revoked_writes(owner: &str, pid: i32, native_idx: u32) { + let native_target = super::macos_ax_dump::retained_cached_target(pid, native_idx).unwrap(); + let lease = super::control_session::acquire(owner, "app_click").unwrap(); + let stale_token = super::control_session::capture_token().unwrap(); + super::control_session::stop(Some(owner), "fixture_revoke_queued_input").unwrap(); + drop(lease); + tokio::task::spawn_blocking(move || { + use super::{control_session, macos_ax_dispatch}; + use core_foundation::{base::TCFType, string::CFString}; + assert_eq!( + unsafe { macos_ax_dispatch::actual_pid(native_target.reference().0) }.unwrap(), + pid, + "Revocation must exercise a same-process main-queue message" + ); + control_session::with_token(stale_token, || unsafe { + let action = CFString::new("AXRaise"); + assert_eq!( + macos_ax_dispatch::perform_action( + native_target.reference().0, + action.as_concrete_TypeRef() + ), + -25200, + "Stopped input must be rejected on main before AXRaise" + ); + let attr = CFString::new("AXTitle"); + let value = CFString::new("Revoked write must not arrive"); + assert_eq!( + macos_ax_dispatch::set_input_attribute_value( + native_target.reference().0, + attr.as_concrete_TypeRef(), + value.as_CFTypeRef() + ), + -25200, + "Stopped input must be rejected on main before attribute writes" + ); + }); + }) + .await + .unwrap(); +} +pub fn assert_unbound_window_rejected(owner: &str, pid: i32) { + let mut lease = super::control_session::acquire(owner, "app_click").unwrap(); + let snapshot = super::macos_ax_dump::dump_app_ax(pid, Default::default()).unwrap(); + let foreign = snapshot + .nodes + .iter() + .find(|node| node.title.as_deref() == Some("Unbound semantic action")) + .expect("second-window control missing"); + let target = super::macos_ax_dump::retained_cached_target(pid, foreign.idx).unwrap(); + assert!(super::macos_ax_dump::validate_bound_target(pid, target.reference()).is_err()); + assert!(matches!( + super::macos_ax_write::try_ax_press(target.reference()), + super::macos_ax_write::AxWriteOutcome::Unavailable(_) + )); + lease.complete(); +} +pub fn deactivate_target(pid: i32, window: u32) { + let identity = super::macos_skylight::process_identity(pid).unwrap(); + assert!(super::macos_skylight::set_local_activation( + identity, window, false + )); +} +pub struct ProcessIdentity(super::process_identity::ProcessIdentity); +impl ProcessIdentity { + pub fn read(pid: i32) -> Result { + super::process_identity::ProcessIdentity::read(pid).map(Self) + } + pub fn validate(&self) -> Result<(), String> { + self.0.validate() + } +} diff --git a/src/apps/desktop/src/computer_use/ui_locate_common.rs b/src/crates/services/computer-use/src/computer_use/ui_locate_common.rs similarity index 98% rename from src/apps/desktop/src/computer_use/ui_locate_common.rs rename to src/crates/services/computer-use/src/computer_use/ui_locate_common.rs index 7573637ef3..6d447c3a9e 100644 --- a/src/apps/desktop/src/computer_use/ui_locate_common.rs +++ b/src/crates/services/computer-use/src/computer_use/ui_locate_common.rs @@ -1,10 +1,8 @@ //! Shared validation, filter matching, and global→native pixel mapping for UI locate tools. -use openbitfun_core::agentic::tools::computer_use_host::{ - UiElementLocateQuery, UiElementLocateResult, -}; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; -use screenshots::display_info::DisplayInfo; +use crate::computer_use::displays::DisplayInfo; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{UiElementLocateQuery, UiElementLocateResult}; pub(super) fn validate_query(q: &UiElementLocateQuery) -> OpenBitFunResult<()> { // node_idx alone is enough: it short-circuits BFS via the per-pid AX cache. diff --git a/src/apps/desktop/src/computer_use/windows_ax_shortcuts.rs b/src/crates/services/computer-use/src/computer_use/windows_ax_shortcuts.rs similarity index 98% rename from src/apps/desktop/src/computer_use/windows_ax_shortcuts.rs rename to src/crates/services/computer-use/src/computer_use/windows_ax_shortcuts.rs index b78c6f1da2..9b989caf28 100644 --- a/src/apps/desktop/src/computer_use/windows_ax_shortcuts.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_ax_shortcuts.rs @@ -17,10 +17,10 @@ #![allow(dead_code)] use crate::computer_use::windows_ax_ui::build_updated_cache_with_retry; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ parse_windows_accelerator_display, AppMenuShortcut, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use windows::Win32::Foundation::HWND; use windows::Win32::UI::Accessibility::{ IUIAutomation, IUIAutomationCacheRequest, IUIAutomationElement, IUIAutomationTogglePattern, diff --git a/src/apps/desktop/src/computer_use/windows_ax_ui.rs b/src/crates/services/computer-use/src/computer_use/windows_ax_ui.rs similarity index 99% rename from src/apps/desktop/src/computer_use/windows_ax_ui.rs rename to src/crates/services/computer-use/src/computer_use/windows_ax_ui.rs index d878a0d1bc..3b0014144e 100644 --- a/src/apps/desktop/src/computer_use/windows_ax_ui.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_ax_ui.rs @@ -23,11 +23,11 @@ use super::ax_snapshot_digest::compute_digest; use crate::computer_use::ui_locate_common; -use openbitfun_core::agentic::tools::computer_use_host::{ +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::{ AppInfo, AppStateSnapshot, AxNode, OcrAccessibilityHit, UiElementLocateQuery, UiElementLocateResult, }; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use windows::core::Interface; use windows::Win32::Foundation::HWND; use windows::Win32::System::Com::{ diff --git a/src/apps/desktop/src/computer_use/windows_bg_input.rs b/src/crates/services/computer-use/src/computer_use/windows_bg_input.rs similarity index 99% rename from src/apps/desktop/src/computer_use/windows_bg_input.rs rename to src/crates/services/computer-use/src/computer_use/windows_bg_input.rs index 13c49cec39..0b37ef4d63 100644 --- a/src/apps/desktop/src/computer_use/windows_bg_input.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_bg_input.rs @@ -30,7 +30,7 @@ use std::ffi::c_void; use std::thread::sleep; use std::time::Duration; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use windows::Win32::Foundation::{HWND, LPARAM, POINT, WPARAM}; use windows::Win32::Graphics::Gdi::{ClientToScreen, ScreenToClient}; use windows::Win32::UI::WindowsAndMessaging::{ diff --git a/src/apps/desktop/src/computer_use/windows_capture.rs b/src/crates/services/computer-use/src/computer_use/windows_capture.rs similarity index 96% rename from src/apps/desktop/src/computer_use/windows_capture.rs rename to src/crates/services/computer-use/src/computer_use/windows_capture.rs index d6d5bab170..d3ece41e73 100644 --- a/src/apps/desktop/src/computer_use/windows_capture.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_capture.rs @@ -1,11 +1,11 @@ //! Window-only WGC frames and authoritative DWM geometry. //! There is no desktop/GDI fallback and no encode/decode round trip. -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; pub(super) struct WindowCapture { - pub frame_info: openbitfun_core::agentic::tools::computer_use_host::CaptureFrameInfo, + pub frame_info: openbitfun_agent_tools::computer_use_host::CaptureFrameInfo, pub rgba: Vec, pub origin_x: i32, pub origin_y: i32, diff --git a/src/apps/desktop/src/computer_use/windows_list_apps.rs b/src/crates/services/computer-use/src/computer_use/windows_list_apps.rs similarity index 97% rename from src/apps/desktop/src/computer_use/windows_list_apps.rs rename to src/crates/services/computer-use/src/computer_use/windows_list_apps.rs index a1dad5a5d8..98bb48d21a 100644 --- a/src/apps/desktop/src/computer_use/windows_list_apps.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_list_apps.rs @@ -19,8 +19,8 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::Mutex; -use openbitfun_core::agentic::tools::computer_use_host::{AppInfo, AppWindowInfo}; -use openbitfun_core::util::errors::OpenBitFunResult; +use openbitfun_agent_tools::computer_use_host::error::OpenBitFunResult; +use openbitfun_agent_tools::computer_use_host::{AppInfo, AppWindowInfo}; use windows::core::BOOL; use windows::Win32::Foundation::{HWND, LPARAM, TRUE}; use windows::Win32::UI::WindowsAndMessaging::{ @@ -112,7 +112,7 @@ pub(super) fn list_share_targets() -> Vec Vec { - use openbitfun_core::agentic::tools::computer_use_host::ComputerUseImageGlobalBounds; + use openbitfun_agent_tools::computer_use_host::ComputerUseImageGlobalBounds; // Many windows share a process; open each process once for its name. let mut executables = HashMap::::new(); enumerate_windows(true) @@ -181,7 +181,7 @@ pub(super) fn minimized_window_for_pid(pid: u32) -> Option { /// an application selector, its first minimized titled window). Window-only /// sharing must admit it. Returns whether a window was restored. pub(super) fn restore_window(pid: u32, window: Option) -> OpenBitFunResult { - use openbitfun_core::util::errors::OpenBitFunError; + use openbitfun_agent_tools::computer_use_host::error::OpenBitFunError; use windows::Win32::UI::WindowsAndMessaging::{IsWindow, ShowWindow, SW_RESTORE}; crate::computer_use::control_session::foreground_allowed().map_err(OpenBitFunError::tool)?; let Some(handle) = window.or_else(|| minimized_window_for_pid(pid)) else { diff --git a/src/apps/desktop/src/computer_use/windows_msaa.rs b/src/crates/services/computer-use/src/computer_use/windows_msaa.rs similarity index 99% rename from src/apps/desktop/src/computer_use/windows_msaa.rs rename to src/crates/services/computer-use/src/computer_use/windows_msaa.rs index 4dd47f77ef..5f47041e02 100644 --- a/src/apps/desktop/src/computer_use/windows_msaa.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_msaa.rs @@ -43,7 +43,7 @@ use std::ptr::null_mut; -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use windows::core::Interface; use windows::Win32::Foundation::HWND; use windows::Win32::System::Com::{CoInitializeEx, COINIT_APARTMENTTHREADED}; diff --git a/src/apps/desktop/src/computer_use/windows_overlay.rs b/src/crates/services/computer-use/src/computer_use/windows_overlay.rs similarity index 100% rename from src/apps/desktop/src/computer_use/windows_overlay.rs rename to src/crates/services/computer-use/src/computer_use/windows_overlay.rs diff --git a/src/apps/desktop/src/computer_use/windows_pointer_feedback.rs b/src/crates/services/computer-use/src/computer_use/windows_pointer_feedback.rs similarity index 100% rename from src/apps/desktop/src/computer_use/windows_pointer_feedback.rs rename to src/crates/services/computer-use/src/computer_use/windows_pointer_feedback.rs diff --git a/src/apps/desktop/src/computer_use/windows_wgc_capture.rs b/src/crates/services/computer-use/src/computer_use/windows_wgc_capture.rs similarity index 97% rename from src/apps/desktop/src/computer_use/windows_wgc_capture.rs rename to src/crates/services/computer-use/src/computer_use/windows_wgc_capture.rs index 9474bb8964..a4333879ad 100644 --- a/src/apps/desktop/src/computer_use/windows_wgc_capture.rs +++ b/src/crates/services/computer-use/src/computer_use/windows_wgc_capture.rs @@ -4,7 +4,7 @@ #![allow(dead_code)] -use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use openbitfun_agent_tools::computer_use_host::error::{OpenBitFunError, OpenBitFunResult}; use std::time::{Duration, Instant}; use windows::core::{Interface, HRESULT}; use windows::Graphics::Capture::{ @@ -58,7 +58,7 @@ impl RetainedFrame { Vec, u32, u32, - openbitfun_core::agentic::tools::computer_use_host::CaptureFrameInfo, + openbitfun_agent_tools::computer_use_host::CaptureFrameInfo, )> { (i64::from(width) == i64::from(self.width) && i64::from(height) == i64::from(self.height)) .then(|| { @@ -297,9 +297,9 @@ impl WgcCaptureSession { /// for the next observation, and never read back intermediate frames. fn settle( &mut self, - policy: openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy, - ) -> OpenBitFunResult { - use openbitfun_core::agentic::tools::computer_use_host::{ + policy: openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy, + ) -> OpenBitFunResult { + use openbitfun_agent_tools::computer_use_host::{ app_input_settle_decision, app_input_settle_next_wait_ms, AppInputSettle, AppInputSettleStatus, }; @@ -484,8 +484,8 @@ fn checked_frame_result( fn frame_info( reused: bool, age: Duration, -) -> openbitfun_core::agentic::tools::computer_use_host::CaptureFrameInfo { - openbitfun_core::agentic::tools::computer_use_host::CaptureFrameInfo { +) -> openbitfun_agent_tools::computer_use_host::CaptureFrameInfo { + openbitfun_agent_tools::computer_use_host::CaptureFrameInfo { reused, age_ms: age.as_millis().min(u64::MAX as u128) as u64, } @@ -529,7 +529,7 @@ type CaptureResult = OpenBitFunResult<( Vec, u32, u32, - openbitfun_core::agentic::tools::computer_use_host::CaptureFrameInfo, + openbitfun_agent_tools::computer_use_host::CaptureFrameInfo, )>; enum CaptureCommand { Ensure( @@ -545,7 +545,7 @@ enum CaptureCommand { Settle( usize, crate::computer_use::control_session::ControlToken, - openbitfun_core::agentic::tools::computer_use_host::AppInputSettlePolicy, + openbitfun_agent_tools::computer_use_host::AppInputSettlePolicy, std::sync::mpsc::SyncSender, ), Snapshot( @@ -556,8 +556,7 @@ enum CaptureCommand { ), Stop(std::sync::mpsc::SyncSender<()>), } -type SettleResult = - OpenBitFunResult; +type SettleResult = OpenBitFunResult; // A generation change must not retain a prior owner's native capture session. fn ensure_stream( @@ -662,7 +661,7 @@ fn capture_worker() -> &'static std::sync::mpsc::Sender { ensure_stream(&mut active, handle)?.settle(policy) }) } else { - Ok(openbitfun_core::agentic::tools::computer_use_host::AppInputSettle::unavailable( + Ok(openbitfun_agent_tools::computer_use_host::AppInputSettle::unavailable( "No live window stream; the observation was taken without waiting for repaint", )) }; @@ -741,7 +740,7 @@ pub(super) fn snapshot_popup(hwnd: HWND, popup: HWND) -> OpenBitFunResult<(Vec SettleResult { crate::computer_use::control_session::capture_allowed().map_err(OpenBitFunError::service)?; let (tx, rx) = std::sync::mpsc::sync_channel(1); diff --git a/src/apps/desktop/src/computer_use/windows_window_target.rs b/src/crates/services/computer-use/src/computer_use/windows_window_target.rs similarity index 100% rename from src/apps/desktop/src/computer_use/windows_window_target.rs rename to src/crates/services/computer-use/src/computer_use/windows_window_target.rs diff --git a/src/apps/desktop/src/computer_use/windows_window_target_tests.rs b/src/crates/services/computer-use/src/computer_use/windows_window_target_tests.rs similarity index 100% rename from src/apps/desktop/src/computer_use/windows_window_target_tests.rs rename to src/crates/services/computer-use/src/computer_use/windows_window_target_tests.rs diff --git a/src/crates/services/computer-use/src/host_runtime.rs b/src/crates/services/computer-use/src/host_runtime.rs new file mode 100644 index 0000000000..9736f73677 --- /dev/null +++ b/src/crates/services/computer-use/src/host_runtime.rs @@ -0,0 +1,150 @@ +//! Host lifecycle support without a GUI framework. Native resources always +//! belong to the executing process and its graphical login session. +use std::thread::JoinHandle; + +/// Explain whether this process can attach to its own graphical session. +/// This does not request OS permissions, capture pixels, or activate an app. +pub fn availability() -> Result<(), String> { + if std::env::var_os("SSH_CONNECTION").is_some() || std::env::var_os("SSH_TTY").is_some() { + return Err("[GUI_SESSION_UNAVAILABLE] Computer Use requires a local graphical login session; SSH sessions cannot control another desktop.".into()); + } + platform_availability() +} + +#[cfg(target_os = "linux")] +fn platform_availability() -> Result<(), String> { + linux_session_available( + std::env::var_os("DISPLAY").is_some_and(|s| !s.is_empty()), + std::env::var_os("WAYLAND_DISPLAY").is_some_and(|s| !s.is_empty()), + std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some_and(|s| !s.is_empty()), + ) +} + +#[cfg(any(target_os = "linux", test))] +fn linux_session_available(x11: bool, wayland: bool, session_bus: bool) -> Result<(), String> { + if (x11 || wayland) && session_bus { + Ok(()) + } else { + Err("[GUI_SESSION_UNAVAILABLE] Linux Computer Use requires an X11 or Wayland session and its D-Bus session bus. Screen capture and foreground input additionally require the desktop portal.".into()) + } +} + +#[cfg(target_os = "macos")] +fn platform_availability() -> Result<(), String> { + use core_foundation::base::CFRelease; + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGSessionCopyCurrentDictionary() -> *const std::ffi::c_void; + } + // Copy follows the CF ownership rule. No capture or permission prompting. + let session = unsafe { CGSessionCopyCurrentDictionary() }; + if session.is_null() { + return Err( + "[GUI_SESSION_UNAVAILABLE] macOS Computer Use requires a graphical login session." + .into(), + ); + } + unsafe { CFRelease(session) }; + Ok(()) +} + +#[cfg(target_os = "windows")] +fn platform_availability() -> Result<(), String> { + use windows::Win32::System::StationsAndDesktops::{ + GetProcessWindowStation, GetUserObjectInformationW, UOI_FLAGS, USEROBJECTFLAGS, + }; + use windows::Win32::{Foundation::HANDLE, UI::WindowsAndMessaging::WSF_VISIBLE}; + // A service's invisible window station is not an interactive desktop. + let station = unsafe { GetProcessWindowStation() }.map_err(|error| { + format!("[GUI_SESSION_UNAVAILABLE] Cannot inspect the process window station: {error}") + })?; + let mut flags = USEROBJECTFLAGS::default(); + unsafe { + GetUserObjectInformationW( + HANDLE(station.0), + UOI_FLAGS, + Some((&mut flags as *mut USEROBJECTFLAGS).cast()), + std::mem::size_of::() as u32, + None, + ) + } + .map_err(|error| { + format!("[GUI_SESSION_UNAVAILABLE] Cannot inspect the process window station: {error}") + })?; + if flags.dwFlags & WSF_VISIBLE as u32 != 0 { + Ok(()) + } else { + Err("[GUI_SESSION_UNAVAILABLE] Windows Computer Use requires an interactive user window station; services and session 0 cannot control a desktop.".into()) + } +} + +#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] +fn platform_availability() -> Result<(), String> { + Err("[GUI_SESSION_UNAVAILABLE] No native Computer Use provider for this platform.".into()) +} + +/// CLI runs its existing async Runtime on a worker. macOS additionally needs +/// its real main dispatch/run loop for AppKit, capture and native input. +/// Windows owns native message/COM workers; Linux uses its async portal/AT-SPI IO. +pub fn join(worker: JoinHandle) -> std::thread::Result { + #[cfg(target_os = "macos")] + { + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { + static kCFRunLoopDefaultMode: *const std::ffi::c_void; + fn CFRunLoopRunInMode( + mode: *const std::ffi::c_void, + seconds: f64, + return_after_source: bool, + ) -> i32; + } + while !worker.is_finished() { + unsafe { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true); + } + // The CF loop can return immediately before any source exists. + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + worker.join() +} + +/// Initialize the framework owned by a CLI graphical host, without activation. +/// Desktop already initializes AppKit through its own host lifecycle. +pub fn initialize() -> Result<(), String> { + availability()?; + #[cfg(target_os = "macos")] + dispatch::Queue::main().exec_sync(|| { + let app: *mut objc2::runtime::AnyObject = + unsafe { objc2::msg_send![objc2::class!(NSApplication), sharedApplication] }; + let _: bool = unsafe { objc2::msg_send![app, setActivationPolicy: 2isize] }; + }); + Ok(()) +} + +/// Drop on the Runtime worker before exiting, while main still services cleanup. +pub struct StopOnExit; +impl Drop for StopOnExit { + fn drop(&mut self) { + let _ = crate::control_session::stop(None, "host_shutdown"); + } +} + +#[cfg(test)] +mod tests { + #[test] + fn linux_headless_and_missing_bus_do_not_become_local_fallbacks() { + for (x11, wayland, bus) in [ + (false, false, false), + (false, false, true), + (true, false, false), + (false, true, false), + ] { + assert!(super::linux_session_available(x11, wayland, bus) + .unwrap_err() + .contains("GUI_SESSION_UNAVAILABLE")); + } + assert!(super::linux_session_available(true, false, true).is_ok()); + assert!(super::linux_session_available(false, true, true).is_ok()); + } +} diff --git a/src/crates/services/computer-use/src/lib.rs b/src/crates/services/computer-use/src/lib.rs new file mode 100644 index 0000000000..a7780a1ddc --- /dev/null +++ b/src/crates/services/computer-use/src/lib.rs @@ -0,0 +1,17 @@ +//! Native Computer Use services for Windows, macOS and Linux. +//! Product hosts own runtime/configuration wiring; this crate owns OS resources. +mod computer_use; +pub use computer_use::{ + control_session, grants, permissions, share_grants, share_targets, shared_preview, + NativeComputerUseHost, +}; +static OCR_DEBUG_DIRECTORY: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Set the host-owned diagnostic destination before starting native work. +pub fn set_ocr_debug_directory(path: std::path::PathBuf) { + let _ = OCR_DEBUG_DIRECTORY.set(path); +} + +#[cfg(all(feature = "test-support", target_os = "macos"))] +pub use computer_use::test_support; +pub mod host_runtime;