Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(e2e): vendored patch 驱动原生 frame,打通跨域 iframe

hairyfdbe573549fbb
diff --git a/eslint.config.mjs b/eslint.config.mjs
index a24846cc..01d0e0a8 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -9,6 +9,9 @@ export default antfu({
'AGENTS.*',
'docs',
'archive',
+ // vendored 第三方 crate(含其 README/permissions 产物):格式由上游决定,
+ // 只保留本仓对其的 patch 说明(PATCH.md 由人读,不参与 lint)
+ 'src-tauri/vendor',
// genapi 产物:格式由生成器(prettier 默认)决定,不由项目 eslint 规约
'packages/*/src/client/apis/index.ts',
'packages/*/src/client/apis/index.type.ts',
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f3a53b89..7e5cb5de 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -5226,8 +5226,6 @@ dependencies = [
[[package]]
name = "tauri-plugin-wdio-webdriver"
version = "1.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52c5e97428174a52b7f4357bbc4535fcce52c6a06c8ee7a379502f7cda1b6045"
dependencies = [
"async-trait",
"axum",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4429863e..4252729b 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -113,6 +113,15 @@ libc = "0.2"
[target.'cfg(target_os = "linux")'.dependencies]
tray-icon = { version = "0.25", default-features = false, features = [ "ksni" ] }
+# E2E 基础设施:上游 `tauri-plugin-wdio-webdriver` 的帧上下文靠 JS 模拟
+# (`frame.contentWindow.eval`)。壳层是 `tauri://localhost`,内嵌 dsh 是
+# `http://127.0.0.1:<port>`,跨域下 `contentDocument` 为 null、proxy 无 `eval`,
+# 一切帧内脚本必然超时。本地副本改为 WebView2 原生 `ICoreWebView2Frame2::ExecuteScript`
+# (引擎按帧路由,不受同源策略约束)。改动仅限 Windows 路径,其余与上游 1.4.0 一致;
+# 上游支持后删除 vendor 与本节,详见 vendor 目录内 README。
+[patch.crates-io]
+tauri-plugin-wdio-webdriver = { path = "vendor/tauri-plugin-wdio-webdriver" }
+
[target.'cfg(windows)'.dependencies]
rfd = "0.16"
webview2-com = "0.38"
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/Cargo.toml b/src-tauri/vendor/tauri-plugin-wdio-webdriver/Cargo.toml
new file mode 100644
index 00000000..e86f1119
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/Cargo.toml
@@ -0,0 +1,164 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.77"
+name = "tauri-plugin-wdio-webdriver"
+version = "1.4.0"
+authors = ["You"]
+build = "build.rs"
+links = "tauri-plugin-wdio-webdriver"
+exclude = ["/examples"]
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Embedded WebDriver server for WDIO Tauri testing"
+readme = "README.md"
+keywords = [
+ "tauri",
+ "webdriver",
+ "wdio",
+ "testing",
+ "automation",
+]
+categories = [
+ "development-tools::testing",
+ "gui",
+]
+license = "MIT"
+repository = "https://github.com/webdriverio/desktop-mobile"
+
+[lib]
+name = "tauri_plugin_wdio_webdriver"
+path = "src/lib.rs"
+
+[dependencies.async-trait]
+version = "0.1"
+
+[dependencies.axum]
+version = "0.8"
+
+[dependencies.base64]
+version = "0.22"
+
+[dependencies.serde]
+version = "1.0"
+features = ["derive"]
+
+[dependencies.serde_json]
+version = "1"
+
+[dependencies.tauri]
+version = "2.10.0"
+
+[dependencies.tempfile]
+version = "3"
+
+[dependencies.thiserror]
+version = "2"
+
+[dependencies.tokio]
+version = "1"
+features = [
+ "rt-multi-thread",
+ "sync",
+ "net",
+ "time",
+ "macros",
+]
+
+[dependencies.tracing]
+version = "0.1"
+
+[dependencies.uuid]
+version = "1"
+features = ["v4"]
+
+[build-dependencies.tauri-plugin]
+version = "2.5.3"
+features = ["build"]
+
+[target.'cfg(target_os = "linux")'.dependencies.cairo-rs]
+version = "0.18"
+features = ["png"]
+
+[target.'cfg(target_os = "linux")'.dependencies.glib]
+version = "0.21"
+
+[target.'cfg(target_os = "linux")'.dependencies.gtk]
+version = "0.18"
+
+[target.'cfg(target_os = "linux")'.dependencies.javascriptcore-rs]
+version = "1.1"
+
+[target.'cfg(target_os = "linux")'.dependencies.webkit2gtk]
+version = "2.0"
+
+[target.'cfg(target_os = "macos")'.dependencies.block2]
+version = "0.6"
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2]
+version = "0.6"
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit]
+version = "0.3"
+features = [
+ "NSImage",
+ "NSImageRep",
+ "NSBitmapImageRep",
+]
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation]
+version = "0.3"
+features = [
+ "NSString",
+ "NSData",
+ "NSError",
+ "NSArray",
+ "NSDictionary",
+ "NSTimer",
+ "NSRunLoop",
+ "NSDate",
+ "block2",
+]
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2-web-kit]
+version = "0.3"
+features = [
+ "WKWebView",
+ "WKWebViewConfiguration",
+ "WKSnapshotConfiguration",
+ "WKUIDelegate",
+ "WKPDFConfiguration",
+ "WKFrameInfo",
+ "WKContentWorld",
+ "WKUserContentController",
+ "WKScriptMessage",
+ "WKScriptMessageHandler",
+ "block2",
+ "objc2-app-kit",
+]
+
+[target.'cfg(target_os = "windows")'.dependencies.webview2-com]
+version = "0.38"
+
+[target.'cfg(target_os = "windows")'.dependencies.windows]
+version = "0.61"
+features = [
+ "Win32_System_Com",
+ "Win32_System_WinRT",
+]
+
+[target.'cfg(target_os = "windows")'.dependencies.windows-core]
+version = "0.61"
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/LICENSE b/src-tauri/vendor/tauri-plugin-wdio-webdriver/LICENSE
new file mode 100644
index 00000000..1e6bd77a
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 WebdriverIO Community
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/PATCH.md b/src-tauri/vendor/tauri-plugin-wdio-webdriver/PATCH.md
new file mode 100644
index 00000000..de227824
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/PATCH.md
@@ -0,0 +1,51 @@
+# Vendored patch: cross-origin frame execution (Windows)
+
+`tauri-plugin-wdio-webdriver` **1.4.0**, copied verbatim from crates.io and wired in via
+`[patch.crates-io]` in `src-tauri/Cargo.toml`. Exactly one behaviour is changed, and only
+under `#[cfg(target_os = "windows")]`. Everything else is upstream and should be kept that
+way, so dropping this directory is a one-line revert when upstream ships the feature.
+
+## Why
+
+Upstream represents a frame context by evaluating the script inside `frame.contentWindow`
+(`wrap_script_for_frame_context()` in `src/platform/executor.rs`). That only works
+same-origin. Our shell is `tauri://localhost` and the embedded harness is served from
+`http://127.0.0.1:<port>`, so `contentDocument` is `null` and the injected `ctx.eval(...)`
+never runs:
+
+```
+WebDriverError: Script execution timed out when running execute/sync
+```
+
+`switchFrame()` itself resolves (validation only checks the tag name), so the failure
+surfaces one call later — on the first `execute` inside the frame.
+
+## What changed
+
+- `src/platform/windows.rs`
+ - `FrameRegistry` — captures `ICoreWebView2Frame` handles from `FrameCreated`
+ (`ICoreWebView2_4::add_FrameCreated`), keyed by window label, in the same order as
+ `document.querySelectorAll('iframe, frame')` so indices line up with upstream's wrapper.
+ Holds one COM reference per frame behind `SendableComPtr`.
+ - `register_frame_handler()` — registered from the existing `register_webview_handlers()`
+ hook (`on_webview_ready`).
+ - `WindowsExecutor::evaluate_js()` now dispatches:
+ - empty frame context → top-level, unchanged;
+ - depth-1 frame with a captured handle → `ICoreWebView2Frame2::ExecuteScript`, which the
+ engine routes to the frame irrespective of origin;
+ - anything else (nested frame, or handle not yet captured) → the upstream JS wrapper,
+ unchanged.
+ - `evaluate_js_inner()` split into `evaluate_js_top_level()` (the original body minus the
+ wrapper) and `evaluate_js_in_frame()`.
+- `src/platform/mod.rs` — re-export `FrameRegistry`.
+- `src/lib.rs` — `app.manage(FrameRegistry::default())`.
+
+There is no behaviour change when `frame_context` is empty, which is every non-frame test.
+
+## Removal
+
+Delete this directory and the `[patch.crates-io]` block plus its comment in
+`src-tauri/Cargo.toml`. `Cargo.lock` regains the `source` + `checksum` lines for the
+registry copy.
+
+Upstream issue: pending.
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/README.md b/src-tauri/vendor/tauri-plugin-wdio-webdriver/README.md
new file mode 100644
index 00000000..319934ec
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/README.md
@@ -0,0 +1,298 @@
+# tauri-plugin-wdio-webdriver
+
+> **This copy is vendored and patched.** See [`PATCH.md`](./PATCH.md). It is
+> `tauri-plugin-wdio-webdriver` 1.4.0 from crates.io with one E2E-only change to the
+> Windows frame-execution path; everything else is upstream and must stay that way so the
+> patch is cheap to drop when upstream supports cross-origin frames.
+
+[![Crates.io](https://img.shields.io/crates/v/tauri-plugin-wdio-webdriver.svg)](https://crates.io/crates/tauri-plugin-wdio-webdriver)
+[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
+
+An embedded W3C WebDriver server for Tauri applications, providing the **embedded** driver provider for `@wdio/tauri-service`. This plugin embeds a WebDriver HTTP server directly inside your Tauri app, eliminating the need for external drivers like `tauri-driver` or CrabNebula.
+
+This is a fork of [`Choochmeque/tauri-plugin-webdriver`](https://github.com/Choochmeque/tauri-plugin-webdriver) with changes for WebdriverIO compatibility.
+
+## When to Use This Plugin
+
+This plugin is required when using the `'embedded'` driver provider with `@wdio/tauri-service`:
+
+- **macOS** — auto-detected, no configuration needed
+- **Windows/Linux** — set `driverProvider: 'embedded'` or `TAURI_WEBDRIVER_PORT` env var
+
+It is **not needed** if you use the `'official'` or `'crabnebula'` driver providers.
+
+## Features
+
+- **Full W3C WebDriver compliance** — 47 endpoints implementing the W3C WebDriver specification
+- **Native platform integration** — Uses native WebView APIs (WKWebView, WebView2, WebKitGTK)
+- **Zero configuration** — Add the plugin, and `@wdio/tauri-service` handles the rest
+- **No external drivers** — No need to install `tauri-driver`, `msedgedriver`, or `webkit2gtk-driver`
+
+### Supported Platforms
+
+| Platform | Status | Backend |
+|----------|--------|---------|
+| macOS | Full support | WKWebView native APIs |
+| Windows | Full support | WebView2 native APIs |
+| Linux | Full support | WebKitGTK native APIs |
+
+## Installation
+
+> **Warning**: This plugin exposes automation capabilities via HTTP. Never include it in production builds.
+
+Add to your `Cargo.toml` as a dev/test-only dependency:
+
+```toml
+[target.'cfg(debug_assertions)'.dependencies]
+tauri-plugin-wdio-webdriver = "1"
+```
+
+Or use a feature flag for more control:
+
+```toml
+[features]
+webdriver = ["tauri-plugin-wdio-webdriver"]
+
+[dependencies]
+tauri-plugin-wdio-webdriver = { version = "1", optional = true }
+```
+
+## Usage with @wdio/tauri-service
+
+### 1. Register the plugin
+
+Use conditional compilation to exclude from release builds:
+
+```rust
+fn main() {
+ let builder = tauri::Builder::default();
+
+ #[cfg(debug_assertions)]
+ let builder = builder.plugin(tauri_plugin_wdio_webdriver::init());
+
+ builder
+ .run(tauri::generate_context!())
+ .expect("error while running tauri application");
+}
+```
+
+### 2. Configure WebdriverIO
+
+```typescript
+// wdio.conf.ts
+export const config = {
+ services: [['@wdio/tauri-service', {
+ driverProvider: 'embedded', // Auto-detected on macOS
+ }]],
+
+ capabilities: [{
+ browserName: 'tauri',
+ 'tauri:options': {
+ application: './src-tauri/target/release/my-app',
+ },
+ }],
+};
+```
+
+The service spawns your Tauri app with `TAURI_WEBDRIVER_PORT` set, the plugin starts the WebDriver server on that port, and WebdriverIO connects directly — no external driver process needed.
+
+### 3. Add permissions
+
+Add to your `src-tauri/capabilities/default.json`:
+
+```json
+{
+ "permissions": [
+ "wdio-webdriver:default"
+ ]
+}
+```
+
+## Standalone Usage
+
+The plugin also works with any W3C WebDriver client independently of `@wdio/tauri-service`:
+
+```bash
+# Start your app with the WebDriver port configured
+TAURI_WEBDRIVER_PORT=4445 cargo tauri dev
+```
+
+Then connect with any client:
+
+```javascript
+// WebdriverIO
+const browser = await remote({
+ hostname: '127.0.0.1',
+ port: 4445,
+ capabilities: {}
+});
+```
+
+```python
+# Selenium
+driver = webdriver.Remote(
+ command_executor="http://127.0.0.1:4445",
+ options=webdriver.ChromeOptions()
+)
+```
+
+## Configuration
+
+The WebDriver server runs on port `4445` by default, bound to `127.0.0.1`.
+
+### Custom Port
+
+**1. Environment variable** (used by `@wdio/tauri-service` automatically):
+
+```bash
+TAURI_WEBDRIVER_PORT=9515 cargo tauri dev
+```
+
+**2. Programmatically:**
+
+```rust
+#[cfg(debug_assertions)]
+let builder = builder.plugin(tauri_plugin_wdio_webdriver::init_with_port(9515));
+```
+
+Port resolution order:
+1. `init_with_port(port)` — uses the specified port (ignores env var)
+2. `init()` — checks `TAURI_WEBDRIVER_PORT` env var, falls back to 4445
+
+## W3C WebDriver Endpoints
+
+### Session Management
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/status` | Server status |
+| POST | `/session` | Create session |
+| DELETE | `/session/{id}` | Delete session |
+
+### Timeouts
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/timeouts` | Get timeouts |
+| POST | `/session/{id}/timeouts` | Set timeouts |
+
+### Navigation
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/url` | Get current URL |
+| POST | `/session/{id}/url` | Navigate to URL |
+| GET | `/session/{id}/title` | Get page title |
+| POST | `/session/{id}/back` | Go back |
+| POST | `/session/{id}/forward` | Go forward |
+| POST | `/session/{id}/refresh` | Refresh page |
+
+### Elements
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/session/{id}/element` | Find element |
+| POST | `/session/{id}/elements` | Find elements |
+| GET | `/session/{id}/element/active` | Get active element |
+| POST | `/session/{id}/element/{eid}/element` | Find from element |
+| POST | `/session/{id}/element/{eid}/elements` | Find all from element |
+| POST | `/session/{id}/element/{eid}/click` | Click element |
+| POST | `/session/{id}/element/{eid}/clear` | Clear element |
+| POST | `/session/{id}/element/{eid}/value` | Send keys |
+| GET | `/session/{id}/element/{eid}/text` | Get text |
+| GET | `/session/{id}/element/{eid}/name` | Get tag name |
+| GET | `/session/{id}/element/{eid}/attribute/{name}` | Get attribute |
+| GET | `/session/{id}/element/{eid}/property/{name}` | Get property |
+| GET | `/session/{id}/element/{eid}/css/{prop}` | Get CSS value |
+| GET | `/session/{id}/element/{eid}/rect` | Get rect |
+| GET | `/session/{id}/element/{eid}/selected` | Is selected |
+| GET | `/session/{id}/element/{eid}/displayed` | Is displayed |
+| GET | `/session/{id}/element/{eid}/enabled` | Is enabled |
+| GET | `/session/{id}/element/{eid}/computedrole` | Get ARIA role |
+| GET | `/session/{id}/element/{eid}/computedlabel` | Get ARIA label |
+| GET | `/session/{id}/element/{eid}/screenshot` | Element screenshot |
+
+### Shadow DOM
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/element/{eid}/shadow` | Get shadow root |
+| POST | `/session/{id}/shadow/{sid}/element` | Find in shadow |
+| POST | `/session/{id}/shadow/{sid}/elements` | Find all in shadow |
+
+### Windows
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/window` | Get window handle |
+| POST | `/session/{id}/window` | Switch to window |
+| DELETE | `/session/{id}/window` | Close window |
+| POST | `/session/{id}/window/new` | New window |
+| GET | `/session/{id}/window/handles` | Get all handles |
+| GET | `/session/{id}/window/rect` | Get window rect |
+| POST | `/session/{id}/window/rect` | Set window rect |
+| POST | `/session/{id}/window/maximize` | Maximize |
+| POST | `/session/{id}/window/minimize` | Minimize |
+| POST | `/session/{id}/window/fullscreen` | Fullscreen |
+
+`Get Window Rect` and `Set Window Rect` use CSS pixels, as required by the
+[W3C WebDriver Window Rect commands](https://www.w3.org/TR/webdriver2/#set-window-rect).
+On desktop platforms, the plugin converts Tauri's physical outer-window bounds
+using the window's current display scale factor. Position changes are completed
+before a requested size is applied, including moves between displays.
+
+### Frames
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/session/{id}/frame` | Switch to frame |
+| POST | `/session/{id}/frame/parent` | Switch to parent |
+
+### Scripts
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/session/{id}/execute/sync` | Execute sync script |
+| POST | `/session/{id}/execute/async` | Execute async script |
+
+### Cookies
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/cookie` | Get all cookies |
+| POST | `/session/{id}/cookie` | Add cookie |
+| DELETE | `/session/{id}/cookie` | Delete all cookies |
+| GET | `/session/{id}/cookie/{name}` | Get cookie |
+| DELETE | `/session/{id}/cookie/{name}` | Delete cookie |
+
+### Alerts
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/session/{id}/alert/dismiss` | Dismiss alert |
+| POST | `/session/{id}/alert/accept` | Accept alert |
+| GET | `/session/{id}/alert/text` | Get alert text |
+| POST | `/session/{id}/alert/text` | Send alert text |
+
+### Actions
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/session/{id}/actions` | Perform actions |
+| DELETE | `/session/{id}/actions` | Release actions |
+
+### Document
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/session/{id}/source` | Get page source |
+| GET | `/session/{id}/screenshot` | Take screenshot |
+| POST | `/session/{id}/print` | Print to PDF |
+
+## Locator Strategies
+
+| Strategy | Example |
+|----------|---------|
+| `css selector` | `#id`, `.class`, `div > p` |
+| `xpath` | `//div[@id='test']` |
+| `tag name` | `button`, `input` |
+| `link text` | Exact link text match |
+| `partial link text` | Partial link text match |
+
+## See Also
+
+- [Plugin Setup Guide](../tauri-service/docs/plugin-setup.md) — Full setup instructions including this plugin
+- [Platform Support](../tauri-service/docs/platform-support.md) — Per-platform details
+- [Upstream repository](https://github.com/Choochmeque/tauri-plugin-webdriver) — Original project
+
+## License
+
+MIT
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/build.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/build.rs
new file mode 100644
index 00000000..fd9aab60
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/build.rs
@@ -0,0 +1,8 @@
+const COMMANDS: &[&str] = &[];
+
+fn main() {
+ tauri_plugin::Builder::new(COMMANDS)
+ .android_path("android")
+ .ios_path("ios")
+ .build();
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/autogenerated/reference.md b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/autogenerated/reference.md
new file mode 100644
index 00000000..50c0f402
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/autogenerated/reference.md
@@ -0,0 +1,13 @@
+## Default Permission
+
+Default permissions for the plugin
+
+## Permission Table
+
+<table>
+<tr>
+<th>Identifier</th>
+<th>Description</th>
+</tr>
+
+</table>
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/default.toml b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/default.toml
new file mode 100644
index 00000000..8ea0a5f9
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/default.toml
@@ -0,0 +1,3 @@
+[default]
+description = "Default permissions for the plugin"
+permissions = []
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/schemas/schema.json b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/schemas/schema.json
new file mode 100644
index 00000000..c801ea4c
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/permissions/schemas/schema.json
@@ -0,0 +1,306 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Default permissions for the plugin",
+ "type": "string",
+ "const": "default",
+ "markdownDescription": "Default permissions for the plugin"
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/desktop.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/desktop.rs
new file mode 100644
index 00000000..0fd16cb7
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/desktop.rs
@@ -0,0 +1,12 @@
+use serde::de::DeserializeOwned;
+use tauri::{plugin::PluginApi, AppHandle, Runtime};
+
+pub fn init<R: Runtime, C: DeserializeOwned>(
+ app: &AppHandle<R>,
+ _api: PluginApi<R, C>,
+) -> Webdriver<R> {
+ Webdriver(app.clone())
+}
+
+/// Access to the webdriver APIs.
+pub struct Webdriver<R: Runtime>(AppHandle<R>);
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/error.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/error.rs
new file mode 100644
index 00000000..177e8c26
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/error.rs
@@ -0,0 +1,21 @@
+use serde::{ser::Serializer, Serialize};
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+ #[cfg(mobile)]
+ #[error(transparent)]
+ PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
+}
+
+impl Serialize for Error {
+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_str(self.to_string().as_ref())
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/eval_channel.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/eval_channel.rs
new file mode 100644
index 00000000..02e1f398
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/eval_channel.rs
@@ -0,0 +1,45 @@
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+use serde_json::Value;
+use tokio::sync::oneshot;
+
+/// Correlates DirectEval results the webview reports back out-of-band, keyed by id.
+///
+/// The macOS DirectEval path runs its script via `callAsyncJavaScript` to keep the run loop pumping
+/// (so the app's own `core.invoke` IPC resolves on a headless runner) but must NOT read the result
+/// from that call's completion handler — macOS 26.4's WebKit reclaims it intermittently. Instead the
+/// script posts `{ id, result }` to a `WKScriptMessageHandler`, which calls `complete` to wake the
+/// executor awaiting `register`. Mirrors the Windows `AsyncScriptState` native-handler pattern.
+/// Removable once the upstream reclaim is resolved:
+/// https://github.com/webdriverio/desktop-mobile/issues/540
+#[derive(Default)]
+pub struct EvalResultRegistry {
+ pending: Mutex<HashMap<String, oneshot::Sender<Value>>>,
+}
+
+impl EvalResultRegistry {
+ pub fn register(&self, id: String) -> oneshot::Receiver<Value> {
+ let (tx, rx) = oneshot::channel();
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.insert(id, tx);
+ }
+ rx
+ }
+
+ /// No-op if `id` is unknown or already completed, so a duplicate or late report is harmless.
+ pub fn complete(&self, id: &str, result: Value) {
+ if let Ok(mut pending) = self.pending.lock() {
+ if let Some(tx) = pending.remove(id) {
+ let _ = tx.send(result);
+ }
+ }
+ }
+
+ /// Drop a pending registration (e.g. on timeout) so its sender doesn't leak.
+ pub fn cancel(&self, id: &str) {
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.remove(id);
+ }
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/lib.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/lib.rs
new file mode 100644
index 00000000..34ce2d11
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/lib.rs
@@ -0,0 +1,87 @@
+use tauri::{
+ plugin::{Builder, TauriPlugin},
+ Manager, Runtime,
+};
+
+#[cfg(desktop)]
+mod desktop;
+#[cfg(mobile)]
+mod mobile;
+
+mod error;
+#[cfg(target_os = "macos")]
+mod eval_channel;
+mod platform;
+mod server;
+mod webdriver;
+
+pub use error::{Error, Result};
+
+/// Default port for the `WebDriver` HTTP server
+pub const DEFAULT_PORT: u16 = 4445;
+
+/// Environment variable name for configuring the port
+pub const PORT_ENV_VAR: &str = "TAURI_WEBDRIVER_PORT";
+
+/// Initializes the plugin with default settings.
+///
+/// The port is determined in the following order:
+/// 1. `TAURI_WEBDRIVER_PORT` environment variable (if set and valid)
+/// 2. Default port (4445)
+#[must_use]
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ let port = std::env::var(PORT_ENV_VAR)
+ .ok()
+ .and_then(|s| s.parse::<u16>().ok())
+ .unwrap_or(DEFAULT_PORT);
+
+ init_with_port(port)
+}
+
+/// Initializes the plugin with a custom port.
+///
+/// This ignores the `TAURI_WEBDRIVER_PORT` environment variable.
+#[must_use]
+pub fn init_with_port<R: Runtime>(port: u16) -> TauriPlugin<R> {
+ Builder::new("wdio-webdriver")
+ .setup(move |app, api| {
+ #[cfg(mobile)]
+ let webdriver = mobile::init(app, api)?;
+ #[cfg(desktop)]
+ let webdriver = desktop::init(app, api);
+ app.manage(webdriver);
+
+ // Manage async script state for native message handlers (Windows only)
+ #[cfg(target_os = "windows")]
+ app.manage(platform::AsyncScriptState::default());
+ // Serialize concurrent ExecuteScript calls per webview (Windows only)
+ #[cfg(target_os = "windows")]
+ app.manage(platform::ScriptExecutionLocks::default());
+ // Native frame handles captured from FrameCreated (Windows only)
+ #[cfg(target_os = "windows")]
+ app.manage(platform::FrameRegistry::default());
+
+ // Manage per-window alert state
+ app.manage(platform::AlertStateManager::default());
+
+ // Arc so the (non-generic) objc2 message handler can hold its own clone; see eval_channel.
+ #[cfg(target_os = "macos")]
+ app.manage(std::sync::Arc::new(eval_channel::EvalResultRegistry::default()));
+
+ // Start the macOS headless run-loop pump early (before any webview loads); Once-guarded,
+ // so the on_webview_ready registration remains a fallback. See #540.
+ #[cfg(target_os = "macos")]
+ platform::start_runloop_pump_early(app.app_handle());
+
+ // Start the WebDriver HTTP server
+ let app_handle = app.app_handle().clone();
+ server::start(app_handle, port);
+ tracing::info!("WDIO WebDriver plugin initialized on port {port}");
+
+ Ok(())
+ })
+ .on_webview_ready(|webview| {
+ platform::register_webview_handlers(&webview);
+ })
+ .build()
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/mobile.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/mobile.rs
new file mode 100644
index 00000000..62866ebb
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/mobile.rs
@@ -0,0 +1,72 @@
+use serde::de::DeserializeOwned;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::{
+ plugin::{PluginApi, PluginHandle},
+ AppHandle, Runtime,
+};
+
+#[cfg(target_os = "ios")]
+tauri::ios_plugin_binding!(init_plugin_webdriver);
+
+// initializes the Kotlin or Swift plugin classes
+pub fn init<R: Runtime, C: DeserializeOwned>(
+ _app: &AppHandle<R>,
+ api: PluginApi<R, C>,
+) -> crate::Result<Webdriver<R>> {
+ #[cfg(target_os = "android")]
+ let handle = api.register_android_plugin("com.plugin.webdriver", "WebDriverPlugin")?;
+ #[cfg(target_os = "ios")]
+ let handle = api.register_ios_plugin(init_plugin_webdriver)?;
+ Ok(Webdriver(handle))
+}
+
+/// Access to the webdriver APIs.
+pub struct Webdriver<R: Runtime>(pub PluginHandle<R>);
+
+// =============================================================================
+// Shared Plugin Method Arguments (Android & iOS)
+// =============================================================================
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct EvaluateJsArgs {
+ pub script: String,
+ pub timeout_ms: u64,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TouchArgs {
+ pub r#type: String,
+ pub x: i32,
+ pub y: i32,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ScreenshotArgs {
+ pub timeout_ms: u64,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SendAlertTextArgs {
+ pub prompt_text: String,
+}
+
+// =============================================================================
+// Shared Plugin Method Responses (Android & iOS)
+// =============================================================================
+
+#[derive(Debug, Deserialize)]
+pub struct JsResult {
+ pub success: bool,
+ pub value: Option<Value>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AlertResult {
+ pub message: Option<String>,
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/alert_state.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/alert_state.rs
new file mode 100644
index 00000000..a1f1311b
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/alert_state.rs
@@ -0,0 +1,162 @@
+//! Cross-platform alert state management for `WebDriver`.
+//!
+//! This module provides per-window state for handling JavaScript alert/confirm/prompt dialogs
+//! across different platform implementations.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+/// Type of pending alert
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AlertType {
+ Alert,
+ Confirm,
+ Prompt,
+}
+
+/// Response from `WebDriver` for an alert
+#[derive(Debug, Clone)]
+pub struct AlertResponse {
+ pub accepted: bool,
+ pub prompt_text: Option<String>,
+}
+
+/// Pending alert waiting for `WebDriver` response
+pub struct PendingAlert {
+ pub message: String,
+ pub default_text: Option<String>,
+ pub alert_type: AlertType,
+ /// Sender to signal `WebDriver`'s accept/dismiss response
+ pub responder: std::sync::mpsc::Sender<AlertResponse>,
+}
+
+/// Per-window alert state for coordinating between UI delegate and `WebDriver` commands
+pub struct AlertState {
+ pending: Mutex<Option<PendingAlert>>,
+ /// Text input for prompt dialogs (set by `sendAlertText`)
+ prompt_input: Mutex<Option<String>>,
+}
+
+impl AlertState {
+ /// Create a new empty alert state
+ pub fn new() -> Self {
+ Self {
+ pending: Mutex::new(None),
+ prompt_input: Mutex::new(None),
+ }
+ }
+
+ /// Set a pending alert, clearing any previous prompt input
+ pub fn set_pending(&self, alert: PendingAlert) {
+ // Clear any previous prompt input
+ if let Ok(mut guard) = self.prompt_input.lock() {
+ *guard = None;
+ }
+ if let Ok(mut guard) = self.pending.lock() {
+ *guard = Some(alert);
+ }
+ }
+
+ /// Set the prompt input text (only valid for Prompt type alerts)
+ pub fn set_prompt_input(&self, text: String) -> bool {
+ // Only allow setting if there's a pending prompt
+ if !matches!(self.get_alert_type(), Some(AlertType::Prompt)) {
+ return false;
+ }
+ if let Ok(mut guard) = self.prompt_input.lock() {
+ *guard = Some(text);
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Get the current prompt input text
+ pub fn get_prompt_input(&self) -> Option<String> {
+ if let Ok(guard) = self.prompt_input.lock() {
+ guard.clone()
+ } else {
+ None
+ }
+ }
+
+ /// Get the message of the current pending alert
+ pub fn get_message(&self) -> Option<String> {
+ if let Ok(guard) = self.pending.lock() {
+ guard.as_ref().map(|a| a.message.clone())
+ } else {
+ None
+ }
+ }
+
+ /// Get the type of the current pending alert
+ pub fn get_alert_type(&self) -> Option<AlertType> {
+ if let Ok(guard) = self.pending.lock() {
+ guard.as_ref().map(|a| a.alert_type)
+ } else {
+ None
+ }
+ }
+
+ /// Get the default text for prompt dialogs
+ pub fn get_default_text(&self) -> Option<String> {
+ if let Ok(guard) = self.pending.lock() {
+ guard.as_ref().and_then(|a| a.default_text.clone())
+ } else {
+ None
+ }
+ }
+
+ /// Send response to pending alert and clear it
+ pub fn respond(&self, accepted: bool, prompt_text: Option<String>) -> bool {
+ if let Ok(mut guard) = self.pending.lock() {
+ if let Some(alert) = guard.take() {
+ // Clear prompt input
+ if let Ok(mut input_guard) = self.prompt_input.lock() {
+ *input_guard = None;
+ }
+ let _ = alert.responder.send(AlertResponse {
+ accepted,
+ prompt_text,
+ });
+ return true;
+ }
+ }
+ false
+ }
+}
+
+impl Default for AlertState {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Manager for per-window alert states
+pub struct AlertStateManager {
+ states: Mutex<HashMap<String, Arc<AlertState>>>,
+}
+
+impl AlertStateManager {
+ /// Create a new alert state manager
+ pub fn new() -> Self {
+ Self {
+ states: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// Get or create alert state for a window
+ pub fn get_or_create(&self, window_label: &str) -> Arc<AlertState> {
+ let mut states = self.states.lock().expect("AlertStateManager lock poisoned");
+ states
+ .entry(window_label.to_string())
+ .or_insert_with(|| Arc::new(AlertState::new()))
+ .clone()
+ }
+}
+
+impl Default for AlertStateManager {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/android.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/android.rs
new file mode 100644
index 00000000..33b0e354
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/android.rs
@@ -0,0 +1,537 @@
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::{Manager, Runtime, WebviewWindow};
+
+use crate::mobile::{
+ AlertResult, EvaluateJsArgs, JsResult, ScreenshotArgs, SendAlertTextArgs, TouchArgs, Webdriver,
+};
+use crate::platform::{
+ wrap_script_for_frame_context, Cookie, FrameId, PlatformExecutor, PointerEventType,
+ PrintOptions, WindowRect,
+};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::Timeouts;
+
+/// Android `WebView` executor using Tauri's mobile plugin bridge
+#[derive(Clone)]
+pub struct AndroidExecutor<R: Runtime> {
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+}
+
+impl<R: Runtime> AndroidExecutor<R> {
+ pub fn new(window: WebviewWindow<R>, timeouts: Timeouts, frame_context: Vec<FrameId>) -> Self {
+ Self {
+ window,
+ timeouts,
+ frame_context,
+ }
+ }
+}
+
+// =============================================================================
+// Android-specific Plugin Method Arguments
+// =============================================================================
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AsyncScriptArgs {
+ async_id: String,
+ script: String,
+ timeout_ms: u64,
+}
+
+#[derive(Debug, Serialize)]
+struct GetCookiesArgs {
+ url: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetCookieArgs {
+ url: String,
+ name: String,
+ value: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ path: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ domain: Option<String>,
+ secure: bool,
+ http_only: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ expiry: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ same_site: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+struct DeleteCookieArgs {
+ url: String,
+ name: String,
+}
+
+// =============================================================================
+// Android-specific Plugin Method Responses
+// =============================================================================
+
+#[derive(Debug, Deserialize)]
+struct CookiesResult {
+ success: bool,
+ cookies: Option<String>, // JSON array as string
+ error: Option<String>,
+}
+
+#[async_trait]
+impl<R: Runtime + 'static> PlatformExecutor<R> for AndroidExecutor<R> {
+ fn window(&self) -> &WebviewWindow<R> {
+ &self.window
+ }
+
+ fn script_timeout_ms(&self) -> u64 {
+ self.timeouts.script_ms
+ }
+
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ let wrapped_script = wrap_script_for_frame_context(script, &self.frame_context);
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let args = EvaluateJsArgs {
+ script: wrapped_script,
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("evaluateJs", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ // Parse the stringified JSON value from Android
+ let value = if let Some(value_str) = result.value {
+ if let Some(s) = value_str.as_str() {
+ // Android returns JSON as a string, parse it
+ serde_json::from_str(s).unwrap_or(value_str)
+ } else {
+ value_str
+ }
+ } else {
+ Value::Null
+ };
+
+ Ok(serde_json::json!({
+ "success": true,
+ "value": value
+ }))
+ } else {
+ let error_msg = result.error.as_deref().unwrap_or("Unknown error");
+ if error_msg.to_lowercase().contains("timeout") {
+ Err(WebDriverErrorResponse::script_timeout())
+ } else {
+ Err(WebDriverErrorResponse::javascript_error(error_msg, None))
+ }
+ }
+ }
+
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ let async_id = uuid::Uuid::new_v4().to_string();
+
+ // Build wrapper that includes argument deserialization and callback
+ let wrapper = format!(
+ r"(function() {{
+ var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+ var __args = {args_json}.map(deserializeArg);
+ __args.push(__done);
+ try {{
+ (function() {{ {script} }}).apply(null, __args);
+ }} catch (e) {{
+ __done(null, e.message || String(e));
+ }}
+ }})()"
+ );
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let plugin_args = AsyncScriptArgs {
+ async_id,
+ script: wrapper,
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("executeAsyncScript", plugin_args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ let value = if let Some(value_str) = result.value {
+ if let Some(s) = value_str.as_str() {
+ serde_json::from_str(s).unwrap_or(value_str)
+ } else {
+ value_str
+ }
+ } else {
+ Value::Null
+ };
+ Ok(value)
+ } else {
+ let error_msg = result.error.as_deref().unwrap_or("Unknown error");
+ if error_msg.to_lowercase().contains("timeout") {
+ Err(WebDriverErrorResponse::script_timeout())
+ } else {
+ Err(WebDriverErrorResponse::javascript_error(error_msg, None))
+ }
+ }
+ }
+
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let args = ScreenshotArgs {
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("takeScreenshot", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ if let Some(Value::String(base64)) = result.value {
+ Ok(base64)
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Screenshot returned invalid data",
+ ))
+ }
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ result.error.as_deref().unwrap_or("Screenshot failed"),
+ ))
+ }
+ }
+
+ async fn take_element_screenshot(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ // Scroll element into view first
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+
+ // Take full screenshot (element clipping can be added later)
+ self.take_screenshot().await
+ }
+
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("printToPdf", options)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ if let Some(Value::String(base64)) = result.value {
+ Ok(base64)
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Print returned invalid data",
+ ))
+ }
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ result.error.as_deref().unwrap_or("Print failed"),
+ ))
+ }
+ }
+
+ // Override pointer dispatch to use native touch on Android
+ async fn dispatch_pointer_event(
+ &self,
+ event_type: PointerEventType,
+ x: i32,
+ y: i32,
+ _button: u32,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let touch_type = match event_type {
+ PointerEventType::Down => "down",
+ PointerEventType::Up => "up",
+ PointerEventType::Move => "move",
+ };
+
+ let args = TouchArgs {
+ r#type: touch_type.to_string(),
+ x,
+ y,
+ };
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("dispatchTouch", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ Ok(())
+ }
+
+ // Alert handling via plugin
+ async fn get_alert_text(&self) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let result: AlertResult = webdriver
+ .0
+ .run_mobile_plugin_async("getAlertText", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ result
+ .message
+ .ok_or_else(WebDriverErrorResponse::no_such_alert)
+ }
+
+ async fn accept_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("acceptAlert", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ Ok(())
+ }
+
+ async fn dismiss_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("dismissAlert", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ Ok(())
+ }
+
+ async fn send_alert_text(&self, text: &str) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async(
+ "sendAlertText",
+ SendAlertTextArgs {
+ prompt_text: text.to_string(),
+ },
+ )
+ .await
+ .map_err(|e| {
+ let msg = e.to_string();
+ if msg.contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else if msg.contains("not a prompt") {
+ WebDriverErrorResponse::element_not_interactable(
+ "User prompt is not a prompt dialog",
+ )
+ } else {
+ WebDriverErrorResponse::unknown_error(&msg)
+ }
+ })?;
+
+ Ok(())
+ }
+
+ // =========================================================================
+ // Cookies (using Android CookieManager via plugin)
+ // =========================================================================
+
+ async fn get_all_cookies(&self) -> Result<Vec<Cookie>, WebDriverErrorResponse> {
+ let url = self
+ .window
+ .url()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?
+ .to_string();
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let result: CookiesResult = webdriver
+ .0
+ .run_mobile_plugin_async("getCookies", GetCookiesArgs { url })
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if !result.success {
+ return Err(WebDriverErrorResponse::unknown_error(
+ result.error.as_deref().unwrap_or("Failed to get cookies"),
+ ));
+ }
+
+ // Parse JSON array of cookies from the plugin
+ let cookies_json = result.cookies.unwrap_or_default();
+ if cookies_json.is_empty() || cookies_json == "[]" {
+ return Ok(Vec::new());
+ }
+
+ let cookies: Vec<Cookie> = serde_json::from_str(&cookies_json).map_err(|e| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to parse cookies: {e}"))
+ })?;
+
+ Ok(cookies)
+ }
+
+ async fn get_cookie(&self, name: &str) -> Result<Option<Cookie>, WebDriverErrorResponse> {
+ let cookies = self.get_all_cookies().await?;
+ Ok(cookies.into_iter().find(|c| c.name == name))
+ }
+
+ async fn add_cookie(&self, mut cookie: Cookie) -> Result<(), WebDriverErrorResponse> {
+ let url = self
+ .window
+ .url()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ // Per WebDriver spec: if no domain is specified, use the current page's domain
+ if cookie.domain.is_none() {
+ cookie.domain = url.host_str().map(String::from);
+ }
+
+ // Default path to "/" if not specified
+ if cookie.path.is_none() {
+ cookie.path = Some("/".to_string());
+ }
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async(
+ "setCookie",
+ SetCookieArgs {
+ url: url.to_string(),
+ name: cookie.name,
+ value: cookie.value,
+ path: cookie.path,
+ domain: cookie.domain,
+ secure: cookie.secure,
+ http_only: cookie.http_only,
+ expiry: cookie.expiry,
+ same_site: cookie.same_site,
+ },
+ )
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ Ok(())
+ }
+
+ async fn delete_cookie(&self, name: &str) -> Result<(), WebDriverErrorResponse> {
+ let url = self
+ .window
+ .url()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?
+ .to_string();
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async(
+ "deleteCookie",
+ DeleteCookieArgs {
+ url,
+ name: name.to_string(),
+ },
+ )
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ Ok(())
+ }
+
+ async fn delete_all_cookies(&self) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("deleteAllCookies", ())
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ Ok(())
+ }
+
+ // =========================================================================
+ // Window Management
+ // =========================================================================
+
+ async fn get_window_rect(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ // Get viewport size from Kotlin plugin
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ webdriver
+ .0
+ .run_mobile_plugin_async("getViewportSize", ())
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/executor.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/executor.rs
new file mode 100644
index 00000000..e161906c
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/executor.rs
@@ -0,0 +1,2203 @@
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::webview::Cookie as TauriCookie;
+use tauri::{Runtime, WebviewWindow};
+
+#[cfg(desktop)]
+use tauri::Listener;
+#[cfg(desktop)]
+use tauri::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize};
+
+use tauri::Manager;
+
+use crate::platform::alert_state::{AlertStateManager, AlertType};
+use crate::server::response::WebDriverErrorResponse;
+
+/// Element bounding rectangle
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct ElementRect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+/// Window rectangle (position and size)
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct WindowRect {
+ #[serde(default)]
+ pub x: i32,
+ #[serde(default)]
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[cfg(desktop)]
+fn physical_window_rect_to_logical(
+ position: PhysicalPosition<i32>,
+ size: PhysicalSize<u32>,
+ scale_factor: f64,
+) -> WindowRect {
+ let position = position.to_logical::<i32>(scale_factor);
+ let size = size.to_logical::<u32>(scale_factor);
+
+ WindowRect {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ }
+}
+
+#[cfg(desktop)]
+fn physical_window_chrome_to_logical(
+ outer: PhysicalSize<u32>,
+ inner: PhysicalSize<u32>,
+ scale_factor: f64,
+) -> LogicalSize<u32> {
+ PhysicalSize::new(
+ outer.width.saturating_sub(inner.width),
+ outer.height.saturating_sub(inner.height),
+ )
+ .to_logical(scale_factor)
+}
+
+#[cfg(desktop)]
+const WINDOW_CHANGE_EVENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
+
+/// Apply a native window change and wait for Tauri to confirm it via `event_name`.
+///
+/// Only a failure of the native call itself is an error. A window manager may clamp or
+/// ignore a request, in which case the confirming event never arrives — `Set Window Rect`
+/// is best-effort, so callers report the rect the window actually ended up with instead
+/// of failing the command.
+#[cfg(desktop)]
+async fn apply_window_change<R, F>(
+ window: &WebviewWindow<R>,
+ event_name: &'static str,
+ operation: &'static str,
+ change: F,
+) -> Result<(), WebDriverErrorResponse>
+where
+ R: Runtime,
+ F: FnOnce() -> tauri::Result<()>,
+{
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ let listener_id = window.once(event_name, move |_| {
+ let _ = sender.send(());
+ });
+
+ if let Err(error) = change() {
+ window.unlisten(listener_id);
+ return Err(WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to {operation}: {error}"
+ )));
+ }
+
+ match tokio::time::timeout(WINDOW_CHANGE_EVENT_TIMEOUT, receiver).await {
+ Ok(Ok(())) => {}
+ Ok(Err(_)) => {
+ tracing::debug!("Window event listener closed while waiting to {operation}");
+ }
+ Err(_) => {
+ window.unlisten(listener_id);
+ tracing::debug!("Timed out waiting to {operation}");
+ }
+ }
+
+ Ok(())
+}
+
+#[cfg(all(test, desktop))]
+mod window_rect_tests {
+ use super::*;
+
+ #[test]
+ fn converts_physical_window_rect_at_common_scale_factors() {
+ let cases = [
+ (
+ PhysicalPosition::new(-200, 150),
+ PhysicalSize::new(720, 540),
+ 1.0,
+ WindowRect {
+ x: -200,
+ y: 150,
+ width: 720,
+ height: 540,
+ },
+ ),
+ (
+ PhysicalPosition::new(-151, 251),
+ PhysicalSize::new(1000, 750),
+ 1.25,
+ WindowRect {
+ x: -121,
+ y: 201,
+ width: 800,
+ height: 600,
+ },
+ ),
+ (
+ PhysicalPosition::new(-400, 300),
+ PhysicalSize::new(1440, 1080),
+ 2.0,
+ WindowRect {
+ x: -200,
+ y: 150,
+ width: 720,
+ height: 540,
+ },
+ ),
+ ];
+
+ for (position, size, scale_factor, expected) in cases {
+ let actual = physical_window_rect_to_logical(position, size, scale_factor);
+
+ assert_eq!(actual.x, expected.x);
+ assert_eq!(actual.y, expected.y);
+ assert_eq!(actual.width, expected.width);
+ assert_eq!(actual.height, expected.height);
+ }
+ }
+
+ #[test]
+ fn converts_physical_window_chrome_before_subtracting_it() {
+ let retina_chrome = physical_window_chrome_to_logical(
+ PhysicalSize::new(1440, 1080),
+ PhysicalSize::new(1440, 1032),
+ 2.0,
+ );
+ let fractional_chrome = physical_window_chrome_to_logical(
+ PhysicalSize::new(1251, 1001),
+ PhysicalSize::new(1000, 750),
+ 1.25,
+ );
+
+ assert_eq!(retina_chrome, LogicalSize::new(0, 24));
+ assert_eq!(fractional_chrome, LogicalSize::new(201, 201));
+ }
+}
+
+/// Frame identifier for switching frames
+#[derive(Debug, Clone)]
+pub enum FrameId {
+ /// Frame by index
+ Index(u32),
+ /// Frame by element reference (`js_var`)
+ Element(String),
+}
+
+/// Pointer event type
+#[derive(Debug, Clone, Copy)]
+pub enum PointerEventType {
+ Down,
+ Up,
+ Move,
+ Click,
+}
+
+/// Cookie data
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct Cookie {
+ pub name: String,
+ pub value: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub domain: Option<String>,
+ #[serde(default)]
+ pub secure: bool,
+ #[serde(default, rename = "httpOnly")]
+ pub http_only: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expiry: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "sameSite")]
+ pub same_site: Option<String>,
+}
+
+/// Print options for PDF generation
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PrintOptions {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub orientation: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scale: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub background: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "pageWidth")]
+ pub page_width: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "pageHeight")]
+ pub page_height: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "marginTop")]
+ pub margin_top: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "marginBottom")]
+ pub margin_bottom: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "marginLeft")]
+ pub margin_left: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "marginRight")]
+ pub margin_right: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "shrinkToFit")]
+ pub shrink_to_fit: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none", rename = "pageRanges")]
+ pub page_ranges: Option<Vec<String>>,
+}
+
+/// Tracks the state of modifier keys during action sequences
+#[derive(Debug, Clone, Copy, Default)]
+#[allow(clippy::struct_excessive_bools)]
+pub struct ModifierState {
+ pub ctrl: bool,
+ pub shift: bool,
+ pub alt: bool,
+ pub meta: bool,
+}
+
+impl ModifierState {
+ /// Update modifier state when a key is pressed or released
+ pub fn update(&mut self, key: &str, is_down: bool) {
+ match key {
+ "\u{E009}" => self.ctrl = is_down, // Control
+ "\u{E008}" => self.shift = is_down, // Shift
+ "\u{E00A}" => self.alt = is_down, // Alt
+ "\u{E03D}" => self.meta = is_down, // Meta
+ _ => {}
+ }
+ }
+}
+
+/// Platform-agnostic trait for `WebView` operations.
+/// Each platform (macOS, Windows, Linux) implements this trait.
+#[async_trait]
+#[allow(clippy::too_many_lines)]
+pub trait PlatformExecutor<R: Runtime>: Send + Sync {
+ // =========================================================================
+ // Window Access
+ // =========================================================================
+
+ /// Get a reference to the underlying window
+ fn window(&self) -> &WebviewWindow<R>;
+
+ /// Get the script timeout in milliseconds
+ fn script_timeout_ms(&self) -> u64;
+
+ // =========================================================================
+ // Core JavaScript Execution
+ // =========================================================================
+
+ /// Execute JavaScript and return the result as JSON
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse>;
+
+ // =========================================================================
+ // Navigation
+ // =========================================================================
+
+ /// Navigate to a URL
+ async fn navigate(&self, url: &str) -> Result<(), WebDriverErrorResponse> {
+ let script = format!(
+ r"window.location.href = '{}'; null;",
+ url.replace('\\', "\\\\").replace('\'', "\\'")
+ );
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Get current URL
+ async fn get_url(&self) -> Result<String, WebDriverErrorResponse> {
+ let result = self.evaluate_js("window.location.href").await?;
+ extract_string_value(&result)
+ }
+
+ /// Get page title
+ async fn get_title(&self) -> Result<String, WebDriverErrorResponse> {
+ let result = self.evaluate_js("document.title").await?;
+ extract_string_value(&result)
+ }
+
+ /// Navigate back in history
+ async fn go_back(&self) -> Result<(), WebDriverErrorResponse> {
+ self.evaluate_js("window.history.back(); null;").await?;
+ Ok(())
+ }
+
+ /// Navigate forward in history
+ async fn go_forward(&self) -> Result<(), WebDriverErrorResponse> {
+ self.evaluate_js("window.history.forward(); null;").await?;
+ Ok(())
+ }
+
+ /// Refresh the current page
+ async fn refresh(&self) -> Result<(), WebDriverErrorResponse> {
+ self.evaluate_js("window.location.reload(); null;").await?;
+ Ok(())
+ }
+
+ // =========================================================================
+ // Document
+ // =========================================================================
+
+ /// Get page source HTML
+ async fn get_source(&self) -> Result<String, WebDriverErrorResponse> {
+ let result = self
+ .evaluate_js("document.documentElement.outerHTML")
+ .await?;
+ extract_string_value(&result)
+ }
+
+ // =========================================================================
+ // Element Operations
+ // =========================================================================
+
+ /// Find element and store reference in a JavaScript variable
+ /// Returns true if element was found
+ async fn find_element(
+ &self,
+ strategy_js: &str,
+ js_var: &str,
+ ) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = {strategy_js};
+ if (el) {{
+ window.{js_var} = el;
+ return true;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Find multiple elements and store count
+ /// Returns the number of elements found
+ async fn find_elements(
+ &self,
+ strategy_js: &str,
+ js_var_prefix: &str,
+ ) -> Result<usize, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var elements = {strategy_js};
+ var count = elements.length;
+ for (var i = 0; i < count; i++) {{
+ window['{js_var_prefix}' + i] = elements[i];
+ }}
+ return count;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_usize_value(&result)
+ }
+
+ /// Find element from a parent element and store reference
+ /// Returns true if element was found
+ async fn find_element_from_element(
+ &self,
+ parent_js_var: &str,
+ strategy_js: &str,
+ js_var: &str,
+ ) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var parent = window.{parent_js_var};
+ if (!parent || !parent.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var el = {strategy_js};
+ if (el) {{
+ window.{js_var} = el;
+ return true;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Find multiple elements from a parent element
+ /// Returns count of elements found, stores as {prefix}0, {prefix}1, etc.
+ async fn find_elements_from_element(
+ &self,
+ parent_js_var: &str,
+ strategy_js: &str,
+ js_var_prefix: &str,
+ ) -> Result<usize, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var parent = window.{parent_js_var};
+ if (!parent || !parent.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var elements = {strategy_js};
+ var count = elements.length;
+ for (var i = 0; i < count; i++) {{
+ window['{js_var_prefix}' + i] = elements[i];
+ }}
+ return count;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_usize_value(&result)
+ }
+
+ /// Get element text content
+ async fn get_element_text(&self, js_var: &str) -> Result<String, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ return el.textContent || '';
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_string_value(&result)
+ }
+
+ /// Get element tag name (lowercase)
+ async fn get_element_tag_name(&self, js_var: &str) -> Result<String, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ return el.tagName.toLowerCase();
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_string_value(&result)
+ }
+
+ /// Get element attribute value
+ /// Per W3C `WebDriver` spec, certain attributes should return current property values:
+ /// - "value" on input/textarea returns current value property
+ /// - "checked" on checkbox/radio returns current checked state
+ /// - "selected" on option returns current selected state
+ async fn get_element_attribute(
+ &self,
+ js_var: &str,
+ name: &str,
+ ) -> Result<Option<String>, WebDriverErrorResponse> {
+ let escaped_name = name.replace('\\', "\\\\").replace('\'', "\\'");
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var attrName = '{escaped_name}'.toLowerCase();
+ var tagName = el.tagName.toLowerCase();
+
+ // Per W3C WebDriver spec, return property values for certain attributes
+ if (attrName === 'value') {{
+ if (tagName === 'input' || tagName === 'textarea') {{
+ return el.value;
+ }}
+ }}
+ if (attrName === 'checked') {{
+ if (tagName === 'input' && (el.type === 'checkbox' || el.type === 'radio')) {{
+ return el.checked ? 'true' : null;
+ }}
+ }}
+ if (attrName === 'selected') {{
+ if (tagName === 'option') {{
+ return el.selected ? 'true' : null;
+ }}
+ }}
+
+ return el.getAttribute('{escaped_name}');
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+
+ if let Some(value) = result.get("value") {
+ if value.is_null() {
+ return Ok(None);
+ }
+ if let Some(s) = value.as_str() {
+ return Ok(Some(s.to_string()));
+ }
+ }
+ Ok(None)
+ }
+
+ /// Get element property value
+ async fn get_element_property(
+ &self,
+ js_var: &str,
+ name: &str,
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let escaped_name = name.replace('\\', "\\\\").replace('\'', "\\'");
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ return el['{escaped_name}'];
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_value(&result)
+ }
+
+ /// Get element CSS property value
+ async fn get_element_css_value(
+ &self,
+ js_var: &str,
+ property: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ let escaped_prop = property.replace('\\', "\\\\").replace('\'', "\\'");
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ return window.getComputedStyle(el).getPropertyValue('{escaped_prop}');
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_string_value(&result)
+ }
+
+ /// Get element bounding rectangle
+ async fn get_element_rect(&self, js_var: &str) -> Result<ElementRect, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var rect = el.getBoundingClientRect();
+ return {{
+ x: rect.x + window.scrollX,
+ y: rect.y + window.scrollY,
+ width: rect.width,
+ height: rect.height
+ }};
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+
+ if let Some(value) = result.get("value") {
+ return Ok(ElementRect {
+ x: value.get("x").and_then(Value::as_f64).unwrap_or(0.0),
+ y: value.get("y").and_then(Value::as_f64).unwrap_or(0.0),
+ width: value.get("width").and_then(Value::as_f64).unwrap_or(0.0),
+ height: value.get("height").and_then(Value::as_f64).unwrap_or(0.0),
+ });
+ }
+ Ok(ElementRect::default())
+ }
+
+ /// Get an element's in-view center point in **client (viewport)** coordinates,
+ /// scrolling it into view first. Unlike [`Executor::get_element_rect`], this
+ /// does not add scroll offsets: pointer events dispatch against viewport
+ /// coordinates (`clientX`/`clientY`), so the center must be viewport-relative.
+ async fn get_element_center(&self, js_var: &str) -> Result<(i32, i32), WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ behavior: 'instant', block: 'center', inline: 'center' }});
+ var r = el.getBoundingClientRect();
+ return {{
+ x: Math.floor(r.left + r.width / 2),
+ y: Math.floor(r.top + r.height / 2)
+ }};
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+
+ let value = result.get("value").cloned().ok_or_else(|| {
+ WebDriverErrorResponse::unknown_error("element center script returned no value")
+ })?;
+
+ #[derive(serde::Deserialize)]
+ struct Center {
+ x: i32,
+ y: i32,
+ }
+ let center: Center = serde_json::from_value(value).map_err(|err| {
+ WebDriverErrorResponse::unknown_error(&format!("could not read element center: {err}"))
+ })?;
+ Ok((center.x, center.y))
+ }
+
+ /// Check if element is displayed
+ async fn is_element_displayed(&self, js_var: &str) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var style = window.getComputedStyle(el);
+ return style.display !== 'none' && style.visibility !== 'hidden' && el.offsetParent !== null;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Check if element is enabled
+ async fn is_element_enabled(&self, js_var: &str) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ return !el.disabled;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Check if element is selected (for checkboxes, radio buttons, options)
+ async fn is_element_selected(&self, js_var: &str) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {{
+ return el.checked;
+ }}
+ if (el.tagName === 'OPTION') {{
+ return el.selected;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Click on element
+ async fn click_element(&self, js_var: &str) -> Result<(), WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+ el.click();
+ // Explicitly focus the element after click - programmatic click()
+ // doesn't always trigger focus like a real click would
+ if (typeof el.focus === 'function') {{
+ el.focus();
+ }}
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Clear element content (for inputs/textareas)
+ async fn clear_element(&self, js_var: &str) -> Result<(), WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.focus();
+ if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {{
+ var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ el.tagName === 'INPUT' ? window.HTMLInputElement.prototype : window.HTMLTextAreaElement.prototype,
+ 'value'
+ ).set;
+ nativeInputValueSetter.call(el, '');
+ var inputEvent = new InputEvent('input', {{
+ bubbles: true,
+ cancelable: true,
+ inputType: 'deleteContentBackward'
+ }});
+ el.dispatchEvent(inputEvent);
+ var changeEvent = new Event('change', {{ bubbles: true }});
+ el.dispatchEvent(changeEvent);
+ }} else if (el.isContentEditable) {{
+ el.innerHTML = '';
+ }}
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Send keys to element
+ async fn send_keys_to_element(
+ &self,
+ js_var: &str,
+ text: &str,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let escaped = text
+ .replace('\\', "\\\\")
+ .replace('`', "\\`")
+ .replace('$', "\\$");
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.focus();
+
+ if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {{
+ var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ el.tagName === 'INPUT' ? window.HTMLInputElement.prototype : window.HTMLTextAreaElement.prototype,
+ 'value'
+ ).set;
+
+ var newValue = el.value + `{escaped}`;
+ nativeInputValueSetter.call(el, newValue);
+
+ var inputEvent = new InputEvent('input', {{
+ bubbles: true,
+ cancelable: true,
+ inputType: 'insertText',
+ data: `{escaped}`
+ }});
+ el.dispatchEvent(inputEvent);
+
+ var changeEvent = new Event('change', {{ bubbles: true }});
+ el.dispatchEvent(changeEvent);
+ }} else if (el.isContentEditable) {{
+ document.execCommand('insertText', false, `{escaped}`);
+ }}
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Get the active (focused) element and store in `js_var`
+ /// Returns true if an active element was found
+ async fn get_active_element(&self, js_var: &str) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = document.activeElement;
+ if (el && el !== document.body) {{
+ window.{js_var} = el;
+ return true;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Get element's computed accessibility role
+ async fn get_element_computed_role(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+
+ // Check for explicit role attribute first
+ var explicitRole = el.getAttribute('role');
+ if (explicitRole) return explicitRole;
+
+ // Try computedRole if available (Chrome/Edge)
+ if (el.computedRole) return el.computedRole;
+
+ // Compute implicit role based on element type
+ var tag = el.tagName.toLowerCase();
+ var type = el.type ? el.type.toLowerCase() : '';
+
+ // Map elements to their implicit ARIA roles
+ var roleMap = {{
+ 'a': el.hasAttribute('href') ? 'link' : 'generic',
+ 'article': 'article',
+ 'aside': 'complementary',
+ 'button': 'button',
+ 'datalist': 'listbox',
+ 'details': 'group',
+ 'dialog': 'dialog',
+ 'fieldset': 'group',
+ 'figure': 'figure',
+ 'footer': 'contentinfo',
+ 'form': 'form',
+ 'h1': 'heading',
+ 'h2': 'heading',
+ 'h3': 'heading',
+ 'h4': 'heading',
+ 'h5': 'heading',
+ 'h6': 'heading',
+ 'header': 'banner',
+ 'hr': 'separator',
+ 'img': el.getAttribute('alt') === '' ? 'presentation' : 'img',
+ 'li': 'listitem',
+ 'main': 'main',
+ 'menu': 'list',
+ 'meter': 'meter',
+ 'nav': 'navigation',
+ 'ol': 'list',
+ 'optgroup': 'group',
+ 'option': 'option',
+ 'output': 'status',
+ 'progress': 'progressbar',
+ 'section': 'region',
+ 'select': el.multiple ? 'listbox' : 'combobox',
+ 'summary': 'button',
+ 'table': 'table',
+ 'tbody': 'rowgroup',
+ 'td': 'cell',
+ 'textarea': 'textbox',
+ 'tfoot': 'rowgroup',
+ 'th': 'columnheader',
+ 'thead': 'rowgroup',
+ 'tr': 'row',
+ 'ul': 'list'
+ }};
+
+ // Handle input types
+ if (tag === 'input') {{
+ var inputRoles = {{
+ 'button': 'button',
+ 'checkbox': 'checkbox',
+ 'email': 'textbox',
+ 'image': 'button',
+ 'number': 'spinbutton',
+ 'radio': 'radio',
+ 'range': 'slider',
+ 'reset': 'button',
+ 'search': 'searchbox',
+ 'submit': 'button',
+ 'tel': 'textbox',
+ 'text': 'textbox',
+ 'url': 'textbox'
+ }};
+ return inputRoles[type] || 'textbox';
+ }}
+
+ return roleMap[tag] || '';
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_string_value(&result)
+ }
+
+ /// Get element's computed accessibility label
+ async fn get_element_computed_label(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ let script = format!(
+ r#"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+
+ // Try computedName if available (Chrome/Edge)
+ if (el.computedName) return el.computedName;
+
+ // Check aria-labelledby first (highest priority)
+ var labelledBy = el.getAttribute('aria-labelledby');
+ if (labelledBy) {{
+ var labels = labelledBy.split(/\s+/).map(function(id) {{
+ var labelEl = document.getElementById(id);
+ return labelEl ? labelEl.textContent : '';
+ }});
+ var combined = labels.join(' ').trim();
+ if (combined) return combined;
+ }}
+
+ // Check aria-label
+ var ariaLabel = el.getAttribute('aria-label');
+ if (ariaLabel) return ariaLabel;
+
+ // For inputs, check associated label
+ var tag = el.tagName.toLowerCase();
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {{
+ // Check for label with 'for' attribute
+ if (el.id) {{
+ var label = document.querySelector("label[for='" + el.id + "']");
+ if (label) return label.textContent.trim();
+ }}
+ // Check for wrapping label
+ var parentLabel = el.closest('label');
+ if (parentLabel) {{
+ // Get label text excluding the input's value
+ var clone = parentLabel.cloneNode(true);
+ var inputs = clone.querySelectorAll('input, textarea, select');
+ inputs.forEach(function(input) {{ input.remove(); }});
+ var labelText = clone.textContent.trim();
+ if (labelText) return labelText;
+ }}
+ // Check placeholder
+ if (el.placeholder) return el.placeholder;
+ }}
+
+ // For buttons and links, use text content
+ if (tag === 'button' || tag === 'a') {{
+ return el.textContent.trim();
+ }}
+
+ // For images, use alt text
+ if (tag === 'img') {{
+ return el.getAttribute('alt') || '';
+ }}
+
+ // Check title attribute as last resort
+ var title = el.getAttribute('title');
+ if (title) return title;
+
+ // Fall back to text content for other elements
+ return el.textContent ? el.textContent.trim() : '';
+ }})()"#
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_string_value(&result)
+ }
+
+ // =========================================================================
+ // Shadow DOM
+ // =========================================================================
+
+ /// Get element's shadow root and store in `shadow_var`
+ /// Returns true if shadow root exists
+ async fn get_element_shadow_root(
+ &self,
+ js_var: &str,
+ shadow_var: &str,
+ ) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ var shadow = el.shadowRoot;
+ if (shadow) {{
+ window.{shadow_var} = shadow;
+ return true;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Find element within a shadow root
+ async fn find_element_from_shadow(
+ &self,
+ shadow_var: &str,
+ strategy_js: &str,
+ js_var: &str,
+ ) -> Result<bool, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var shadow = window.{shadow_var};
+ if (!shadow) {{
+ throw new Error('no such shadow root');
+ }}
+ var el = {strategy_js};
+ if (el) {{
+ window.{js_var} = el;
+ return true;
+ }}
+ return false;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_bool_value(&result)
+ }
+
+ /// Find multiple elements within a shadow root
+ async fn find_elements_from_shadow(
+ &self,
+ shadow_var: &str,
+ strategy_js: &str,
+ js_var_prefix: &str,
+ ) -> Result<usize, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var shadow = window.{shadow_var};
+ if (!shadow) {{
+ throw new Error('no such shadow root');
+ }}
+ var elements = {strategy_js};
+ var count = elements.length;
+ for (var i = 0; i < count; i++) {{
+ window['{js_var_prefix}' + i] = elements[i];
+ }}
+ return count;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ extract_usize_value(&result)
+ }
+
+ // =========================================================================
+ // Script Execution
+ // =========================================================================
+
+ /// Execute synchronous JavaScript with arguments
+ async fn execute_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ // Generate unique result variable name
+ let result_var = format!("__wdio_exec_{}", uuid::Uuid::new_v4());
+
+ // Wrapper script that:
+ // 1. Executes the user's script as a function body (per W3C WebDriver spec §13.2.2)
+ // 2. Stores result in a global variable for polling
+ // Note: We use an IIFE that returns `undefined` to avoid Promise serialization issues
+ //
+ // The script is treated as a function body. Clients that want to return a value must
+ // include an explicit `return` statement — this matches WebdriverIO's function-object
+ // wrapping (`return (fn).apply(null, arguments)`) and raw string scripts like
+ // `"return document.title"`.
+ let wrapper = format!(
+ r"(function() {{
+ var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+
+ function serializeValue(value) {{
+ if (value === null || value === undefined) return null;
+ if (typeof value === 'boolean') return value;
+ if (typeof value === 'number') {{
+ if (!isFinite(value)) return null;
+ return value;
+ }}
+ if (typeof value === 'string') return value;
+ if (typeof value === 'function') return null;
+ if (typeof value === 'symbol') return null;
+ if (typeof value === 'bigint') return Number(value);
+ if (Array.isArray(value)) {{
+ return value.map(serializeValue);
+ }}
+ if (typeof value === 'object') {{
+ if (value[ELEMENT_KEY]) return value;
+ if (value && value.nodeType && value.nodeType === 1) return null;
+ var result = {{}};
+ for (var key in value) {{
+ if (value.hasOwnProperty(key)) {{
+ result[key] = serializeValue(value[key]);
+ }}
+ }}
+ return result;
+ }}
+ return null;
+ }}
+
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+
+ // Start async execution (fire and forget)
+ (async function() {{
+ try {{
+ var args = {args_json}.map(deserializeArg);
+ // W3C-compliant: wrap as function body, apply with args
+ var raw_result = await (async function() {{ {script} }}).apply(null, args);
+ var serialized = serializeValue(raw_result);
+ window['{result_var}'] = {{ __wd_success: true, __wd_value: serialized }};
+ }} catch (e) {{
+ window['{result_var}'] = {{ __wd_success: false, __wd_error: e.message || String(e) }};
+ }}
+ }})();
+
+ // Return undefined to avoid Promise serialization issues
+ return undefined;
+ }})()",
+ );
+
+ // Execute the wrapper script (fire and forget, returns undefined)
+ self.evaluate_js(&wrapper).await?;
+
+ // Poll for the result with timeout
+ let poll_script = format!("window['{}']", result_var);
+ let timeout = std::time::Duration::from_millis(self.script_timeout_ms());
+ let start = std::time::Instant::now();
+ let poll_interval = std::time::Duration::from_millis(50);
+
+ loop {
+ let poll_result = self.evaluate_js(&poll_script).await?;
+ let inner = poll_result.get("value").cloned().unwrap_or(Value::Null);
+
+ // Check if we have a result
+ if !inner.is_null() && inner.get("__wd_success").is_some() {
+ // Clean up the global variable
+ let cleanup_script = format!("delete window['{}']", result_var);
+ let _ = self.evaluate_js(&cleanup_script).await;
+
+ return extract_script_result_from_inner(&inner);
+ }
+
+ if start.elapsed() > timeout {
+ // Clean up on timeout
+ let cleanup_script = format!("delete window['{}']", result_var);
+ let _ = self.evaluate_js(&cleanup_script).await;
+
+ return Err(WebDriverErrorResponse::script_timeout());
+ }
+
+ tokio::time::sleep(poll_interval).await;
+ }
+ }
+
+ /// Execute asynchronous JavaScript with callback.
+ ///
+ /// Each platform must implement this using native message handlers.
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse>;
+
+ /// Execute a pre-wrapped async DirectEval script (the `/wdio/eval` channel).
+ ///
+ /// The script uses the W3C async-callback contract (`arguments[last]` is the done callback).
+ /// Defaults to `execute_async_script`; a platform may override to avoid a long-lived native
+ /// completion handler (see the macOS executor).
+ async fn execute_direct_eval(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ self.execute_async_script(script, &[]).await
+ }
+
+ // =========================================================================
+ // Screenshots
+ // =========================================================================
+
+ /// Take screenshot of the page, returns base64-encoded PNG
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse>;
+
+ /// Take screenshot of a specific element, returns base64-encoded PNG
+ async fn take_element_screenshot(&self, js_var: &str)
+ -> Result<String, WebDriverErrorResponse>;
+
+ // =========================================================================
+ // Actions (Keyboard/Pointer)
+ // =========================================================================
+
+ /// Dispatch a keyboard event with modifier state
+ async fn dispatch_key_event(
+ &self,
+ key: &str,
+ is_down: bool,
+ modifiers: &ModifierState,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let (js_key, js_code, key_code) = match key {
+ "\u{E007}" => ("Enter", "Enter", 13),
+ "\u{E003}" => ("Backspace", "Backspace", 8),
+ "\u{E004}" => ("Tab", "Tab", 9),
+ "\u{E006}" => ("Enter", "NumpadEnter", 13),
+ "\u{E00C}" => ("Escape", "Escape", 27),
+ "\u{E00D}" => (" ", "Space", 32),
+ "\u{E012}" => ("ArrowLeft", "ArrowLeft", 37),
+ "\u{E013}" => ("ArrowUp", "ArrowUp", 38),
+ "\u{E014}" => ("ArrowRight", "ArrowRight", 39),
+ "\u{E015}" => ("ArrowDown", "ArrowDown", 40),
+ "\u{E017}" => ("Delete", "Delete", 46),
+ "\u{E031}" => ("F1", "F1", 112),
+ "\u{E032}" => ("F2", "F2", 113),
+ "\u{E033}" => ("F3", "F3", 114),
+ "\u{E034}" => ("F4", "F4", 115),
+ "\u{E035}" => ("F5", "F5", 116),
+ "\u{E036}" => ("F6", "F6", 117),
+ "\u{E037}" => ("F7", "F7", 118),
+ "\u{E038}" => ("F8", "F8", 119),
+ "\u{E039}" => ("F9", "F9", 120),
+ "\u{E03A}" => ("F10", "F10", 121),
+ "\u{E03B}" => ("F11", "F11", 122),
+ "\u{E03C}" => ("F12", "F12", 123),
+ "\u{E008}" => ("Shift", "ShiftLeft", 16),
+ "\u{E009}" => ("Control", "ControlLeft", 17),
+ "\u{E00A}" => ("Alt", "AltLeft", 18),
+ "\u{E03D}" => ("Meta", "MetaLeft", 91),
+ _ => {
+ let ch = key.chars().next().unwrap_or(' ');
+ let upper = ch.to_ascii_uppercase();
+ let code = if ch.is_ascii_alphabetic() {
+ format!("Key{upper}")
+ } else if ch.is_ascii_digit() {
+ format!("Digit{ch}")
+ } else {
+ key.to_string()
+ };
+ return self
+ .dispatch_regular_key(key, &code, is_down, modifiers)
+ .await;
+ }
+ };
+
+ let event_type = if is_down { "keydown" } else { "keyup" };
+
+ // For special keys that modify input (Backspace, Delete), handle value changes
+ let script = if is_down && (js_key == "Backspace" || js_key == "Delete") {
+ format!(
+ r"(function() {{
+ var activeEl = document.activeElement || document.body;
+
+ // Dispatch keydown event
+ var keydownEvent = new KeyboardEvent('keydown', {{
+ key: '{js_key}',
+ code: '{js_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ bubbles: true,
+ cancelable: true
+ }});
+ activeEl.dispatchEvent(keydownEvent);
+
+ // If active element is an input or textarea, handle deletion
+ if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {{
+ var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ activeEl.tagName === 'INPUT'
+ ? window.HTMLInputElement.prototype
+ : window.HTMLTextAreaElement.prototype,
+ 'value'
+ ).set;
+
+ var currentValue = activeEl.value;
+ var selStart = activeEl.selectionStart;
+ var selEnd = activeEl.selectionEnd;
+ var newValue;
+ var inputType;
+
+ // Check if there's a selection
+ if (selStart !== selEnd) {{
+ // Delete selection
+ newValue = currentValue.slice(0, selStart) + currentValue.slice(selEnd);
+ inputType = 'deleteContentBackward';
+ // Set cursor position after deletion
+ nativeInputValueSetter.call(activeEl, newValue);
+ activeEl.setSelectionRange(selStart, selStart);
+ }} else if ('{js_key}' === 'Backspace' && selStart > 0) {{
+ newValue = currentValue.slice(0, selStart - 1) + currentValue.slice(selStart);
+ inputType = 'deleteContentBackward';
+ nativeInputValueSetter.call(activeEl, newValue);
+ activeEl.setSelectionRange(selStart - 1, selStart - 1);
+ }} else if ('{js_key}' === 'Delete' && selStart < currentValue.length) {{
+ newValue = currentValue.slice(0, selStart) + currentValue.slice(selStart + 1);
+ inputType = 'deleteContentForward';
+ nativeInputValueSetter.call(activeEl, newValue);
+ activeEl.setSelectionRange(selStart, selStart);
+ }} else {{
+ return true; // Nothing to delete
+ }}
+
+ // Dispatch input event
+ var inputEvent = new InputEvent('input', {{
+ bubbles: true,
+ cancelable: true,
+ inputType: inputType
+ }});
+ activeEl.dispatchEvent(inputEvent);
+ }}
+
+ return true;
+ }})()"
+ )
+ } else if is_down
+ && (js_key == "ArrowDown"
+ || js_key == "ArrowUp"
+ || js_key == "ArrowLeft"
+ || js_key == "ArrowRight")
+ {
+ // Handle arrow keys on radio buttons for navigation
+ let go_forward = js_key == "ArrowDown" || js_key == "ArrowRight";
+ format!(
+ r#"(function() {{
+ var activeEl = document.activeElement || document.body;
+
+ // Dispatch keydown event first
+ var keydownEvent = new KeyboardEvent('keydown', {{
+ key: '{js_key}',
+ code: '{js_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ bubbles: true,
+ cancelable: true
+ }});
+ activeEl.dispatchEvent(keydownEvent);
+
+ // If active element is a radio button, handle navigation
+ if (activeEl.tagName === 'INPUT' && activeEl.type === 'radio' && activeEl.name) {{
+ var name = activeEl.name;
+ var radios = Array.from(document.querySelectorAll("input[type='radio'][name='" + name + "']"));
+ var currentIndex = radios.indexOf(activeEl);
+
+ if (currentIndex !== -1 && radios.length > 1) {{
+ var nextIndex;
+ if ({go_forward}) {{
+ // ArrowDown/ArrowRight - go to next
+ nextIndex = (currentIndex + 1) % radios.length;
+ }} else {{
+ // ArrowUp/ArrowLeft - go to previous
+ nextIndex = (currentIndex - 1 + radios.length) % radios.length;
+ }}
+
+ var nextRadio = radios[nextIndex];
+ nextRadio.checked = true;
+ nextRadio.focus();
+
+ // Dispatch change event
+ var changeEvent = new Event('change', {{ bubbles: true }});
+ nextRadio.dispatchEvent(changeEvent);
+ }}
+ }}
+
+ return true;
+ }})()"#
+ )
+ } else {
+ format!(
+ r"(function() {{
+ var event = new KeyboardEvent('{event_type}', {{
+ key: '{js_key}',
+ code: '{js_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ bubbles: true,
+ cancelable: true
+ }});
+ var activeEl = document.activeElement || document.body;
+ activeEl.dispatchEvent(event);
+ return true;
+ }})()"
+ )
+ };
+
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Dispatch a regular (non-special) key event with modifier state
+ async fn dispatch_regular_key(
+ &self,
+ key: &str,
+ code: &str,
+ is_down: bool,
+ modifiers: &ModifierState,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let ch = key.chars().next().unwrap_or(' ');
+ let key_code = ch as u32;
+ let event_type = if is_down { "keydown" } else { "keyup" };
+
+ let escaped_key = key.replace('\\', "\\\\").replace('\'', "\\'");
+ let escaped_code = code.replace('\\', "\\\\").replace('\'', "\\'");
+
+ let ctrl_key = modifiers.ctrl;
+ let meta_key = modifiers.meta;
+ let shift_key = modifiers.shift;
+ let alt_key = modifiers.alt;
+
+ // Check for Ctrl+A or Meta+A (select all)
+ let is_select_all = is_down && (ch == 'a' || ch == 'A') && (ctrl_key || meta_key);
+
+ let script = if is_select_all {
+ // Handle Ctrl+A / Meta+A: select all text
+ format!(
+ r"(function() {{
+ var activeEl = document.activeElement || document.body;
+
+ // Dispatch keydown event with modifiers
+ var keydownEvent = new KeyboardEvent('keydown', {{
+ key: '{escaped_key}',
+ code: '{escaped_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ ctrlKey: {ctrl_key},
+ metaKey: {meta_key},
+ shiftKey: {shift_key},
+ altKey: {alt_key},
+ bubbles: true,
+ cancelable: true
+ }});
+ activeEl.dispatchEvent(keydownEvent);
+
+ // Select all text in input/textarea
+ if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {{
+ activeEl.select();
+ }} else {{
+ document.execCommand('selectAll', false, null);
+ }}
+
+ return true;
+ }})()"
+ )
+ } else if is_down {
+ // For keydown events on printable characters, update input value
+ format!(
+ r"(function() {{
+ var activeEl = document.activeElement || document.body;
+
+ // Dispatch keydown event with modifiers
+ var keydownEvent = new KeyboardEvent('keydown', {{
+ key: '{escaped_key}',
+ code: '{escaped_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ ctrlKey: {ctrl_key},
+ metaKey: {meta_key},
+ shiftKey: {shift_key},
+ altKey: {alt_key},
+ bubbles: true,
+ cancelable: true
+ }});
+ activeEl.dispatchEvent(keydownEvent);
+
+ // If active element is an input or textarea, update value and dispatch input event
+ // Only do this for non-modifier key combos
+ if (!{ctrl_key} && !{meta_key} && !{alt_key}) {{
+ if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {{
+ var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ activeEl.tagName === 'INPUT'
+ ? window.HTMLInputElement.prototype
+ : window.HTMLTextAreaElement.prototype,
+ 'value'
+ ).set;
+
+ var newValue = activeEl.value + '{escaped_key}';
+ nativeInputValueSetter.call(activeEl, newValue);
+
+ // Dispatch input event
+ var inputEvent = new InputEvent('input', {{
+ bubbles: true,
+ cancelable: true,
+ inputType: 'insertText',
+ data: '{escaped_key}'
+ }});
+ activeEl.dispatchEvent(inputEvent);
+ }}
+ }}
+
+ return true;
+ }})()"
+ )
+ } else {
+ format!(
+ r"(function() {{
+ var activeEl = document.activeElement || document.body;
+ var event = new KeyboardEvent('{event_type}', {{
+ key: '{escaped_key}',
+ code: '{escaped_code}',
+ keyCode: {key_code},
+ which: {key_code},
+ ctrlKey: {ctrl_key},
+ metaKey: {meta_key},
+ shiftKey: {shift_key},
+ altKey: {alt_key},
+ bubbles: true,
+ cancelable: true
+ }});
+ activeEl.dispatchEvent(event);
+ return true;
+ }})()"
+ )
+ };
+
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Dispatch a pointer/mouse event
+ async fn dispatch_pointer_event(
+ &self,
+ event_type: PointerEventType,
+ x: i32,
+ y: i32,
+ button: u32,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let event_name = match event_type {
+ PointerEventType::Down => "mousedown",
+ PointerEventType::Up => "mouseup",
+ PointerEventType::Move => "mousemove",
+ // Manually dispatched mousedown/mouseup do NOT make the browser
+ // synthesize a click, so element click handlers never fire. The
+ // actions handler emits this explicitly after a same-spot down+up.
+ PointerEventType::Click => "click",
+ };
+
+ let buttons = if matches!(event_type, PointerEventType::Down) {
+ 1 << button
+ } else {
+ 0
+ };
+ let script = format!(
+ r"(function() {{
+ var el = document.elementFromPoint({x}, {y});
+ if (!el) el = document.body;
+
+ var event = new MouseEvent('{event_name}', {{
+ bubbles: true,
+ cancelable: true,
+ clientX: {x},
+ clientY: {y},
+ button: {button},
+ buttons: {buttons}
+ }});
+ el.dispatchEvent(event);
+ return true;
+ }})()"
+ );
+
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ /// Dispatch a scroll/wheel event
+ async fn dispatch_scroll_event(
+ &self,
+ x: i32,
+ y: i32,
+ delta_x: i32,
+ delta_y: i32,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = document.elementFromPoint({x}, {y});
+ if (!el) el = document.body;
+
+ var event = new WheelEvent('wheel', {{
+ bubbles: true,
+ cancelable: true,
+ clientX: {x},
+ clientY: {y},
+ deltaX: {delta_x},
+ deltaY: {delta_y},
+ deltaMode: 0
+ }});
+ el.dispatchEvent(event);
+
+ window.scrollBy({delta_x}, {delta_y});
+ return true;
+ }})()"
+ );
+
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+
+ // =========================================================================
+ // Window Management
+ // =========================================================================
+
+ /// Get window rectangle (position and size)
+ #[cfg(desktop)]
+ async fn get_window_rect(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ let scale_factor = self.window().scale_factor().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get window scale factor: {error}"
+ ))
+ })?;
+ let position = self.window().outer_position().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get window position: {error}"
+ ))
+ })?;
+ let size = self.window().outer_size().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to get window size: {error}"))
+ })?;
+
+ Ok(physical_window_rect_to_logical(
+ position,
+ size,
+ scale_factor,
+ ))
+ }
+
+ #[cfg(mobile)]
+ async fn get_window_rect(&self) -> Result<WindowRect, WebDriverErrorResponse>;
+
+ /// Set window rectangle (position and size)
+ #[cfg(desktop)]
+ async fn set_window_rect(
+ &self,
+ rect: WindowRect,
+ ) -> Result<WindowRect, WebDriverErrorResponse> {
+ // Exit fullscreen/maximized state before setting rect
+ // Otherwise the window manager may ignore our size/position request
+ let is_fullscreen = self.window().is_fullscreen().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to query window fullscreen state: {error}"
+ ))
+ })?;
+ if is_fullscreen {
+ apply_window_change(
+ self.window(),
+ "tauri://resize",
+ "exit window fullscreen state",
+ || self.window().set_fullscreen(false),
+ )
+ .await?;
+ }
+ let is_maximized = self.window().is_maximized().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to query window maximized state: {error}"
+ ))
+ })?;
+ if is_maximized {
+ apply_window_change(
+ self.window(),
+ "tauri://resize",
+ "restore maximized window",
+ || self.window().unmaximize(),
+ )
+ .await?;
+ }
+
+ let scale_factor = self.window().scale_factor().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get window scale factor: {error}"
+ ))
+ })?;
+ let position = self.window().outer_position().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get window position: {error}"
+ ))
+ })?;
+ let outer_size = self.window().outer_size().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get outer window size: {error}"
+ ))
+ })?;
+ let inner_size = self.window().inner_size().map_err(|error| {
+ WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to get inner window size: {error}"
+ ))
+ })?;
+
+ let current_rect = physical_window_rect_to_logical(position, outer_size, scale_factor);
+ let chrome_size = physical_window_chrome_to_logical(outer_size, inner_size, scale_factor);
+
+ if rect.x != current_rect.x || rect.y != current_rect.y {
+ apply_window_change(self.window(), "tauri://move", "set window position", || {
+ self.window()
+ .set_position(LogicalPosition::new(rect.x, rect.y))
+ })
+ .await?;
+ }
+
+ if rect.width != current_rect.width || rect.height != current_rect.height {
+ // Tauri sets the inner size. Chrome is measured in logical pixels before any
+ // display move so physical metrics from different scale factors are never mixed.
+ let inner_size = LogicalSize::new(
+ rect.width.saturating_sub(chrome_size.width),
+ rect.height.saturating_sub(chrome_size.height),
+ );
+ apply_window_change(self.window(), "tauri://resize", "set window size", || {
+ self.window().set_size(inner_size)
+ })
+ .await?;
+ }
+
+ self.get_window_rect().await
+ }
+
+ /// Maximize window
+ #[cfg(desktop)]
+ async fn maximize_window(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ apply_window_change(self.window(), "tauri://resize", "maximize window", || {
+ self.window().maximize()
+ })
+ .await?;
+ self.get_window_rect().await
+ }
+
+ /// Minimize window
+ #[cfg(desktop)]
+ async fn minimize_window(&self) -> Result<(), WebDriverErrorResponse> {
+ let _ = self.window().minimize();
+ Ok(())
+ }
+
+ /// Set window to fullscreen
+ #[cfg(desktop)]
+ async fn fullscreen_window(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ apply_window_change(
+ self.window(),
+ "tauri://resize",
+ "enter window fullscreen state",
+ || self.window().set_fullscreen(true),
+ )
+ .await?;
+ self.get_window_rect().await
+ }
+
+ /// Set window rectangle (mobile unsupported)
+ #[cfg(mobile)]
+ async fn set_window_rect(
+ &self,
+ _rect: WindowRect,
+ ) -> Result<WindowRect, WebDriverErrorResponse> {
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Setting window rect is not supported on mobile platforms",
+ ))
+ }
+
+ /// Maximize window (mobile unsupported)
+ #[cfg(mobile)]
+ async fn maximize_window(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Maximizing window is not supported on mobile platforms",
+ ))
+ }
+
+ /// Minimize window (mobile unsupported)
+ #[cfg(mobile)]
+ async fn minimize_window(&self) -> Result<(), WebDriverErrorResponse> {
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Minimizing window is not supported on mobile platforms",
+ ))
+ }
+
+ /// Set window to fullscreen (mobile unsupported)
+ #[cfg(mobile)]
+ async fn fullscreen_window(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Fullscreen window is not supported on mobile platforms",
+ ))
+ }
+
+ // =========================================================================
+ // Frames
+ // =========================================================================
+
+ /// Switch to a frame by ID (index or element reference)
+ async fn switch_to_frame(&self, id: FrameId) -> Result<(), WebDriverErrorResponse> {
+ match id {
+ FrameId::Index(index) => {
+ let script = format!(
+ r"(function() {{
+ var frames = document.querySelectorAll('iframe, frame');
+ if ({index} >= frames.length) {{
+ return false;
+ }}
+ return true;
+ }})()"
+ );
+ let result = self.evaluate_js(&script).await?;
+ if result.get("value") == Some(&Value::Bool(false)) {
+ return Err(WebDriverErrorResponse::no_such_frame());
+ }
+ Ok(())
+ }
+ FrameId::Element(js_var) => {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ if (el.tagName !== 'IFRAME' && el.tagName !== 'FRAME') {{
+ throw new Error('element is not a frame');
+ }}
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+ Ok(())
+ }
+ }
+ }
+
+ /// Switch to parent frame
+ async fn switch_to_parent_frame(&self) -> Result<(), WebDriverErrorResponse> {
+ // No-op - frame context is managed by the session, not the executor
+ Ok(())
+ }
+
+ // =========================================================================
+ // Cookies (using Tauri's native cookie APIs)
+ // =========================================================================
+
+ /// Get all cookies
+ async fn get_all_cookies(&self) -> Result<Vec<Cookie>, WebDriverErrorResponse> {
+ self.window()
+ .cookies()
+ .map(|cookies| cookies.iter().map(tauri_cookie_to_webdriver).collect())
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))
+ }
+
+ /// Get a specific cookie by name
+ async fn get_cookie(&self, name: &str) -> Result<Option<Cookie>, WebDriverErrorResponse> {
+ let cookies = self.get_all_cookies().await?;
+ Ok(cookies.into_iter().find(|c| c.name == name))
+ }
+
+ /// Add a cookie
+ async fn add_cookie(&self, mut cookie: Cookie) -> Result<(), WebDriverErrorResponse> {
+ // Per WebDriver spec: if no domain is specified, use the current page's domain
+ if cookie.domain.is_none() {
+ if let Ok(url) = self.window().url() {
+ cookie.domain = url.host_str().map(String::from);
+ }
+ }
+
+ // Default path to "/" if not specified
+ if cookie.path.is_none() {
+ cookie.path = Some("/".to_string());
+ }
+
+ let tauri_cookie = webdriver_cookie_to_tauri(&cookie);
+ self.window()
+ .set_cookie(tauri_cookie)
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))
+ }
+
+ /// Delete a cookie by name
+ async fn delete_cookie(&self, name: &str) -> Result<(), WebDriverErrorResponse> {
+ // Find the cookie first to get its exact domain/path for deletion
+ let cookies = self
+ .window()
+ .cookies()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ for cookie in cookies {
+ if cookie.name() == name {
+ self.window()
+ .delete_cookie(cookie)
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+ return Ok(());
+ }
+ }
+ Ok(())
+ }
+
+ /// Delete all cookies
+ async fn delete_all_cookies(&self) -> Result<(), WebDriverErrorResponse> {
+ let cookies = self
+ .window()
+ .cookies()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ for cookie in cookies {
+ self.window()
+ .delete_cookie(cookie)
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+ }
+ Ok(())
+ }
+
+ // =========================================================================
+ // Alerts (using per-window alert state)
+ // =========================================================================
+
+ /// Dismiss the current alert (cancel)
+ async fn dismiss_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let manager = self.window().app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(self.window().label());
+ if alert_state.respond(false, None) {
+ Ok(())
+ } else {
+ Err(WebDriverErrorResponse::no_such_alert())
+ }
+ }
+
+ /// Accept the current alert (OK)
+ async fn accept_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let manager = self.window().app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(self.window().label());
+ // For prompts, use input text if set, otherwise default text
+ let prompt_text = alert_state
+ .get_prompt_input()
+ .or_else(|| alert_state.get_default_text());
+ if alert_state.respond(true, prompt_text) {
+ Ok(())
+ } else {
+ Err(WebDriverErrorResponse::no_such_alert())
+ }
+ }
+
+ /// Get the text of the current alert
+ async fn get_alert_text(&self) -> Result<String, WebDriverErrorResponse> {
+ let manager = self.window().app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(self.window().label());
+ match alert_state.get_message() {
+ Some(msg) => Ok(msg),
+ None => Err(WebDriverErrorResponse::no_such_alert()),
+ }
+ }
+
+ /// Send text to the current alert (for prompts)
+ async fn send_alert_text(&self, text: &str) -> Result<(), WebDriverErrorResponse> {
+ let manager = self.window().app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(self.window().label());
+ match alert_state.get_alert_type() {
+ None => Err(WebDriverErrorResponse::no_such_alert()),
+ Some(AlertType::Prompt) => {
+ // Store the text for when acceptAlert is called
+ if alert_state.set_prompt_input(text.to_string()) {
+ Ok(())
+ } else {
+ Err(WebDriverErrorResponse::no_such_alert())
+ }
+ }
+ Some(_) => Err(WebDriverErrorResponse::element_not_interactable(
+ "User prompt is not a prompt dialog",
+ )),
+ }
+ }
+
+ // =========================================================================
+ // Print
+ // =========================================================================
+
+ /// Print page to PDF, returns base64-encoded PDF
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse>;
+}
+
+// =============================================================================
+// Helper Functions for Default Implementations
+// =============================================================================
+
+/// Extract string value from JavaScript result
+fn extract_string_value(result: &Value) -> Result<String, WebDriverErrorResponse> {
+ if let Some(success) = result.get("success").and_then(Value::as_bool) {
+ if success {
+ if let Some(value) = result.get("value") {
+ if let Some(s) = value.as_str() {
+ return Ok(s.to_string());
+ }
+ return Ok(value.to_string());
+ }
+ } else if let Some(error) = result.get("error").and_then(Value::as_str) {
+ return Err(WebDriverErrorResponse::javascript_error(error, None));
+ }
+ }
+ Ok(String::new())
+}
+
+/// Extract boolean value from JavaScript result
+fn extract_bool_value(result: &Value) -> Result<bool, WebDriverErrorResponse> {
+ if let Some(success) = result.get("success").and_then(Value::as_bool) {
+ if success {
+ if let Some(value) = result.get("value").and_then(Value::as_bool) {
+ return Ok(value);
+ }
+ } else if let Some(error) = result.get("error").and_then(Value::as_str) {
+ return Err(WebDriverErrorResponse::javascript_error(error, None));
+ }
+ }
+ Ok(false)
+}
+
+/// Extract usize value from JavaScript result
+fn extract_usize_value(result: &Value) -> Result<usize, WebDriverErrorResponse> {
+ if let Some(success) = result.get("success").and_then(Value::as_bool) {
+ if success {
+ if let Some(count) = result.get("value").and_then(Value::as_u64) {
+ return Ok(usize::try_from(count).unwrap_or(0));
+ }
+ } else if let Some(error) = result.get("error").and_then(Value::as_str) {
+ return Err(WebDriverErrorResponse::javascript_error(error, None));
+ }
+ }
+ Ok(0)
+}
+
+/// Extract raw Value from JavaScript result
+fn extract_value(result: &Value) -> Result<Value, WebDriverErrorResponse> {
+ if let Some(success) = result.get("success").and_then(Value::as_bool) {
+ if success {
+ return Ok(result.get("value").cloned().unwrap_or(Value::Null));
+ } else if let Some(error) = result.get("error").and_then(Value::as_str) {
+ return Err(WebDriverErrorResponse::javascript_error(error, None));
+ }
+ }
+ Ok(Value::Null)
+}
+
+/// Extract result from inner value (the __wd_success/__wd_value object)
+fn extract_script_result_from_inner(inner: &Value) -> Result<Value, WebDriverErrorResponse> {
+ // Check the script execution result
+ if let Some(success) = inner.get("__wd_success").and_then(Value::as_bool) {
+ if success {
+ return Ok(inner.get("__wd_value").cloned().unwrap_or(Value::Null));
+ } else if let Some(error) = inner.get("__wd_error").and_then(Value::as_str) {
+ return Err(WebDriverErrorResponse::javascript_error(error, None));
+ }
+ }
+
+ // If we got null or no wrapper structure, it's likely a syntax error
+ if inner.is_null() || inner.get("__wd_success").is_none() {
+ return Err(WebDriverErrorResponse::javascript_error(
+ "Script execution failed (possible syntax error)",
+ None,
+ ));
+ }
+
+ Ok(Value::Null)
+}
+
+/// Wrap a JavaScript script to execute within a specific frame context.
+/// If `frame_context` is empty (top-level), returns the script unchanged.
+/// Otherwise, wraps the script to navigate to the correct frame before execution.
+pub fn wrap_script_for_frame_context(script: &str, frame_context: &[FrameId]) -> String {
+ use std::fmt::Write;
+
+ if frame_context.is_empty() {
+ return script.to_string();
+ }
+
+ // Build JavaScript to navigate to the target frame
+ let mut frame_nav = String::new();
+ frame_nav.push_str("(function() {\n");
+ frame_nav.push_str(" var ctx = window;\n");
+ frame_nav.push_str(" var doc = document;\n");
+
+ for (i, frame_id) in frame_context.iter().enumerate() {
+ match frame_id {
+ FrameId::Index(index) => {
+ let _ = writeln!(
+ frame_nav,
+ " var frames{i} = doc.querySelectorAll('iframe, frame');"
+ );
+ let _ = writeln!(
+ frame_nav,
+ " if ({index} >= frames{i}.length) throw new Error('no such frame');"
+ );
+ let _ = writeln!(frame_nav, " var frame{i} = frames{i}[{index}];");
+ let _ = writeln!(
+ frame_nav,
+ " if (!frame{i}.contentWindow) throw new Error('no such frame');"
+ );
+ let _ = writeln!(frame_nav, " ctx = frame{i}.contentWindow;");
+ let _ = writeln!(frame_nav, " doc = frame{i}.contentDocument;");
+ }
+ FrameId::Element(js_var) => {
+ let _ = writeln!(frame_nav, " var frame{i} = window.{js_var};");
+ let _ = writeln!(
+ frame_nav,
+ " if (!frame{i} || !doc.contains(frame{i})) throw new Error('stale element reference');"
+ );
+ let _ = writeln!(
+ frame_nav,
+ " if (frame{i}.tagName !== 'IFRAME' && frame{i}.tagName !== 'FRAME') throw new Error('element is not a frame');"
+ );
+ let _ = writeln!(
+ frame_nav,
+ " if (!frame{i}.contentWindow) throw new Error('no such frame');"
+ );
+ let _ = writeln!(frame_nav, " ctx = frame{i}.contentWindow;");
+ let _ = writeln!(frame_nav, " doc = frame{i}.contentDocument;");
+ }
+ }
+ }
+
+ // Execute the original script in the frame context
+ // We use Function constructor to evaluate in the frame's context
+ let escaped_script = script
+ .replace('\\', "\\\\")
+ .replace('`', "\\`")
+ .replace("${", "\\${");
+
+ let _ = writeln!(frame_nav, " return ctx.eval(`{escaped_script}`);");
+ frame_nav.push_str("})()");
+
+ frame_nav
+}
+
+// =============================================================================
+// Cookie Conversion Functions
+// =============================================================================
+
+/// Convert Tauri cookie to `WebDriver` cookie
+fn tauri_cookie_to_webdriver(cookie: &TauriCookie<'static>) -> Cookie {
+ use tauri::webview::cookie::{Expiration, SameSite};
+
+ Cookie {
+ name: cookie.name().to_string(),
+ value: cookie.value().to_string(),
+ path: cookie.path().map(String::from),
+ domain: cookie.domain().map(String::from),
+ secure: cookie.secure().unwrap_or(false),
+ http_only: cookie.http_only().unwrap_or(false),
+ expiry: cookie.expires().and_then(|exp| match exp {
+ Expiration::DateTime(dt) => u64::try_from(dt.unix_timestamp()).ok(),
+ Expiration::Session => None,
+ }),
+ same_site: cookie.same_site().map(|ss| match ss {
+ SameSite::Strict => "Strict".to_string(),
+ SameSite::Lax => "Lax".to_string(),
+ SameSite::None => "None".to_string(),
+ }),
+ }
+}
+
+/// Convert `WebDriver` cookie to Tauri cookie
+fn webdriver_cookie_to_tauri(cookie: &Cookie) -> TauriCookie<'static> {
+ use tauri::webview::cookie::{time::OffsetDateTime, Expiration, SameSite};
+
+ let mut builder = TauriCookie::build((cookie.name.clone(), cookie.value.clone()));
+
+ if let Some(ref path) = cookie.path {
+ builder = builder.path(path.clone());
+ }
+
+ if let Some(ref domain) = cookie.domain {
+ builder = builder.domain(domain.clone());
+ }
+
+ // SECURITY: Always set Secure attribute for all cookies.
+ // This WebDriver implementation supports cookie testing per the WebDriver specification.
+ builder = builder.secure(true);
+
+ if cookie.http_only {
+ builder = builder.http_only(true);
+ }
+
+ if let Some(expiry) = cookie.expiry {
+ if let Some(dt) = i64::try_from(expiry)
+ .ok()
+ .and_then(|expiry| OffsetDateTime::from_unix_timestamp(expiry).ok())
+ {
+ builder = builder.expires(Expiration::DateTime(dt));
+ }
+ }
+
+ if let Some(ref same_site) = cookie.same_site {
+ let ss = match same_site.to_lowercase().as_str() {
+ "strict" => SameSite::Strict,
+ "lax" => SameSite::Lax,
+ _ => SameSite::None,
+ };
+ builder = builder.same_site(ss);
+ }
+
+ builder.build()
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/ios.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/ios.rs
new file mode 100644
index 00000000..4906dd8e
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/ios.rs
@@ -0,0 +1,355 @@
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::{Manager, Runtime, WebviewWindow};
+
+use crate::mobile::{
+ AlertResult, EvaluateJsArgs, JsResult, ScreenshotArgs, SendAlertTextArgs, TouchArgs, Webdriver,
+};
+use crate::platform::{
+ wrap_script_for_frame_context, FrameId, PlatformExecutor, PointerEventType, PrintOptions,
+ WindowRect,
+};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::Timeouts;
+
+/// iOS WKWebView executor using Tauri's mobile plugin bridge
+#[derive(Clone)]
+pub struct IOSExecutor<R: Runtime> {
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+}
+
+impl<R: Runtime> IOSExecutor<R> {
+ pub fn new(window: WebviewWindow<R>, timeouts: Timeouts, frame_context: Vec<FrameId>) -> Self {
+ Self {
+ window,
+ timeouts,
+ frame_context,
+ }
+ }
+}
+
+// =============================================================================
+// iOS-specific Plugin Method Arguments
+// =============================================================================
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AsyncScriptArgs {
+ script: String,
+ timeout_ms: u64,
+}
+
+#[async_trait]
+impl<R: Runtime + 'static> PlatformExecutor<R> for IOSExecutor<R> {
+ fn window(&self) -> &WebviewWindow<R> {
+ &self.window
+ }
+
+ fn script_timeout_ms(&self) -> u64 {
+ self.timeouts.script_ms
+ }
+
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ let wrapped_script = wrap_script_for_frame_context(script, &self.frame_context);
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let args = EvaluateJsArgs {
+ script: wrapped_script,
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("evaluateJs", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ // iOS returns the value directly (not JSON-encoded)
+ let value = result.value.unwrap_or(Value::Null);
+
+ Ok(serde_json::json!({
+ "success": true,
+ "value": value
+ }))
+ } else {
+ let error_msg = result.error.as_deref().unwrap_or("Unknown error");
+ if error_msg.to_lowercase().contains("timeout") {
+ Err(WebDriverErrorResponse::script_timeout())
+ } else {
+ Err(WebDriverErrorResponse::javascript_error(error_msg, None))
+ }
+ }
+ }
+
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ // Build wrapper that includes argument deserialization
+ // Swift wraps this in a Promise and provides __done via callAsyncJavaScript
+ let wrapper = format!(
+ r"var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+ var __args = {args_json}.map(deserializeArg);
+ __args.push(__done);
+ (function() {{ {script} }}).apply(null, __args);"
+ );
+
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let plugin_args = AsyncScriptArgs {
+ script: wrapper,
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("executeAsyncScript", plugin_args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ // iOS returns the value directly (not JSON-encoded) via callAsyncJavaScript
+ Ok(result.value.unwrap_or(Value::Null))
+ } else {
+ let error_msg = result.error.as_deref().unwrap_or("Unknown error");
+ if error_msg.to_lowercase().contains("timeout") {
+ Err(WebDriverErrorResponse::script_timeout())
+ } else {
+ Err(WebDriverErrorResponse::javascript_error(error_msg, None))
+ }
+ }
+ }
+
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let args = ScreenshotArgs {
+ timeout_ms: self.timeouts.script_ms,
+ };
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("takeScreenshot", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ if let Some(Value::String(base64)) = result.value {
+ Ok(base64)
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Screenshot returned invalid data",
+ ))
+ }
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ result.error.as_deref().unwrap_or("Screenshot failed"),
+ ))
+ }
+ }
+
+ async fn take_element_screenshot(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ // Scroll element into view first
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+
+ // Take full screenshot (element clipping can be added later)
+ self.take_screenshot().await
+ }
+
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let result: JsResult = webdriver
+ .0
+ .run_mobile_plugin_async("printToPdf", options)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ if result.success {
+ if let Some(Value::String(base64)) = result.value {
+ Ok(base64)
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Print returned invalid data",
+ ))
+ }
+ } else {
+ Err(WebDriverErrorResponse::unknown_error(
+ result.error.as_deref().unwrap_or("Print failed"),
+ ))
+ }
+ }
+
+ // Override pointer dispatch to use touch events on iOS
+ async fn dispatch_pointer_event(
+ &self,
+ event_type: PointerEventType,
+ x: i32,
+ y: i32,
+ _button: u32,
+ ) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let touch_type = match event_type {
+ PointerEventType::Down => "down",
+ PointerEventType::Up => "up",
+ PointerEventType::Move => "move",
+ };
+
+ let args = TouchArgs {
+ r#type: touch_type.to_string(),
+ x,
+ y,
+ };
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("dispatchTouch", args)
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ Ok(())
+ }
+
+ // Alert handling via plugin
+ async fn get_alert_text(&self) -> Result<String, WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let result: AlertResult = webdriver
+ .0
+ .run_mobile_plugin_async("getAlertText", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ result
+ .message
+ .ok_or_else(WebDriverErrorResponse::no_such_alert)
+ }
+
+ async fn accept_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("acceptAlert", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ Ok(())
+ }
+
+ async fn dismiss_alert(&self) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async("dismissAlert", ())
+ .await
+ .map_err(|e| {
+ if e.to_string().contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else {
+ WebDriverErrorResponse::unknown_error(&e.to_string())
+ }
+ })?;
+
+ Ok(())
+ }
+
+ async fn send_alert_text(&self, text: &str) -> Result<(), WebDriverErrorResponse> {
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ let _result: Value = webdriver
+ .0
+ .run_mobile_plugin_async(
+ "sendAlertText",
+ SendAlertTextArgs {
+ prompt_text: text.to_string(),
+ },
+ )
+ .await
+ .map_err(|e| {
+ let msg = e.to_string();
+ if msg.contains("no such alert") {
+ WebDriverErrorResponse::no_such_alert()
+ } else if msg.contains("not a prompt") {
+ WebDriverErrorResponse::element_not_interactable(
+ "User prompt is not a prompt dialog",
+ )
+ } else {
+ WebDriverErrorResponse::unknown_error(&msg)
+ }
+ })?;
+
+ Ok(())
+ }
+
+ // Cookies: Use default implementation from PlatformExecutor trait
+ // (Tauri's window().cookies() APIs work on iOS)
+
+ // =========================================================================
+ // Window Management
+ // =========================================================================
+
+ async fn get_window_rect(&self) -> Result<WindowRect, WebDriverErrorResponse> {
+ // Get viewport size from Swift plugin
+ let webdriver = self.window.app_handle().state::<Webdriver<R>>();
+
+ webdriver
+ .0
+ .run_mobile_plugin_async("getViewportSize", ())
+ .await
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/linux.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/linux.rs
new file mode 100644
index 00000000..364935ea
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/linux.rs
@@ -0,0 +1,548 @@
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
+use base64::Engine as _;
+use glib::MainContext;
+use javascriptcore::ValueExt;
+use serde_json::Value;
+use tauri::{Manager, Runtime, WebviewWindow};
+use tokio::sync::oneshot;
+use webkit2gtk::{
+ PrintOperationExt, ScriptDialogType, SnapshotOptions, SnapshotRegion, WebViewExt,
+};
+
+use crate::platform::alert_state::{AlertStateManager, AlertType, PendingAlert};
+use crate::platform::{wrap_script_for_frame_context, FrameId, PlatformExecutor, PrintOptions};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::Timeouts;
+
+/// Convert a JavaScriptCore value to JSON with multiple fallback strategies.
+///
+/// WebKitGTK's `to_json()` can fail for certain types (functions, undefined,
+/// circular refs, etc.). This function provides robust serialization:
+///
+/// 1. Try `to_json(0)` first (handles most primitives and objects)
+/// 2. Try type-specific conversions for special cases
+/// 3. Fall back to string representation or null
+fn js_value_to_json(js_value: &javascriptcore::Value) -> Result<Value, String> {
+ // Strategy 1: Try standard JSON serialization
+ if let Some(json_str) = js_value.to_json(0) {
+ match serde_json::from_str::<Value>(json_str.as_str()) {
+ Ok(value) => return Ok(value),
+ Err(_) => return Ok(Value::String(json_str.to_string())),
+ }
+ }
+
+ // Strategy 2: Handle null/undefined explicitly
+ if js_value.is_null() || js_value.is_undefined() {
+ return Ok(Value::Null);
+ }
+
+ // Strategy 3: Handle booleans
+ if js_value.is_boolean() {
+ return Ok(Value::Bool(js_value.to_boolean()));
+ }
+
+ // Strategy 4: Handle numbers - use to_string then parse
+ if js_value.is_number() {
+ let num_str = js_value.to_string();
+ if let Ok(n) = num_str.parse::<f64>() {
+ // Handle NaN and Infinity
+ if n.is_nan() || n.is_infinite() {
+ return Ok(Value::Null);
+ }
+ // Check if it's an integer
+ if n == n.trunc() && n >= i64::MIN as f64 && n <= i64::MAX as f64 {
+ return Ok(Value::Number(serde_json::Number::from(n as i64)));
+ }
+ // Handle as floating point
+ match serde_json::Number::from_f64(n) {
+ Some(num) => return Ok(Value::Number(num)),
+ None => return Ok(Value::Null),
+ }
+ }
+ return Ok(Value::Null);
+ }
+
+ // Strategy 5: Handle strings - to_string() returns String directly
+ if js_value.is_string() {
+ return Ok(Value::String(js_value.to_string()));
+ }
+
+ // Strategy 6: For arrays, objects, functions, etc. - convert to string
+ let string_repr = js_value.to_string();
+ if string_repr.is_empty() {
+ return Ok(Value::Null);
+ }
+ Ok(Value::String(string_repr))
+}
+
+/// Linux `WebKitGTK` executor
+#[derive(Clone)]
+pub struct LinuxExecutor<R: Runtime> {
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+}
+
+impl<R: Runtime> LinuxExecutor<R> {
+ pub fn new(window: WebviewWindow<R>, timeouts: Timeouts, frame_context: Vec<FrameId>) -> Self {
+ Self {
+ window,
+ timeouts,
+ frame_context,
+ }
+ }
+}
+
+/// Register `WebKitGTK` handlers at webview creation time.
+/// This is called from the plugin's `on_webview_ready` hook to ensure
+/// the script dialog handler is registered before any navigation completes.
+pub fn register_webview_handlers<R: Runtime>(webview: &tauri::Webview<R>) {
+ use crate::platform::alert_state::AlertResponse;
+ use webkit2gtk::WebViewExt as _;
+
+ // Get per-window alert state from the manager
+ let manager = webview.app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(webview.label());
+
+ let _ = webview.with_webview(move |webview| {
+ let webview = webview.inner().clone();
+ let alert_state = alert_state.clone();
+
+ // Connect to the script-dialog signal to intercept JS dialogs
+ webview.connect_script_dialog(move |_webview, dialog| {
+ let dialog_type = dialog.dialog_type();
+ let message = dialog.message().map(|s| s.to_string()).unwrap_or_default();
+
+ // Map WebKitGTK dialog type to our AlertType
+ let alert_type = match dialog_type {
+ ScriptDialogType::Alert => AlertType::Alert,
+ ScriptDialogType::Confirm => AlertType::Confirm,
+ ScriptDialogType::Prompt => AlertType::Prompt,
+ ScriptDialogType::BeforeUnloadConfirm | _ => {
+ // BEFOREUNLOAD or unknown - let default behavior handle it
+ return false;
+ }
+ };
+
+ let default_text = if alert_type == AlertType::Prompt {
+ dialog
+ .prompt_get_default_text()
+ .map(|s| s.to_string())
+ .filter(|s| !s.is_empty())
+ } else {
+ None
+ };
+
+ tracing::debug!("Intercepted {:?} dialog: {}", alert_type, message);
+
+ // Create channel for WebDriver response
+ let (tx, rx) = std::sync::mpsc::channel::<AlertResponse>();
+ alert_state.set_pending(PendingAlert {
+ message: message.clone(),
+ default_text: default_text.clone(),
+ alert_type,
+ responder: tx,
+ });
+
+ // Wait for WebDriver response with timeout
+ let timeout = std::time::Duration::from_secs(30);
+ let response = rx.recv_timeout(timeout);
+
+ match response {
+ Ok(AlertResponse {
+ accepted,
+ prompt_text,
+ }) => {
+ if alert_type == AlertType::Confirm {
+ dialog.confirm_set_confirmed(accepted);
+ } else if alert_type == AlertType::Prompt && accepted {
+ // Only set text if accepted - when dismissed, not calling
+ // prompt_set_text() causes JavaScript to receive null
+ let text = prompt_text.or(default_text).unwrap_or_default();
+ dialog.prompt_set_text(&text);
+ }
+ // For Alert type, nothing special to set
+ }
+ Err(_) => {
+ // Timeout - auto-accept
+ if alert_type == AlertType::Confirm {
+ dialog.confirm_set_confirmed(true);
+ }
+ }
+ }
+
+ // Return true to indicate we handled the dialog
+ true
+ });
+
+ tracing::debug!("Registered script dialog handler for webview");
+ });
+}
+
+#[async_trait]
+impl<R: Runtime + 'static> PlatformExecutor<R> for LinuxExecutor<R> {
+ // =========================================================================
+ // Window Access
+ // =========================================================================
+
+ fn window(&self) -> &WebviewWindow<R> {
+ &self.window
+ }
+
+ fn script_timeout_ms(&self) -> u64 {
+ self.timeouts.script_ms
+ }
+
+ // =========================================================================
+ // Core JavaScript Execution
+ // =========================================================================
+
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+ let script_owned = wrap_script_for_frame_context(script, &self.frame_context);
+
+ let result = self.window.with_webview(move |webview| {
+ let webview = webview.inner().clone();
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ // Use glib main context to spawn the async future
+ let ctx = MainContext::default();
+ ctx.spawn_local(async move {
+ let result = webview
+ .evaluate_javascript_future(&script_owned, None, None)
+ .await;
+ let response: Result<Value, String> = match result {
+ Ok(js_value) => {
+ // Try multiple serialization strategies for robustness
+ js_value_to_json(&js_value)
+ }
+ Err(e) => Err(e.to_string()),
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::javascript_error(
+ &e.to_string(),
+ None,
+ ));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(serde_json::json!({
+ "success": true,
+ "value": value
+ })),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ // =========================================================================
+ // Screenshots
+ // =========================================================================
+
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse> {
+ // Use WebKitGTK's native snapshot API
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| {
+ let webview = webview.inner().clone();
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ // Use glib main context to spawn the async future
+ let ctx = MainContext::default();
+ ctx.spawn_local(async move {
+ // Take snapshot of visible content
+ let result = webview
+ .snapshot_future(SnapshotRegion::Visible, SnapshotOptions::NONE)
+ .await;
+
+ let response: Result<String, String> = match result {
+ Ok(surface) => {
+ let mut png_data: Vec<u8> = Vec::new();
+ match gtk::cairo::ImageSurface::try_from(surface) {
+ Ok(image_surface) => match image_surface.write_to_png(&mut png_data) {
+ Ok(()) => Ok(BASE64_STANDARD.encode(&png_data)),
+ Err(e) => Err(format!("Failed to write PNG: {e}")),
+ },
+ Err(e) => Err(format!("Failed to downcast to ImageSurface: {e:?}")),
+ }
+ }
+ Err(e) => Err(e.to_string()),
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(base64))) => {
+ if base64.is_empty() {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Screenshot returned empty data",
+ ))
+ } else {
+ Ok(base64)
+ }
+ }
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::unknown_error(&error)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ async fn take_element_screenshot(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+
+ self.take_screenshot().await
+ }
+
+ // =========================================================================
+ // Print
+ // =========================================================================
+
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel::<Result<(), String>>();
+
+ // Create temp directory for PDF output
+ let temp_dir = tempfile::TempDir::new().map_err(|e| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to create temp dir: {e}"))
+ })?;
+ let pdf_path = temp_dir.path().join("print.pdf");
+ let pdf_path_clone = pdf_path.clone();
+
+ // Extract options before moving into closure
+ let orientation = options.orientation.clone();
+ let page_width = options.page_width;
+ let page_height = options.page_height;
+ let margin_top = options.margin_top;
+ let margin_bottom = options.margin_bottom;
+ let margin_left = options.margin_left;
+ let margin_right = options.margin_right;
+
+ let result = self.window.with_webview(move |webview| {
+ let webview = webview.inner().clone();
+
+ // Create print operation
+ let print_op = webkit2gtk::PrintOperation::new(&webview);
+
+ // Create page setup
+ let page_setup = gtk::PageSetup::new();
+
+ // Page size (cm to points: 1 cm = 28.35 points)
+ let width_points = page_width.unwrap_or(21.0) * 28.35;
+ let height_points = page_height.unwrap_or(29.7) * 28.35;
+ let paper_size = gtk::PaperSize::new_custom(
+ "custom",
+ "Custom",
+ width_points,
+ height_points,
+ gtk::Unit::Points,
+ );
+ page_setup.set_paper_size(&paper_size);
+
+ // Orientation
+ if orientation.as_deref() == Some("landscape") {
+ page_setup.set_orientation(gtk::PageOrientation::Landscape);
+ } else {
+ page_setup.set_orientation(gtk::PageOrientation::Portrait);
+ }
+
+ // Margins (cm to points)
+ page_setup.set_top_margin(margin_top.unwrap_or(1.0) * 28.35, gtk::Unit::Points);
+ page_setup.set_bottom_margin(margin_bottom.unwrap_or(1.0) * 28.35, gtk::Unit::Points);
+ page_setup.set_left_margin(margin_left.unwrap_or(1.0) * 28.35, gtk::Unit::Points);
+ page_setup.set_right_margin(margin_right.unwrap_or(1.0) * 28.35, gtk::Unit::Points);
+
+ print_op.set_page_setup(&page_setup);
+
+ // Print settings for PDF output
+ let settings = gtk::PrintSettings::new();
+ settings.set_printer("Print to File");
+ settings.set(
+ gtk::PRINT_SETTINGS_OUTPUT_URI,
+ Some(&format!("file://{}", pdf_path_clone.display())),
+ );
+ settings.set(gtk::PRINT_SETTINGS_OUTPUT_FILE_FORMAT, Some("pdf"));
+
+ print_op.set_print_settings(&settings);
+
+ // Connect to finished signal
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ print_op.connect_finished(move |_op| {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Ok(()));
+ }
+ }
+ });
+
+ // Run print operation (silent, no dialog)
+ let () = print_op.print();
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ // Wait for completion
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(()))) => {}
+ Ok(Ok(Err(error))) => {
+ return Err(WebDriverErrorResponse::unknown_error(&error));
+ }
+ Ok(Err(_)) => {
+ return Err(WebDriverErrorResponse::unknown_error("Channel closed"));
+ }
+ Err(_) => {
+ return Err(WebDriverErrorResponse::script_timeout());
+ }
+ }
+
+ // Read the PDF file
+ let pdf_data = std::fs::read(&pdf_path).map_err(|e| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to read PDF file: {e}"))
+ })?;
+
+ Ok(BASE64_STANDARD.encode(&pdf_data))
+ }
+
+ // =========================================================================
+ // Async Script Execution
+ // =========================================================================
+
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ // Build wrapper that includes argument deserialization.
+ // call_async_javascript_function_future treats the body as function statements,
+ // so `return` is required — without it the function returns undefined immediately.
+ let wrapper = format!(
+ r"return new Promise((resolve, reject) => {{
+ var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+ var __done = function(result, error) {{
+ if (error) {{
+ reject(new Error(typeof error === 'string' ? error : String(error)));
+ }} else {{
+ resolve(result);
+ }}
+ }};
+ var __args = {args_json}.map(deserializeArg);
+ __args.push(__done);
+ try {{
+ (function() {{ {script} }}).apply(null, __args);
+ }} catch (e) {{
+ reject(e);
+ }}
+ }})"
+ );
+
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| {
+ let webview = webview.inner().clone();
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ // Use glib main context to spawn the async future
+ let ctx = MainContext::default();
+ ctx.spawn_local(async move {
+ // call_async_javascript_function_future handles Promises natively
+ let result = webview
+ .call_async_javascript_function_future(&wrapper, None, None, None)
+ .await;
+
+ let response: Result<Value, String> = match result {
+ Ok(js_value) => {
+ if let Some(json_str) = js_value.to_json(0) {
+ match serde_json::from_str::<Value>(json_str.as_str()) {
+ Ok(value) => Ok(value),
+ Err(_) => Ok(Value::String(json_str.to_string())),
+ }
+ } else {
+ Ok(Value::Null)
+ }
+ }
+ Err(e) => Err(e.to_string()),
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::javascript_error(
+ &e.to_string(),
+ None,
+ ));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(value),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/macos.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/macos.rs
new file mode 100644
index 00000000..c31e70df
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/macos.rs
@@ -0,0 +1,970 @@
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
+use base64::Engine as _;
+use block2::{DynBlock, RcBlock};
+use objc2::rc::Retained;
+use objc2::runtime::{AnyObject, ProtocolObject};
+use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
+use objc2_app_kit::{NSBitmapImageFileType, NSBitmapImageRep, NSImage};
+use objc2_foundation::{
+ NSData, NSDictionary, NSError, NSObject, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes,
+ NSString, NSTimer,
+};
+use objc2_web_kit::{
+ WKContentWorld, WKFrameInfo, WKPDFConfiguration, WKScriptMessage, WKScriptMessageHandler,
+ WKSnapshotConfiguration, WKUIDelegate, WKUserContentController, WKWebView,
+};
+use serde_json::Value;
+use tauri::{Manager, Runtime, WebviewWindow};
+use tokio::sync::oneshot;
+
+use crate::eval_channel::EvalResultRegistry;
+use crate::platform::alert_state::{AlertState, AlertStateManager, AlertType, PendingAlert};
+use crate::platform::{wrap_script_for_frame_context, FrameId, PlatformExecutor, PrintOptions};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::Timeouts;
+
+/// Key for associating the UI delegate with the webview
+static DELEGATE_KEY: u8 = 0;
+
+/// macOS `WebView` executor using `WKWebView` native APIs
+#[derive(Clone)]
+pub struct MacOSExecutor<R: Runtime> {
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+}
+
+impl<R: Runtime> MacOSExecutor<R> {
+ pub fn new(window: WebviewWindow<R>, timeouts: Timeouts, frame_context: Vec<FrameId>) -> Self {
+ Self {
+ window,
+ timeouts,
+ frame_context,
+ }
+ }
+
+ /// Dispatch one `callAsyncJavaScript` attempt of a DirectEval wrapper. The returned receiver fires
+ /// when macOS 26.4's WebKit reclaims the completion with no value — the signal `execute_direct_eval`
+ /// uses to re-dispatch. When the completion *does* carry a value, it is delivered to `registry` as a
+ /// fallback for a lost message-handler post (first-write-wins keeps the post authoritative).
+ fn dispatch_eval_attempt(
+ &self,
+ wrapper: &str,
+ id: &str,
+ registry: &Arc<EvalResultRegistry>,
+ attempt: usize,
+ ) -> Result<oneshot::Receiver<()>, String> {
+ let (fail_tx, fail_rx) = oneshot::channel::<()>();
+ let wrapper = wrapper.to_owned();
+ let id = id.to_owned();
+ let registry = registry.clone();
+ // `RcBlock` is `Fn` but `Sender::send` consumes self, so guard the one-shot send (WebKit calls
+ // the completion once; this just makes a double-call harmless). Same pattern as `evaluate_js`.
+ let fail_tx = Arc::new(std::sync::Mutex::new(Some(fail_tx)));
+
+ self.window
+ .with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+ let ns_script = NSString::from_str(&wrapper);
+ let mtm = MainThreadMarker::new_unchecked();
+ let empty_dict: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::new();
+ let content_world = WKContentWorld::pageWorld(mtm);
+
+ let block = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| {
+ if !error.is_null() {
+ tracing::debug!(
+ "DirectEval completion reclaimed (attempt {attempt}): {}",
+ describe_ns_error(&*error)
+ );
+ if let Ok(mut guard) = fail_tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(());
+ }
+ }
+ return;
+ }
+ if !result.is_null() {
+ registry.complete(&id, ns_object_to_json(&*result));
+ }
+ });
+
+ wk_webview.callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler(
+ &ns_script,
+ Some(&empty_dict),
+ None,
+ &content_world,
+ Some(&block),
+ );
+ })
+ .map_err(|e| e.to_string())?;
+
+ Ok(fail_rx)
+ }
+}
+
+/// Register `WKWebView` handlers at webview creation time.
+/// This is called from the plugin's `on_webview_ready` hook to ensure
+/// the UI delegate is registered before any navigation completes.
+pub fn register_webview_handlers<R: Runtime>(webview: &tauri::Webview<R>) {
+ use objc2::ffi::{objc_setAssociatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC};
+
+ // Get per-window alert state from the manager
+ let manager = webview.app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(webview.label());
+ // Cloned Arc so the (non-generic) objc2 message handler can hold it for the webview's lifetime.
+ let eval_registry = webview
+ .app_handle()
+ .state::<Arc<EvalResultRegistry>>()
+ .inner()
+ .clone();
+
+ let _ = webview.with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+
+ let delegate = WebDriverUIDelegate::new(alert_state);
+ let delegate_protocol: Retained<ProtocolObject<dyn WKUIDelegate>> =
+ ProtocolObject::from_retained(delegate);
+
+ let _: () = msg_send![wk_webview, setUIDelegate: &*delegate_protocol];
+
+ // Associate delegate with webview - released when webview is deallocated
+ objc_setAssociatedObject(
+ std::ptr::from_ref::<WKWebView>(wk_webview)
+ .cast_mut()
+ .cast(),
+ std::ptr::addr_of!(DELEGATE_KEY).cast(),
+ Retained::into_raw(delegate_protocol).cast(),
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC,
+ );
+
+ // The DirectEval result channel (see execute_direct_eval). WKUserContentController retains the
+ // handler for the webview's lifetime, so — unlike the UI delegate — it needs no associated object.
+ let eval_handler = EvalMessageHandler::new(eval_registry);
+ let eval_proto: Retained<ProtocolObject<dyn WKScriptMessageHandler>> =
+ ProtocolObject::from_retained(eval_handler);
+ wk_webview
+ .configuration()
+ .userContentController()
+ .addScriptMessageHandler_name(&eval_proto, &NSString::from_str("wdioEvalResult"));
+
+ start_runloop_pump();
+
+ tracing::debug!("Registered UI delegate + eval message handler for webview");
+ });
+}
+
+/// Keep the app's main run loop waking on a headless/off-screen runner.
+///
+/// With no display, the app parks in `-[NSApplication run]` waiting for events, so WebKit doesn't
+/// promptly service WebContent's URL-scheme resource requests (page-load subresources) or eval
+/// dispatches — a DirectEval can then stall for tens of seconds and time out. A no-op timer in the
+/// run loop's common modes forces it to wake, draining that pending work each tick; the interval only
+/// bounds worst-case servicing latency (well under the command timeout). Harmless with a real display
+/// (the loop already pumps continuously). This plugin ships only in WebDriver-automation builds.
+///
+/// `Once`-guarded, so it is safe to schedule from both plugin `setup` (earliest — covers cold-start
+/// and deeplink navigation before the first webview is ready) and `on_webview_ready` (fallback).
+/// https://github.com/webdriverio/desktop-mobile/issues/540
+///
+/// # Safety
+/// Must be called on the main thread (schedules on the main run loop).
+pub unsafe fn start_runloop_pump() {
+ use std::sync::Once;
+ static PUMP: Once = Once::new();
+ PUMP.call_once(|| {
+ let block = RcBlock::new(|_timer: NonNull<NSTimer>| {});
+ let timer = NSTimer::timerWithTimeInterval_repeats_block(0.05, true, &block);
+ NSRunLoop::mainRunLoop().addTimer_forMode(&timer, NSRunLoopCommonModes);
+ tracing::debug!("Started macOS main run-loop pump for headless WebKit scheduling");
+ });
+}
+
+#[async_trait]
+impl<R: Runtime + 'static> PlatformExecutor<R> for MacOSExecutor<R> {
+ // =========================================================================
+ // Window Access
+ // =========================================================================
+
+ fn window(&self) -> &WebviewWindow<R> {
+ &self.window
+ }
+
+ fn script_timeout_ms(&self) -> u64 {
+ self.timeouts.script_ms
+ }
+
+ // =========================================================================
+ // Core JavaScript Execution
+ // =========================================================================
+
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+ let script_owned = wrap_script_for_frame_context(script, &self.frame_context);
+
+ let result = self.window.with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+ let ns_script = NSString::from_str(&script_owned);
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ let block = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| {
+ let response = if !error.is_null() {
+ let error_ref = &*error;
+ Err(describe_ns_error(error_ref))
+ } else if result.is_null() {
+ Ok(Value::Null)
+ } else {
+ let obj = &*result;
+ Ok(ns_object_to_json(obj))
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+
+ // Use evaluateJavaScript for script execution
+ wk_webview.evaluateJavaScript_completionHandler(&ns_script, Some(&block));
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::javascript_error(
+ &e.to_string(),
+ None,
+ ));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(serde_json::json!({
+ "success": true,
+ "value": value
+ })),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ // =========================================================================
+ // Async Script Execution (using callAsyncJavaScript)
+ // =========================================================================
+
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ // Build wrapper that includes argument deserialization.
+ // callAsyncJavaScript treats the body as function statements, so `return` is required —
+ // without it the function returns undefined immediately and the Promise is discarded.
+ let wrapper = format!(
+ r"return new Promise((resolve, reject) => {{
+ var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+ var __done = function(result, error) {{
+ if (error) {{
+ reject(new Error(typeof error === 'string' ? error : String(error)));
+ }} else {{
+ resolve(result);
+ }}
+ }};
+ var __args = {args_json}.map(deserializeArg);
+ __args.push(__done);
+ try {{
+ (function() {{ {script} }}).apply(null, __args);
+ }} catch (e) {{
+ reject(e);
+ }}
+ }})"
+ );
+
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+ let ns_script = NSString::from_str(&wrapper);
+ let mtm = MainThreadMarker::new_unchecked();
+
+ // Empty dictionary for arguments (we pass args via JSON in the script)
+ let empty_dict: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::new();
+
+ // Get the page content world
+ let content_world = WKContentWorld::pageWorld(mtm);
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ let block = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| {
+ let response = if !error.is_null() {
+ let error_ref = &*error;
+ Err(describe_ns_error(error_ref))
+ } else if result.is_null() {
+ Ok(Value::Null)
+ } else {
+ let obj = &*result;
+ Ok(ns_object_to_json(obj))
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+
+ wk_webview.callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler(
+ &ns_script,
+ Some(&empty_dict),
+ None,
+ &content_world,
+ Some(&block),
+ );
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::javascript_error(
+ &e.to_string(),
+ None,
+ ));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(value),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ /// DirectEval (`/wdio/eval`) with out-of-band result delivery + reclaim recovery.
+ ///
+ /// Each attempt is dispatched by `dispatch_eval_attempt` via `callAsyncJavaScript`, which keeps the
+ /// run loop pumping — on a headless runner the app's own `core.invoke` IPC response only completes
+ /// while WebKit holds a run-loop activity. The result is delivered primarily out-of-band: the
+ /// wrapper posts `{ id, result }` to the `wdioEvalResult` `WKScriptMessageHandler`, which completes
+ /// the `oneshot` awaited here. macOS 26.4's WebKit intermittently reclaims the `callAsyncJavaScript`
+ /// completion ("Completion handler for function call is no longer reachable"); usually the post
+ /// still lands, but sometimes the script never posts and this would otherwise dead-wait to the
+ /// script timeout (#540 residual). Two guards recover it without changing the happy path:
+ /// 1. **Fallback delivery** — when the completion *does* fire with a value, `dispatch_eval_attempt`
+ /// hands it to the same registry (first-write-wins keeps the post authoritative), so a lost
+ /// post resolves instead of dead-waiting.
+ /// 2. **Bounded re-dispatch** — when the completion is reclaimed with *no* value and no post lands
+ /// within `RECLAIM_GRACE`, re-run the script (up to `MAX_ATTEMPTS`). The grace lets a racing
+ /// post settle first; a genuine re-dispatch *re-executes* the script, so a non-idempotent eval
+ /// could double-apply — acceptable for the read-style evals `execute` runs in practice.
+ /// The whole sequence is bounded by `deadline`. Mirrors the Windows native-handler path
+ /// (`AsyncScriptState`). https://github.com/webdriverio/desktop-mobile/issues/540
+ ///
+ /// `wrapScriptForDirectEval` produces a callback-style script (`arguments[last]` is its
+ /// done-callback); `__report` forwards the result to the message handler then `resolve`s so the
+ /// `callAsyncJavaScript` promise settles.
+ async fn execute_direct_eval(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
+ let id = format!("wdio_de_{}", COUNTER.fetch_add(1, Ordering::Relaxed));
+
+ // Register the waiter before dispatching, so a fast report can't arrive before we're listening.
+ let registry = self
+ .window
+ .state::<Arc<EvalResultRegistry>>()
+ .inner()
+ .clone();
+ let mut rx = registry.register(id.clone());
+
+ // id is alphanumeric + '_', so it needs no escaping in the JS string literal below.
+ let wrapper = format!(
+ r#"return new Promise((resolve) => {{
+ var __report = function (r) {{
+ try {{ window.webkit.messageHandlers.wdioEvalResult.postMessage({{ id: "{id}", result: r }}); }} catch (e) {{}}
+ resolve(r);
+ }};
+ (function () {{ {script} }}).apply(null, [__report]);
+}});"#
+ );
+
+ const MAX_ATTEMPTS: usize = 3;
+ // After a reclaim, wait this long for a racing message-handler post before re-running.
+ const RECLAIM_GRACE: std::time::Duration = std::time::Duration::from_millis(750);
+ let deadline =
+ tokio::time::Instant::now() + std::time::Duration::from_millis(self.timeouts.script_ms);
+ let channel_closed = || WebDriverErrorResponse::unknown_error("Eval result channel closed");
+
+ // Retry only when WebKit reclaims the completion before a result was delivered; `timeout_at`
+ // bounds the whole sequence, so `Elapsed` (below) is the single script-timeout path.
+ let settled = tokio::time::timeout_at(deadline, async {
+ for attempt in 0..MAX_ATTEMPTS {
+ let fail_rx = self
+ .dispatch_eval_attempt(&wrapper, &id, &registry, attempt)
+ .map_err(|e| WebDriverErrorResponse::javascript_error(&e, None))?;
+ tokio::select! {
+ r = &mut rx => return r.map_err(|_| channel_closed()),
+ _ = fail_rx => {
+ if attempt + 1 == MAX_ATTEMPTS {
+ // Last attempt reclaimed: keep waiting for a late post until the deadline.
+ return (&mut rx).await.map_err(|_| channel_closed());
+ }
+ // Race a late post against the grace: if the script actually ran and posts
+ // here, return it — re-dispatching would execute the script (and any mocks it
+ // hits) a second time. Only re-dispatch once the grace elapses with no result.
+ tokio::select! {
+ r = &mut rx => return r.map_err(|_| channel_closed()),
+ _ = tokio::time::sleep(RECLAIM_GRACE) => {}
+ }
+ }
+ }
+ }
+ Err(WebDriverErrorResponse::script_timeout()) // unreachable: the final attempt returns above
+ })
+ .await;
+
+ let result = settled.unwrap_or_else(|_elapsed| Err(WebDriverErrorResponse::script_timeout()));
+ if result.is_err() {
+ registry.cancel(&id);
+ }
+ result
+ }
+
+ // =========================================================================
+ // Screenshots
+ // =========================================================================
+
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+ let mtm = MainThreadMarker::new_unchecked();
+ let config = WKSnapshotConfiguration::new(mtm);
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ let block = RcBlock::new(move |image: *mut NSImage, error: *mut NSError| {
+ let response = if !error.is_null() {
+ let error_ref = &*error;
+ Err(describe_ns_error(error_ref))
+ } else if image.is_null() {
+ Err("No image returned".to_string())
+ } else {
+ let image_ref = &*image;
+ image_to_png_base64(image_ref)
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+
+ wk_webview.takeSnapshotWithConfiguration_completionHandler(Some(&config), &block);
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(base64))) => Ok(base64),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::unknown_error(&error)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ async fn take_element_screenshot(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ // For element screenshots, we use JavaScript canvas approach
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+
+ // Use html2canvas-like approach if available, otherwise scroll into view
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+
+ // Return element bounds for clipping
+ var rect = el.getBoundingClientRect();
+ return {{
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height
+ }};
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+
+ self.take_screenshot().await
+ }
+
+ // =========================================================================
+ // Print
+ // =========================================================================
+
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse> {
+ // First, inject CSS @page rules for print settings
+ let page_width = options.page_width.unwrap_or(21.0);
+ let page_height = options.page_height.unwrap_or(29.7);
+ let margin_top = options.margin_top.unwrap_or(1.0);
+ let margin_bottom = options.margin_bottom.unwrap_or(1.0);
+ let margin_left = options.margin_left.unwrap_or(1.0);
+ let margin_right = options.margin_right.unwrap_or(1.0);
+ let orientation = options.orientation.as_deref().unwrap_or("portrait");
+
+ // Inject @page CSS rules
+ let css_script = format!(
+ r"(function() {{
+ var style = document.createElement('style');
+ style.id = '__webdriver_print_style';
+ style.textContent = `
+ @page {{
+ size: {page_width}cm {page_height}cm {orientation};
+ margin: {margin_top}cm {margin_right}cm {margin_bottom}cm {margin_left}cm;
+ }}
+ @media print {{
+ body {{
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }}
+ }}
+ `;
+ document.head.appendChild(style);
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&css_script).await?;
+
+ // Now create PDF using WKWebView's native API
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| unsafe {
+ let wk_webview: &WKWebView = &*webview.inner().cast();
+ let mtm = MainThreadMarker::new_unchecked();
+
+ // Create PDF configuration
+ let config = WKPDFConfiguration::new(mtm);
+ // Note: WKPDFConfiguration only has rect and allowTransparentBackground
+ // Page size/margins are handled via CSS @page rules above
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ let block = RcBlock::new(move |data: *mut NSData, error: *mut NSError| {
+ let response = if !error.is_null() {
+ let error_ref = &*error;
+ Err(describe_ns_error(error_ref))
+ } else if data.is_null() {
+ Err("No PDF data returned".to_string())
+ } else {
+ let data_ref = &*data;
+ let bytes = data_ref.to_vec();
+ Ok(bytes)
+ };
+
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ });
+
+ wk_webview.createPDFWithConfiguration_completionHandler(Some(&config), &block);
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ // Wait for result
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ let pdf_result = match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(bytes))) => Ok(bytes),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::unknown_error(&error)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ };
+
+ // Clean up injected style
+ let _ = self
+ .evaluate_js(
+ r"(function() {
+ var style = document.getElementById('__webdriver_print_style');
+ if (style) style.remove();
+ return true;
+ })()",
+ )
+ .await;
+
+ // Return base64 encoded PDF
+ pdf_result.map(|bytes| BASE64_STANDARD.encode(&bytes))
+ }
+}
+
+// =============================================================================
+// Utility Functions
+// =============================================================================
+
+/// Convert `NSImage` to PNG and encode as base64
+unsafe fn image_to_png_base64(image: &NSImage) -> Result<String, String> {
+ let tiff_data: Option<objc2::rc::Retained<NSData>> = image.TIFFRepresentation();
+ let tiff_data = tiff_data.ok_or("Failed to get TIFF representation")?;
+
+ let bitmap_rep = NSBitmapImageRep::imageRepWithData(&tiff_data)
+ .ok_or("Failed to create bitmap image rep")?;
+
+ let empty_dict: objc2::rc::Retained<NSDictionary<NSString>> = NSDictionary::new();
+ let png_data: Option<objc2::rc::Retained<NSData>> =
+ bitmap_rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &empty_dict);
+ let png_data = png_data.ok_or("Failed to convert to PNG")?;
+
+ let bytes = png_data.to_vec();
+ Ok(BASE64_STANDARD.encode(&bytes))
+}
+
+/// Build a diagnostic string for an `NSError` returned by a `WKWebView` completion handler.
+///
+/// `localizedDescription` for a script failure is frequently the opaque
+/// "A JavaScript exception occurred." with no detail. WebKit stashes the real
+/// exception text (and source location) in `userInfo` under the `WKJavaScriptException*`
+/// keys, so surface those when present. Without this, a script failure on the embedded
+/// executor is undiagnosable from the WDIO side (all we get back is the opaque string).
+unsafe fn describe_ns_error(error: &NSError) -> String {
+ let mut out = format!(
+ "{} (code {})",
+ error.localizedDescription(),
+ error.code()
+ );
+
+ let user_info = error.userInfo();
+ let get = |key: &str| -> Option<String> {
+ let ns_key = NSString::from_str(key);
+ // v is Retained<AnyObject>; ns_object_to_json takes &AnyObject. The explicit
+ // unsafe block is required because a closure body does not inherit the enclosing
+ // unsafe fn's context.
+ user_info
+ .objectForKey(&ns_key)
+ .and_then(|v| match unsafe { ns_object_to_json(&v) } {
+ Value::String(s) if !s.is_empty() => Some(s),
+ Value::Number(n) => Some(n.to_string()),
+ _ => None,
+ })
+ };
+
+ if let Some(message) = get("WKJavaScriptExceptionMessage") {
+ out.push_str(": ");
+ out.push_str(&message);
+ }
+ if let (Some(line), Some(column)) = (
+ get("WKJavaScriptExceptionLineNumber"),
+ get("WKJavaScriptExceptionColumnNumber"),
+ ) {
+ out.push_str(&format!(" @ {line}:{column}"));
+ }
+
+ out
+}
+
+/// Convert an `NSObject` to a JSON value
+pub(super) unsafe fn ns_object_to_json(obj: &AnyObject) -> Value {
+ use objc2_foundation::NSString as NSStr;
+
+ let class = obj.class();
+ let class_name = class.name().to_str().unwrap_or("");
+
+ if class_name.contains("String") {
+ let ns_str: &NSStr = &*std::ptr::from_ref::<AnyObject>(obj).cast::<NSStr>();
+ return Value::String(ns_str.to_string());
+ }
+
+ if class_name.contains("Number") || class_name.contains("Boolean") {
+ use objc2::msg_send;
+ use objc2::runtime::Bool;
+
+ if class_name.contains("Boolean") {
+ let bool_val: Bool = msg_send![obj, boolValue];
+ return Value::Bool(bool_val.as_bool());
+ }
+
+ let double_val: f64 = msg_send![obj, doubleValue];
+ let int_val: i64 = msg_send![obj, longLongValue];
+
+ #[allow(clippy::cast_precision_loss)]
+ if (int_val as f64 - double_val).abs() < f64::EPSILON {
+ return Value::Number(serde_json::Number::from(int_val));
+ } else if let Some(n) = serde_json::Number::from_f64(double_val) {
+ return Value::Number(n);
+ }
+ return Value::Null;
+ }
+
+ if class_name.contains("Array") {
+ use objc2::msg_send;
+
+ let count: usize = msg_send![obj, count];
+ let mut arr = Vec::new();
+ for i in 0..count {
+ let item: *mut AnyObject = msg_send![obj, objectAtIndex: i];
+ if !item.is_null() {
+ arr.push(ns_object_to_json(&*item));
+ }
+ }
+ return Value::Array(arr);
+ }
+
+ if class_name.contains("Dictionary") {
+ use objc2::msg_send;
+
+ let keys: *mut AnyObject = msg_send![obj, allKeys];
+ if keys.is_null() {
+ return Value::Object(serde_json::Map::new());
+ }
+
+ let count: usize = msg_send![keys, count];
+ let mut map = serde_json::Map::new();
+
+ for i in 0..count {
+ let key: *mut AnyObject = msg_send![keys, objectAtIndex: i];
+ if key.is_null() {
+ continue;
+ }
+
+ let key_class = (&*key).class().name().to_str().unwrap_or("");
+ if !key_class.contains("String") {
+ continue;
+ }
+
+ let ns_key: &NSStr = &*key.cast_const().cast::<NSStr>();
+ let key_str = ns_key.to_string();
+
+ let val: *mut AnyObject = msg_send![obj, objectForKey: key];
+ if !val.is_null() {
+ map.insert(key_str, ns_object_to_json(&*val));
+ }
+ }
+ return Value::Object(map);
+ }
+
+ if class_name.contains("Null") {
+ return Value::Null;
+ }
+
+ Value::Null
+}
+
+// =============================================================================
+// Native UI Delegate for JavaScript Alerts
+// =============================================================================
+
+/// Instance variables for UI delegate - stores per-window alert state
+struct WebDriverUIDelegateIvars {
+ alert_state: Arc<AlertState>,
+}
+
+// SAFETY: Arc<AlertState> is Send + Sync
+unsafe impl Send for WebDriverUIDelegateIvars {}
+unsafe impl Sync for WebDriverUIDelegateIvars {}
+
+define_class!(
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ #[name = "WebDriverUIDelegate"]
+ #[ivars = WebDriverUIDelegateIvars]
+ struct WebDriverUIDelegate;
+
+ unsafe impl NSObjectProtocol for WebDriverUIDelegate {}
+
+ #[allow(non_snake_case)]
+ unsafe impl WKUIDelegate for WebDriverUIDelegate {
+ /// Handle JavaScript `alert()` calls
+ #[unsafe(method(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:))]
+ fn webView_runJavaScriptAlertPanelWithMessage_initiatedByFrame_completionHandler(
+ &self,
+ _webview: &WKWebView,
+ message: &NSString,
+ _frame: &WKFrameInfo,
+ completion_handler: &DynBlock<dyn Fn()>,
+ ) {
+ let message_str = message.to_string();
+ tracing::debug!("Intercepted alert: {message_str}");
+
+ // Create channel for WebDriver response
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ // Store alert state with responder (using per-window state from ivars)
+ self.ivars().alert_state.set_pending(PendingAlert {
+ message: message_str,
+ default_text: None,
+ alert_type: AlertType::Alert,
+ responder: tx,
+ });
+
+ // Wait for accept/dismiss (with timeout)
+ let timeout = std::time::Duration::from_secs(30);
+ let _ = rx.recv_timeout(timeout);
+
+ completion_handler.call(());
+ }
+
+ /// Handle JavaScript `confirm()` calls
+ #[unsafe(method(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:))]
+ fn webView_runJavaScriptConfirmPanelWithMessage_initiatedByFrame_completionHandler(
+ &self,
+ _webview: &WKWebView,
+ message: &NSString,
+ _frame: &WKFrameInfo,
+ completion_handler: &DynBlock<dyn Fn(objc2::runtime::Bool)>,
+ ) {
+ let message_str = message.to_string();
+ tracing::debug!("Intercepted confirm: {message_str}");
+
+ // Create channel for WebDriver response
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ // Store confirm state with responder (using per-window state from ivars)
+ self.ivars().alert_state.set_pending(PendingAlert {
+ message: message_str,
+ default_text: None,
+ alert_type: AlertType::Confirm,
+ responder: tx,
+ });
+
+ // Wait for accept/dismiss (with timeout)
+ let timeout = std::time::Duration::from_secs(30);
+ let response = rx.recv_timeout(timeout);
+
+ // Return true if accepted, false if dismissed or timeout
+ let accepted = response.map(|r| r.accepted).unwrap_or(true);
+
+ completion_handler.call((objc2::runtime::Bool::from(accepted),));
+ }
+
+ /// Handle JavaScript `prompt()` calls
+ #[unsafe(method(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:))]
+ fn webView_runJavaScriptTextInputPanelWithPrompt_defaultText_initiatedByFrame_completionHandler(
+ &self,
+ _webview: &WKWebView,
+ prompt: &NSString,
+ default_text: Option<&NSString>,
+ _frame: &WKFrameInfo,
+ completion_handler: &DynBlock<dyn Fn(*mut NSString)>,
+ ) {
+ let prompt_str = prompt.to_string();
+ let default = default_text.map(std::string::ToString::to_string);
+ tracing::debug!("Intercepted prompt: {prompt_str}");
+
+ // Create channel for WebDriver response
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ // Store prompt state with responder (using per-window state from ivars)
+ self.ivars().alert_state.set_pending(PendingAlert {
+ message: prompt_str,
+ default_text: default.clone(),
+ alert_type: AlertType::Prompt,
+ responder: tx,
+ });
+
+ // Wait for accept/dismiss (with timeout)
+ let timeout = std::time::Duration::from_secs(30);
+ let response = rx.recv_timeout(timeout);
+
+ // Return the prompt text if accepted, null if dismissed
+ let result: *mut NSString = match response {
+ Ok(r) if r.accepted => {
+ let text = r.prompt_text.or(default).unwrap_or_default();
+ let ns_str = NSString::from_str(&text);
+ Retained::into_raw(ns_str)
+ }
+ _ => std::ptr::null_mut(), // Dismissed or timeout = null (cancel)
+ };
+
+ completion_handler.call((result,));
+ }
+ }
+);
+
+impl WebDriverUIDelegate {
+ /// # Safety
+ /// Must be called from the main thread.
+ unsafe fn new(alert_state: Arc<AlertState>) -> Retained<Self> {
+ let mtm = MainThreadMarker::new_unchecked();
+ let this = Self::alloc(mtm);
+ let this = this.set_ivars(WebDriverUIDelegateIvars { alert_state });
+ msg_send![super(this), init]
+ }
+}
+
+struct EvalMessageHandlerIvars {
+ registry: Arc<EvalResultRegistry>,
+}
+
+// SAFETY: Arc<EvalResultRegistry> is Send + Sync
+unsafe impl Send for EvalMessageHandlerIvars {}
+unsafe impl Sync for EvalMessageHandlerIvars {}
+
+define_class!(
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ #[name = "WdioEvalMessageHandler"]
+ #[ivars = EvalMessageHandlerIvars]
+ struct EvalMessageHandler;
+
+ unsafe impl NSObjectProtocol for EvalMessageHandler {}
+
+ #[allow(non_snake_case)]
+ unsafe impl WKScriptMessageHandler for EvalMessageHandler {
+ /// Delivers `{ id, result }` posted by the DirectEval wrapper to the waiting executor.
+ #[unsafe(method(userContentController:didReceiveScriptMessage:))]
+ fn userContentController_didReceiveScriptMessage(
+ &self,
+ _controller: &WKUserContentController,
+ message: &WKScriptMessage,
+ ) {
+ let json = unsafe { ns_object_to_json(&message.body()) };
+ let (Some(id), Some(result)) =
+ (json.get("id").and_then(Value::as_str), json.get("result").cloned())
+ else {
+ tracing::warn!("wdioEvalResult message missing id/result");
+ return;
+ };
+ self.ivars().registry.complete(id, result);
+ }
+ }
+);
+
+impl EvalMessageHandler {
+ /// # Safety
+ /// Must be called from the main thread.
+ unsafe fn new(registry: Arc<EvalResultRegistry>) -> Retained<Self> {
+ let mtm = MainThreadMarker::new_unchecked();
+ let this = Self::alloc(mtm);
+ let this = this.set_ivars(EvalMessageHandlerIvars { registry });
+ msg_send![super(this), init]
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/mod.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/mod.rs
new file mode 100644
index 00000000..933ddcd8
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/mod.rs
@@ -0,0 +1,113 @@
+pub(crate) mod alert_state;
+mod executor;
+
+pub use alert_state::AlertStateManager;
+pub use executor::*;
+
+#[cfg(target_os = "windows")]
+pub use windows::AsyncScriptState;
+#[cfg(target_os = "windows")]
+pub use windows::FrameRegistry;
+#[cfg(target_os = "windows")]
+pub use windows::ScriptExecutionLocks;
+
+#[cfg(target_os = "macos")]
+mod macos;
+
+#[cfg(target_os = "windows")]
+mod windows;
+
+#[cfg(target_os = "linux")]
+mod linux;
+
+#[cfg(target_os = "android")]
+mod android;
+
+#[cfg(target_os = "ios")]
+mod ios;
+
+use std::sync::Arc;
+use tauri::{Runtime, WebviewWindow};
+
+use crate::webdriver::Timeouts;
+
+/// Create a platform-specific executor for the given window
+#[cfg(target_os = "macos")]
+pub fn create_executor<R: Runtime + 'static>(
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+) -> Arc<dyn PlatformExecutor<R>> {
+ Arc::new(macos::MacOSExecutor::new(window, timeouts, frame_context))
+}
+
+/// Create a platform-specific executor for the given window
+#[cfg(target_os = "windows")]
+pub fn create_executor<R: Runtime + 'static>(
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+) -> Arc<dyn PlatformExecutor<R>> {
+ Arc::new(windows::WindowsExecutor::new(
+ window,
+ timeouts,
+ frame_context,
+ ))
+}
+
+/// Create a platform-specific executor for the given window
+#[cfg(target_os = "linux")]
+pub fn create_executor<R: Runtime + 'static>(
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+) -> Arc<dyn PlatformExecutor<R>> {
+ Arc::new(linux::LinuxExecutor::new(window, timeouts, frame_context))
+}
+
+/// Create a platform-specific executor for the given window
+#[cfg(target_os = "android")]
+pub fn create_executor<R: Runtime + 'static>(
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+) -> Arc<dyn PlatformExecutor<R>> {
+ Arc::new(android::AndroidExecutor::new(
+ window,
+ timeouts,
+ frame_context,
+ ))
+}
+
+/// Create a platform-specific executor for the given window
+#[cfg(target_os = "ios")]
+pub fn create_executor<R: Runtime + 'static>(
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+) -> Arc<dyn PlatformExecutor<R>> {
+ Arc::new(ios::IOSExecutor::new(window, timeouts, frame_context))
+}
+
+/// Register platform-specific webview handlers at webview creation time.
+/// This is called from the plugin's `on_webview_ready` hook.
+/// Note: Mobile platforms (Android/iOS) handle this via native plugins.
+pub fn register_webview_handlers<R: Runtime>(webview: &tauri::Webview<R>) {
+ #[cfg(target_os = "windows")]
+ windows::register_webview_handlers(webview);
+ #[cfg(target_os = "macos")]
+ macos::register_webview_handlers(webview);
+ #[cfg(target_os = "linux")]
+ linux::register_webview_handlers(webview);
+
+ let _ = webview; // Avoid unused variable warning on platforms without handlers
+}
+
+/// Start the macOS headless run-loop pump as early as possible — from the plugin's `setup` hook, on
+/// the main thread — so it covers cold-start / deeplink navigation before the first webview is ready.
+/// `Once`-guarded in `macos::start_runloop_pump`, so the `on_webview_ready` call remains a harmless
+/// fallback. macOS only. See #540.
+#[cfg(target_os = "macos")]
+pub fn start_runloop_pump_early<R: Runtime>(app: &tauri::AppHandle<R>) {
+ let _ = app.run_on_main_thread(|| unsafe { macos::start_runloop_pump() });
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/windows.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/windows.rs
new file mode 100644
index 00000000..b91cf96f
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/platform/windows.rs
@@ -0,0 +1,1359 @@
+use std::collections::{HashMap, HashSet};
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
+use base64::Engine as _;
+use serde_json::Value;
+use tauri::{Manager, Runtime, WebviewWindow};
+use tokio::sync::oneshot;
+use webview2_com::Microsoft::Web::WebView2::Win32::{
+ ICoreWebView2, ICoreWebView2CapturePreviewCompletedHandler, ICoreWebView2Environment6,
+ ICoreWebView2ExecuteScriptCompletedHandler, ICoreWebView2Frame,
+ ICoreWebView2FrameCreatedEventHandler, ICoreWebView2Frame2,
+ ICoreWebView2PrintToPdfCompletedHandler, ICoreWebView2ScriptDialogOpeningEventHandler,
+ ICoreWebView2WebMessageReceivedEventHandler, ICoreWebView2_4, ICoreWebView2_7,
+ COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG, COREWEBVIEW2_PRINT_ORIENTATION_LANDSCAPE,
+ COREWEBVIEW2_PRINT_ORIENTATION_PORTRAIT,
+};
+use windows::core::{Interface, HSTRING, PCWSTR};
+use windows::Win32::Foundation::HGLOBAL;
+use windows::Win32::System::Com::StructuredStorage::CreateStreamOnHGlobal;
+use windows::Win32::System::Com::{
+ CoInitializeEx, COINIT_APARTMENTTHREADED, STATFLAG_NONAME, STREAM_SEEK_SET,
+};
+use windows_core::BOOL;
+
+use crate::platform::alert_state::{AlertState, AlertStateManager, AlertType, PendingAlert};
+use crate::platform::{wrap_script_for_frame_context, FrameId, PlatformExecutor, PrintOptions};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::Timeouts;
+
+// =============================================================================
+// Async Script State
+// =============================================================================
+
+/// Handler name used for postMessage calls
+const HANDLER_NAME: &str = "webdriver_async";
+
+/// Serializes concurrent WebView2 ExecuteScript calls per webview window.
+/// On Windows, issuing multiple concurrent ExecuteScript calls against the same
+/// CoreWebView2 can cause completion handlers to be silently dropped or the
+/// webview to enter an invalid state, causing script timeouts or app crashes.
+/// A per-label tokio::sync::Mutex ensures only one script executes at a time.
+#[derive(Default)]
+pub struct ScriptExecutionLocks {
+ locks: std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
+}
+
+impl ScriptExecutionLocks {
+ pub fn get(&self, label: &str) -> Arc<tokio::sync::Mutex<()>> {
+ let mut m = self.locks.lock().expect("ScriptExecutionLocks poisoned");
+ m.entry(label.to_string())
+ .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
+ .clone()
+ }
+}
+
+/// Shared state for pending async script operations.
+/// This is managed via Tauri's state system (`app.manage()`).
+#[derive(Default)]
+pub struct AsyncScriptState {
+ pending: Mutex<HashMap<String, oneshot::Sender<Result<Value, String>>>>,
+ /// Track which webviews have native handlers registered (by window label)
+ registered_handlers: Mutex<HashSet<String>>,
+}
+
+impl AsyncScriptState {
+ /// Register a pending async operation and return the receiver
+ pub fn register(&self, id: String) -> oneshot::Receiver<Result<Value, String>> {
+ let (tx, rx) = oneshot::channel();
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.insert(id, tx);
+ }
+ rx
+ }
+
+ /// Complete a pending async operation with a result
+ pub fn complete(&self, id: &str, result: Result<Value, String>) {
+ if let Ok(mut pending) = self.pending.lock() {
+ if let Some(tx) = pending.remove(id) {
+ let _ = tx.send(result);
+ }
+ }
+ }
+
+ /// Cancel a pending async operation
+ pub fn cancel(&self, id: &str) {
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.remove(id);
+ }
+ }
+
+ /// Check if a handler is registered for a window label, and mark it as registered if not.
+ /// Returns true if the handler was already registered, false if it needs to be registered.
+ pub fn mark_handler_registered(&self, label: &str) -> bool {
+ if let Ok(mut handlers) = self.registered_handlers.lock() {
+ !handlers.insert(label.to_string())
+ } else {
+ false
+ }
+ }
+}
+
+/// Wrapper for raw COM pointer to allow sending across threads.
+/// SAFETY: The COM object must only be accessed from a COM-initialized thread.
+struct SendableComPtr(*mut std::ffi::c_void);
+unsafe impl Send for SendableComPtr {}
+unsafe impl Sync for SendableComPtr {}
+
+impl SendableComPtr {
+ fn as_ptr(&self) -> *mut std::ffi::c_void {
+ self.0
+ }
+}
+
+// =============================================================================
+// Native frame registry
+// =============================================================================
+
+/// Top-level `WebView2` frames captured from `FrameCreated`.
+///
+/// Upstream drives "switch to frame" by evaluating the script inside
+/// `frame.contentWindow`. That only works same-origin: the shell lives on
+/// `tauri://localhost` while the embedded harness is served from
+/// `http://127.0.0.1:<port>`, so `contentDocument` is `null` and every
+/// frame-context script times out (WebDriver `execute/sync` script timeout).
+///
+/// Holding the native `ICoreWebView2Frame` lets the executor call
+/// `ICoreWebView2Frame2::ExecuteScript` instead, which the engine routes to the
+/// frame regardless of the origin boundary. Only depth-1 frames are captured;
+/// deeper nesting keeps the upstream JS path.
+#[derive(Default, Clone)]
+pub struct FrameRegistry {
+ frames: Arc<Mutex<HashMap<String, Vec<FrameHandle>>>>,
+}
+
+/// A frame plus the single COM reference the registry keeps alive.
+struct FrameHandle {
+ ptr: SendableComPtr,
+ name: String,
+}
+
+impl FrameHandle {
+ /// Hand out the frame as a `Send`-safe pointer holding its **own** COM reference.
+ ///
+ /// The registry must keep its reference: the caller reconstructs the interface inside
+ /// `with_webview` and drops it when the closure ends, which Releases it. `clone()`
+ /// AddRefs for that future Release, and `into_raw()` returns the registry's own
+ /// reference untouched — without this the registry would be left holding a freed
+ /// pointer and the next script would crash the process.
+ fn acquire(&self) -> SendableComPtr {
+ let borrowed = unsafe { ICoreWebView2Frame::from_raw(self.ptr.as_ptr()) };
+ let owned = borrowed.clone();
+ let _ = borrowed.into_raw();
+ SendableComPtr(owned.into_raw())
+ }
+}
+
+impl FrameRegistry {
+ fn register(&self, label: &str, frame: &ICoreWebView2Frame, name: String) {
+ let ptr = SendableComPtr(frame.clone().into_raw());
+ if let Ok(mut frames) = self.frames.lock() {
+ frames
+ .entry(label.to_string())
+ .or_default()
+ .push(FrameHandle { ptr, name });
+ }
+ }
+
+ fn get(&self, label: &str, index: usize) -> Option<(SendableComPtr, String)> {
+ let frames = self.frames.lock().ok()?;
+ let handle = frames.get(label)?.get(index)?;
+ Some((handle.acquire(), handle.name.clone()))
+ }
+}
+
+mod frames {
+ use webview2_com::Microsoft::Web::WebView2::Win32::{
+ ICoreWebView2, ICoreWebView2FrameCreatedEventArgs, ICoreWebView2FrameCreatedEventHandler,
+ ICoreWebView2FrameCreatedEventHandler_Impl,
+ };
+ use windows::core::implement;
+
+ use super::FrameRegistry;
+
+ #[implement(ICoreWebView2FrameCreatedEventHandler)]
+ pub struct FrameCreatedHandler {
+ registry: FrameRegistry,
+ label: String,
+ }
+
+ unsafe impl Send for FrameCreatedHandler {}
+ unsafe impl Sync for FrameCreatedHandler {}
+
+ impl FrameCreatedHandler {
+ pub fn new(registry: FrameRegistry, label: String) -> Self {
+ Self { registry, label }
+ }
+ }
+
+ impl ICoreWebView2FrameCreatedEventHandler_Impl for FrameCreatedHandler_Impl {
+ fn Invoke(
+ &self,
+ _sender: windows::core::Ref<'_, ICoreWebView2>,
+ args: windows::core::Ref<'_, ICoreWebView2FrameCreatedEventArgs>,
+ ) -> windows::core::Result<()> {
+ let Some(args) = args.clone() else {
+ return Ok(());
+ };
+
+ unsafe {
+ let Ok(frame) = args.Frame() else {
+ tracing::error!("FrameCreated: args.Frame() failed");
+ return Ok(());
+ };
+
+ let name = {
+ let mut ptr = windows::core::PWSTR::null();
+ if frame.Name(&raw mut ptr).is_ok() {
+ ptr.to_string().unwrap_or_default()
+ } else {
+ String::new()
+ }
+ };
+
+ tracing::debug!("FrameCreated: name='{name}' registered for '{}'", self.label);
+ self.registry.register(&self.label, &frame, name);
+ }
+
+ Ok(())
+ }
+ }
+}
+
+use frames::FrameCreatedHandler;
+
+/// Register the `FrameCreated` handler so frame handles are captured as they appear.
+///
+/// # Safety
+/// Must be called from a COM-initialized thread with a valid webview.
+unsafe fn register_frame_handler(
+ webview: &ICoreWebView2,
+ registry: FrameRegistry,
+ label: &str,
+) {
+ let Ok(webview4) = webview.cast::<ICoreWebView2_4>() else {
+ tracing::error!("CoreWebView2 does not expose ICoreWebView2_4; frames unavailable");
+ return;
+ };
+
+ let handler: ICoreWebView2FrameCreatedEventHandler =
+ FrameCreatedHandler::new(registry, label.to_string()).into();
+
+ let mut token = std::mem::zeroed();
+ if let Err(e) = webview4.add_FrameCreated(&handler, &raw mut token) {
+ tracing::error!("Failed to register FrameCreated handler: {e:?}");
+ } else {
+ tracing::debug!("Registered native frame handler for '{label}'");
+ }
+
+ // Prevent handler from being dropped - leak it to keep the COM ref alive
+ std::mem::forget(handler);
+}
+
+/// Windows `WebView2` executor
+#[derive(Clone)]
+pub struct WindowsExecutor<R: Runtime> {
+ window: WebviewWindow<R>,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+}
+
+impl<R: Runtime> WindowsExecutor<R> {
+ pub fn new(window: WebviewWindow<R>, timeouts: Timeouts, frame_context: Vec<FrameId>) -> Self {
+ Self {
+ window,
+ timeouts,
+ frame_context,
+ }
+ }
+}
+
+impl<R: Runtime + 'static> WindowsExecutor<R> {
+ /// Core WebView2 script execution — no per-webview lock.
+ /// Callers that need serialization must acquire the lock from
+ /// `ScriptExecutionLocks` before calling this method.
+ ///
+ /// Runs `script` in the top-level context, unwrapped.
+ async fn evaluate_js_top_level(
+ &self,
+ script: &str,
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+ let script_preview: String = script.chars().take(100).collect();
+ let script_owned = script.to_string();
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ let result = self.window.with_webview({
+ let tx = tx.clone();
+ move |webview| unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+
+ if let Ok(webview2) = webview.controller().CoreWebView2() {
+ let script_hstring = HSTRING::from(&script_owned);
+
+ let handler: ICoreWebView2ExecuteScriptCompletedHandler =
+ ExecuteScriptHandler::new(tx.clone()).into();
+
+ if let Err(e) = webview2.ExecuteScript(PCWSTR(script_hstring.as_ptr()), &handler) {
+ tracing::error!("ExecuteScript call failed for script '{}...': {e:?}", script_preview);
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("ExecuteScript failed: {e:?}")));
+ }
+ }
+ }
+ } else {
+ tracing::error!("Failed to get CoreWebView2 for script execution");
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err("Failed to get CoreWebView2".to_string()));
+ }
+ }
+ }
+ }
+ });
+
+ if let Err(e) = result {
+ tracing::error!("with_webview failed: {e}");
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(e.to_string()));
+ }
+ }
+ }
+
+ self.collect_script_result(rx).await
+ }
+
+ /// Run `script` inside a native frame via `ICoreWebView2Frame2::ExecuteScript`.
+ ///
+ /// Unlike the upstream `contentWindow.eval` wrapper this works across origins,
+ /// because the engine routes the call to the frame instead of going through the
+ /// renderer's same-origin gate.
+ async fn evaluate_js_in_frame(
+ &self,
+ frame_ptr: SendableComPtr,
+ script: &str,
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+ let script_owned = script.to_string();
+ let script_preview: String = script.chars().take(100).collect();
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ let result = self.window.with_webview({
+ let tx = tx.clone();
+ move |_webview| unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+
+ let frame = ICoreWebView2Frame::from_raw(frame_ptr.as_ptr());
+ match frame.cast::<ICoreWebView2Frame2>() {
+ Ok(frame2) => {
+ let script_hstring = HSTRING::from(&script_owned);
+ let handler: ICoreWebView2ExecuteScriptCompletedHandler =
+ ExecuteScriptHandler::new(tx.clone()).into();
+
+ if let Err(e) =
+ frame2.ExecuteScript(PCWSTR(script_hstring.as_ptr()), &handler)
+ {
+ tracing::error!("Frame ExecuteScript failed for '{script_preview}...': {e:?}");
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("Frame ExecuteScript failed: {e:?}")));
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!("Frame does not expose ICoreWebView2Frame2: {e:?}");
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err("Frame does not expose ICoreWebView2Frame2".to_string()));
+ }
+ }
+ }
+ }
+ }
+ });
+
+ if let Err(e) = result {
+ tracing::error!("with_webview failed: {e}");
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(e.to_string()));
+ }
+ }
+ }
+
+ self.collect_script_result(rx).await
+ }
+
+ /// Await a script completion channel and shape it like `evaluate_js` expects.
+ async fn collect_script_result(
+ &self,
+ rx: tokio::sync::oneshot::Receiver<Result<Value, String>>,
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(serde_json::json!({
+ "success": true,
+ "value": value
+ })),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => {
+ tracing::error!("Channel closed unexpectedly during script execution");
+ Err(WebDriverErrorResponse::unknown_error("Channel closed"))
+ }
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ /// Map a `FrameId` to a slot in the native frame registry.
+ ///
+ /// The order matches what upstream's JS wrapper walks
+ /// (`document.querySelectorAll('iframe, frame')`), so an element reference is
+ /// resolved to its DOM position in the top-level document.
+ async fn resolve_frame_index(&self, id: &FrameId) -> Result<usize, WebDriverErrorResponse> {
+ match id {
+ FrameId::Index(index) => Ok(usize::try_from(*index).unwrap_or(usize::MAX)),
+ FrameId::Element(js_var) => {
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el) return -1;
+ var frames = document.querySelectorAll('iframe, frame');
+ for (var i = 0; i < frames.length; i++) {{
+ if (frames[i] === el) return i;
+ }}
+ return -1;
+ }})()"
+ );
+ let result = self.evaluate_js_top_level(&script).await?;
+ let index = result.get("value").and_then(Value::as_i64).unwrap_or(-1);
+
+ usize::try_from(index).map_err(|_| WebDriverErrorResponse::no_such_frame())
+ }
+ }
+ }
+}
+
+/// Register `WebView2` handlers at webview creation time.
+/// This is called from the plugin's `on_webview_ready` hook to ensure
+/// the script dialog handler is registered before any navigation completes.
+pub fn register_webview_handlers<R: Runtime>(webview: &tauri::Webview<R>) {
+ // Get per-window alert state from the manager
+ let manager = webview.app_handle().state::<AlertStateManager>();
+ let alert_state = manager.get_or_create(webview.label());
+
+ // Native frame handles are captured per window, so the executor can reach into
+ // cross-origin frames without the JS `contentWindow.eval` simulation.
+ let registry = webview.app_handle().state::<FrameRegistry>().inner().clone();
+ let label = webview.label().to_string();
+
+ let _ = webview.with_webview(move |webview| unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+
+ if let Ok(webview2) = webview.controller().CoreWebView2() {
+ // Disable default script dialogs so ScriptDialogOpening event fires
+ if let Ok(settings) = webview2.Settings() {
+ if let Err(e) = settings.SetAreDefaultScriptDialogsEnabled(false) {
+ tracing::error!("Failed to disable default script dialogs: {e:?}");
+ return;
+ }
+ } else {
+ tracing::error!("Failed to get webview settings");
+ return;
+ }
+
+ let handler: ICoreWebView2ScriptDialogOpeningEventHandler =
+ ScriptDialogOpeningHandler::new(alert_state).into();
+
+ let mut token = std::mem::zeroed();
+ if let Err(e) = webview2.add_ScriptDialogOpening(&handler, &raw mut token) {
+ tracing::error!("Failed to register ScriptDialogOpening handler: {e:?}");
+ } else {
+ tracing::debug!("Registered script dialog handler for webview");
+ }
+
+ // Prevent handler from being dropped - leak it to keep the COM ref alive
+ std::mem::forget(handler);
+
+ register_frame_handler(&webview2, registry, &label);
+ }
+ });
+}
+
+#[async_trait]
+impl<R: Runtime + 'static> PlatformExecutor<R> for WindowsExecutor<R> {
+ // =========================================================================
+ // Window Access
+ // =========================================================================
+
+ fn window(&self) -> &WebviewWindow<R> {
+ &self.window
+ }
+
+ fn script_timeout_ms(&self) -> u64 {
+ self.timeouts.script_ms
+ }
+
+ // =========================================================================
+ // Core JavaScript Execution
+ // =========================================================================
+
+ async fn evaluate_js(&self, script: &str) -> Result<Value, WebDriverErrorResponse> {
+ let locks = self.window.state::<ScriptExecutionLocks>();
+ let lock = locks.get(self.window.label());
+ let _guard = lock.lock().await;
+
+ // No frame context selected: top-level, unchanged.
+ if self.frame_context.is_empty() {
+ return self.evaluate_js_top_level(script).await;
+ }
+
+ // Only depth-1 frames have a native handle; deeper contexts fall back to the
+ // upstream JS wrapper, which is correct (if wasteful) within one origin.
+ if self.frame_context.len() == 1 {
+ let index = self.resolve_frame_index(&self.frame_context[0]).await?;
+ let registry = self.window.state::<FrameRegistry>();
+ if let Some((frame_ptr, name)) = registry.get(self.window.label(), index) {
+ tracing::debug!("Running script in native frame #{index} (name='{name}')");
+ return self.evaluate_js_in_frame(frame_ptr, script).await;
+ }
+ }
+
+ // Fall back to the upstream JS simulation: either the frame is nested, or the
+ // registry has not seen it (non-Windows-origin shell, late frame creation).
+ let wrapped = wrap_script_for_frame_context(script, &self.frame_context);
+ self.evaluate_js_top_level(&wrapped).await
+ }
+
+ // =========================================================================
+ // Screenshots
+ // =========================================================================
+
+ async fn take_screenshot(&self) -> Result<String, WebDriverErrorResponse> {
+ // Use WebView2's native CapturePreview API
+ let (tx, rx) = oneshot::channel();
+
+ let result = self.window.with_webview(move |webview| {
+ unsafe {
+ if let Ok(webview2) = webview.controller().CoreWebView2() {
+ // Create an in-memory stream for the PNG image
+ let stream = match CreateStreamOnHGlobal(HGLOBAL::default(), true) {
+ Ok(s) => s,
+ Err(e) => {
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("Failed to create stream: {e}")));
+ }
+ }
+ return;
+ }
+ };
+
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+ let handler = CapturePreviewHandler::new(tx, stream.clone());
+ let handler: ICoreWebView2CapturePreviewCompletedHandler = handler.into();
+
+ // Capture the preview as PNG
+ if let Err(e) = webview2.CapturePreview(
+ COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG,
+ &stream,
+ &handler,
+ ) {
+ // Handler won't be called, manually signal error
+ // Note: handler already moved, so we can't access tx directly
+ tracing::error!("CapturePreview failed: {e}");
+ }
+ }
+ }
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(base64))) => {
+ if base64.is_empty() {
+ Err(WebDriverErrorResponse::unknown_error(
+ "Screenshot returned empty data",
+ ))
+ } else {
+ Ok(base64)
+ }
+ }
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::unknown_error(&error)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ }
+ }
+
+ async fn take_element_screenshot(
+ &self,
+ js_var: &str,
+ ) -> Result<String, WebDriverErrorResponse> {
+ // Scroll element into view first
+ let script = format!(
+ r"(function() {{
+ var el = window.{js_var};
+ if (!el || !el.isConnected) {{
+ throw new Error('stale element reference');
+ }}
+ el.scrollIntoView({{ block: 'center', inline: 'center' }});
+ return true;
+ }})()"
+ );
+ self.evaluate_js(&script).await?;
+
+ // Take full screenshot and return (element clipping can be added later)
+ self.take_screenshot().await
+ }
+
+ // =========================================================================
+ // Print
+ // =========================================================================
+
+ #[allow(clippy::too_many_lines)]
+ async fn print_page(&self, options: PrintOptions) -> Result<String, WebDriverErrorResponse> {
+ let (tx, rx) = oneshot::channel();
+ let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
+
+ // Create temp directory for PDF output (auto-cleanup on drop)
+ // Note: We use TempDir instead of NamedTempFile because NamedTempFile
+ // opens/locks the file on Windows, preventing WebView2 from writing to it
+ let temp_dir = tempfile::TempDir::new().map_err(|e| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to create temp dir: {e}"))
+ })?;
+ let pdf_path = temp_dir.path().join("print.pdf");
+ let pdf_path_clone = pdf_path.clone();
+
+ // Extract options before moving into closure
+ let orientation = options.orientation.clone();
+ let scale = options.scale;
+ let background = options.background;
+ let page_width = options.page_width;
+ let page_height = options.page_height;
+ let margin_top = options.margin_top;
+ let margin_bottom = options.margin_bottom;
+ let margin_left = options.margin_left;
+ let margin_right = options.margin_right;
+
+ let result = self.window.with_webview(move |webview| unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+
+ let webview2 = match webview.controller().CoreWebView2() {
+ Ok(wv) => wv,
+ Err(e) => {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("Failed to get CoreWebView2: {e:?}")));
+ }
+ }
+ return;
+ }
+ };
+
+ // Cast to ICoreWebView2_7 for PrintToPdf support
+ let webview7: ICoreWebView2_7 = match webview2.cast() {
+ Ok(wv) => wv,
+ Err(e) => {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ =
+ tx.send(Err(format!("Failed to cast to ICoreWebView2_7: {e:?}")));
+ }
+ }
+ return;
+ }
+ };
+
+ // Get environment to create print settings
+ let environment = match webview7.Environment() {
+ Ok(env) => env,
+ Err(e) => {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("Failed to get environment: {e:?}")));
+ }
+ }
+ return;
+ }
+ };
+
+ // Cast to ICoreWebView2Environment6 for CreatePrintSettings
+ let env6: ICoreWebView2Environment6 = match environment.cast() {
+ Ok(env) => env,
+ Err(e) => {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!(
+ "Failed to cast to ICoreWebView2Environment6: {e:?}"
+ )));
+ }
+ }
+ return;
+ }
+ };
+
+ // Create print settings
+ let settings = match env6.CreatePrintSettings() {
+ Ok(s) => s,
+ Err(e) => {
+ if let Ok(mut guard) = tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err(format!("Failed to create print settings: {e:?}")));
+ }
+ }
+ return;
+ }
+ };
+
+ // Apply print options
+ // Orientation
+ if let Some(ref orient) = orientation {
+ let orientation_val = if orient == "landscape" {
+ COREWEBVIEW2_PRINT_ORIENTATION_LANDSCAPE
+ } else {
+ COREWEBVIEW2_PRINT_ORIENTATION_PORTRAIT
+ };
+ let _ = settings.SetOrientation(orientation_val);
+ }
+
+ // Scale factor (1.0 = 100%)
+ if let Some(s) = scale {
+ let _ = settings.SetScaleFactor(s);
+ }
+
+ // Print backgrounds
+ if let Some(bg) = background {
+ let _ = settings.SetShouldPrintBackgrounds(bg);
+ }
+
+ // Page dimensions (WebDriver uses cm, WebView2 uses inches)
+ // 1 inch = 2.54 cm
+ if let Some(w) = page_width {
+ let _ = settings.SetPageWidth(w / 2.54);
+ }
+ if let Some(h) = page_height {
+ let _ = settings.SetPageHeight(h / 2.54);
+ }
+
+ // Margins (WebDriver uses cm, WebView2 uses inches)
+ if let Some(m) = margin_top {
+ let _ = settings.SetMarginTop(m / 2.54);
+ }
+ if let Some(m) = margin_bottom {
+ let _ = settings.SetMarginBottom(m / 2.54);
+ }
+ if let Some(m) = margin_left {
+ let _ = settings.SetMarginLeft(m / 2.54);
+ }
+ if let Some(m) = margin_right {
+ let _ = settings.SetMarginRight(m / 2.54);
+ }
+
+ // Create completion handler
+ let handler: ICoreWebView2PrintToPdfCompletedHandler =
+ handlers::PrintToPdfHandler::new(tx).into();
+
+ // Convert path to HSTRING
+ let path_str = pdf_path_clone.to_string_lossy().to_string();
+ let path_hstring = HSTRING::from(&path_str);
+
+ // Call PrintToPdf
+ if let Err(e) = webview7.PrintToPdf(&path_hstring, &settings, &handler) {
+ tracing::error!("PrintToPdf call failed: {e:?}");
+ }
+ });
+
+ if let Err(e) = result {
+ return Err(WebDriverErrorResponse::unknown_error(&e.to_string()));
+ }
+
+ // Wait for completion
+ let timeout = std::time::Duration::from_millis(self.timeouts.script_ms);
+ let print_result = match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(()))) => Ok(()),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::unknown_error(&error)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => Err(WebDriverErrorResponse::script_timeout()),
+ };
+
+ // Check if print succeeded
+ print_result?;
+
+ // Read the PDF file (temp_file auto-cleans on drop)
+ let pdf_data = std::fs::read(&pdf_path).map_err(|e| {
+ WebDriverErrorResponse::unknown_error(&format!("Failed to read PDF file: {e}"))
+ })?;
+
+ Ok(BASE64_STANDARD.encode(&pdf_data))
+ }
+
+ // =========================================================================
+ // Async Script Execution
+ // =========================================================================
+
+ async fn execute_async_script(
+ &self,
+ script: &str,
+ args: &[Value],
+ ) -> Result<Value, WebDriverErrorResponse> {
+ let args_json = serde_json::to_string(args)
+ .map_err(|e| WebDriverErrorResponse::invalid_argument(&e.to_string()))?;
+
+ let async_id = uuid::Uuid::new_v4().to_string();
+
+ // Get async state and register this operation
+ let app = self.window.app_handle().clone();
+ let async_state = app.state::<AsyncScriptState>();
+ let label = self.window.label().to_string();
+
+ // Register handler if not already registered for this window
+ if !async_state.mark_handler_registered(&label) {
+ let app_clone = app.clone();
+ let handler_result = self.window.with_webview(move |webview| unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+
+ if let Ok(webview2) = webview.controller().CoreWebView2() {
+ let state = app_clone.state::<AsyncScriptState>();
+ register_message_handler(&webview2, state.inner());
+ }
+ });
+
+ if let Err(e) = handler_result {
+ return Err(WebDriverErrorResponse::unknown_error(&format!(
+ "Failed to register message handler: {e}"
+ )));
+ }
+ }
+
+ let rx = async_state.register(async_id.clone());
+
+ // Build wrapper script using postMessage
+ let wrapper = format!(
+ r"(function() {{
+ var ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
+ function deserializeArg(arg) {{
+ if (arg === null || arg === undefined) return arg;
+ if (Array.isArray(arg)) return arg.map(deserializeArg);
+ if (typeof arg === 'object') {{
+ if (arg[ELEMENT_KEY]) {{
+ var el = window['__wd_el_' + arg[ELEMENT_KEY].replace(/-/g, '')];
+ if (!el) throw new Error('stale element reference');
+ return el;
+ }}
+ var result = {{}};
+ for (var key in arg) {{
+ if (arg.hasOwnProperty(key)) result[key] = deserializeArg(arg[key]);
+ }}
+ return result;
+ }}
+ return arg;
+ }}
+ var __done = function(r) {{
+ window.chrome.webview.postMessage(JSON.stringify({{
+ handler: '{HANDLER_NAME}',
+ id: '{async_id}',
+ result: r,
+ error: null
+ }}));
+ }};
+ var __args = {args_json}.map(deserializeArg);
+ __args.push(__done);
+ try {{
+ (function() {{ {script} }}).apply(null, __args);
+ }} catch (e) {{
+ window.chrome.webview.postMessage(JSON.stringify({{
+ handler: '{HANDLER_NAME}',
+ id: '{async_id}',
+ result: null,
+ error: e.message || String(e)
+ }}));
+ }}
+ }})()"
+ );
+
+ // Acquire the per-webview lock and hold it across the entire async script lifecycle.
+ // This prevents another ExecuteScript from preempting the in-flight async JS callback.
+ let locks = self.window.state::<ScriptExecutionLocks>();
+ let lock = locks.get(self.window.label());
+ let _guard = lock.lock().await;
+
+ // Execute the wrapper using the unlocked inner method (we already hold the lock).
+ self.evaluate_js_top_level(&wrapper).await?;
+
+ // Wait for result with timeout (lock is still held; released when _guard drops).
+ let timeout_ms = self.timeouts.script_ms;
+ let timeout = std::time::Duration::from_millis(timeout_ms);
+
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(value))) => Ok(value),
+ Ok(Ok(Err(error))) => Err(WebDriverErrorResponse::javascript_error(&error, None)),
+ Ok(Err(_)) => Err(WebDriverErrorResponse::unknown_error("Channel closed")),
+ Err(_) => {
+ async_state.cancel(&async_id);
+ Err(WebDriverErrorResponse::script_timeout())
+ }
+ }
+ }
+}
+
+// =============================================================================
+// Helper Methods
+// =============================================================================
+// COM Handlers
+// =============================================================================
+
+type ScriptResultSender = Arc<std::sync::Mutex<Option<oneshot::Sender<Result<Value, String>>>>>;
+type CaptureResultSender = Arc<std::sync::Mutex<Option<oneshot::Sender<Result<String, String>>>>>;
+type PrintResultSender = Arc<std::sync::Mutex<Option<oneshot::Sender<Result<(), String>>>>>;
+
+mod handlers {
+ #![allow(clippy::inline_always, clippy::ref_as_ptr)]
+
+ use serde_json::Value;
+ use webview2_com::Microsoft::Web::WebView2::Win32::{
+ ICoreWebView2, ICoreWebView2CapturePreviewCompletedHandler,
+ ICoreWebView2CapturePreviewCompletedHandler_Impl, ICoreWebView2Deferral,
+ ICoreWebView2ExecuteScriptCompletedHandler,
+ ICoreWebView2ExecuteScriptCompletedHandler_Impl, ICoreWebView2PrintToPdfCompletedHandler,
+ ICoreWebView2PrintToPdfCompletedHandler_Impl, ICoreWebView2ScriptDialogOpeningEventArgs,
+ ICoreWebView2ScriptDialogOpeningEventHandler,
+ ICoreWebView2ScriptDialogOpeningEventHandler_Impl,
+ ICoreWebView2WebMessageReceivedEventArgs, ICoreWebView2WebMessageReceivedEventHandler,
+ ICoreWebView2WebMessageReceivedEventHandler_Impl, COREWEBVIEW2_SCRIPT_DIALOG_KIND_ALERT,
+ COREWEBVIEW2_SCRIPT_DIALOG_KIND_CONFIRM, COREWEBVIEW2_SCRIPT_DIALOG_KIND_PROMPT,
+ };
+ use windows::core::{implement, Interface};
+
+ use super::{
+ AlertState, AlertType, AsyncScriptState, CaptureResultSender, PendingAlert,
+ PrintResultSender, ScriptResultSender, SendableComPtr, HANDLER_NAME,
+ };
+ use crate::platform::alert_state::AlertResponse;
+ use std::sync::Arc;
+
+ #[implement(ICoreWebView2ExecuteScriptCompletedHandler)]
+ pub struct ExecuteScriptHandler {
+ pub tx: ScriptResultSender,
+ }
+
+ impl ExecuteScriptHandler {
+ pub fn new(tx: ScriptResultSender) -> Self {
+ Self { tx }
+ }
+ }
+
+ impl ICoreWebView2ExecuteScriptCompletedHandler_Impl for ExecuteScriptHandler_Impl {
+ fn Invoke(
+ &self,
+ errorcode: windows::core::HRESULT,
+ resultobjectasjson: &windows::core::PCWSTR,
+ ) -> windows::core::Result<()> {
+ let response = if errorcode.is_err() {
+ Err(format!("Script execution failed: {errorcode:?}"))
+ } else {
+ let json_str = unsafe { resultobjectasjson.to_string().unwrap_or_default() };
+ match serde_json::from_str(&json_str) {
+ Ok(value) => Ok(value),
+ Err(_) => Ok(Value::String(json_str)),
+ }
+ };
+
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ Ok(())
+ }
+ }
+
+ #[implement(ICoreWebView2CapturePreviewCompletedHandler)]
+ pub struct CapturePreviewHandler {
+ pub tx: CaptureResultSender,
+ pub stream: windows::Win32::System::Com::IStream,
+ }
+
+ impl CapturePreviewHandler {
+ pub fn new(tx: CaptureResultSender, stream: windows::Win32::System::Com::IStream) -> Self {
+ Self { tx, stream }
+ }
+ }
+
+ impl ICoreWebView2CapturePreviewCompletedHandler_Impl for CapturePreviewHandler_Impl {
+ fn Invoke(&self, errorcode: windows::core::HRESULT) -> windows::core::Result<()> {
+ let response = if errorcode.is_err() {
+ Err(format!("Capture preview failed: {errorcode:?}"))
+ } else {
+ // Read PNG data from the stream
+ unsafe {
+ use super::{STATFLAG_NONAME, STREAM_SEEK_SET};
+ use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
+ use base64::Engine as _;
+
+ // Get stream size
+ let mut stat = std::mem::zeroed();
+ if self.stream.Stat(&raw mut stat, STATFLAG_NONAME).is_err() {
+ return Ok(());
+ }
+ let size = usize::try_from(stat.cbSize).unwrap_or(0);
+
+ if size == 0 {
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err("Empty stream".to_string()));
+ }
+ }
+ return Ok(());
+ }
+
+ // Seek to beginning
+ let _ = self.stream.Seek(0, STREAM_SEEK_SET, None);
+
+ // Read data
+ let mut buffer = vec![0u8; size];
+ let mut bytes_read = 0u32;
+ if self
+ .stream
+ .Read(
+ buffer.as_mut_ptr().cast(),
+ u32::try_from(size).unwrap_or(u32::MAX),
+ Some(&raw mut bytes_read),
+ )
+ .is_err()
+ {
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Err("Failed to read stream".to_string()));
+ }
+ }
+ return Ok(());
+ }
+
+ buffer.truncate(bytes_read as usize);
+
+ // Encode as base64
+ let base64 = BASE64_STANDARD.encode(&buffer);
+
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(Ok(base64));
+ }
+ }
+ return Ok(());
+ }
+ };
+
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ Ok(())
+ }
+ }
+
+ /// Handler for PDF printing completion
+ #[implement(ICoreWebView2PrintToPdfCompletedHandler)]
+ pub struct PrintToPdfHandler {
+ pub tx: PrintResultSender,
+ }
+
+ impl PrintToPdfHandler {
+ pub fn new(tx: PrintResultSender) -> Self {
+ Self { tx }
+ }
+ }
+
+ impl ICoreWebView2PrintToPdfCompletedHandler_Impl for PrintToPdfHandler_Impl {
+ fn Invoke(
+ &self,
+ errorcode: windows::core::HRESULT,
+ issuccessful: super::BOOL,
+ ) -> windows::core::Result<()> {
+ let response = if errorcode.is_err() {
+ Err(format!("PrintToPdf failed: {errorcode:?}"))
+ } else if !issuccessful.as_bool() {
+ Err("PrintToPdf was not successful".to_string())
+ } else {
+ Ok(())
+ };
+
+ if let Ok(mut guard) = self.tx.lock() {
+ if let Some(tx) = guard.take() {
+ let _ = tx.send(response);
+ }
+ }
+ Ok(())
+ }
+ }
+
+ /// Handler for receiving web messages from JavaScript via postMessage
+ #[implement(ICoreWebView2WebMessageReceivedEventHandler)]
+ pub struct WebMessageReceivedHandler {
+ state_ptr: *const AsyncScriptState,
+ }
+
+ // SAFETY: The state pointer is valid for the lifetime of the app (managed by Tauri)
+ unsafe impl Send for WebMessageReceivedHandler {}
+ unsafe impl Sync for WebMessageReceivedHandler {}
+
+ impl WebMessageReceivedHandler {
+ pub fn new(state: &AsyncScriptState) -> Self {
+ Self {
+ state_ptr: state as *const AsyncScriptState,
+ }
+ }
+ }
+
+ impl ICoreWebView2WebMessageReceivedEventHandler_Impl for WebMessageReceivedHandler_Impl {
+ fn Invoke(
+ &self,
+ _sender: windows::core::Ref<'_, ICoreWebView2>,
+ args: windows::core::Ref<'_, ICoreWebView2WebMessageReceivedEventArgs>,
+ ) -> windows::core::Result<()> {
+ unsafe {
+ let state_ptr = self.state_ptr;
+ if state_ptr.is_null() {
+ tracing::error!("AsyncScriptState pointer is null");
+ return Ok(());
+ }
+ let state = &*state_ptr;
+
+ // Get the message as JSON string
+ let Some(args_owned) = args.clone() else {
+ return Ok(());
+ };
+ let mut msg_ptr = windows::core::PWSTR::null();
+ if args_owned.WebMessageAsJson(&raw mut msg_ptr).is_err() {
+ return Ok(()); // Failed to get message
+ }
+ let msg_text = msg_ptr.to_string().unwrap_or_default();
+
+ // `WebMessageAsJson` returns the message as a JSON value.
+ // Since JS sends `JSON.stringify({...})`, the message is a string,
+ // so we get a JSON-encoded string (with extra quotes).
+ // First parse to get the inner string, then parse that as our object.
+ let inner_str: String = match serde_json::from_str(&msg_text) {
+ Ok(s) => s,
+ Err(_) => return Ok(()), // Not a JSON string
+ };
+ let msg: Value = match serde_json::from_str(&inner_str) {
+ Ok(v) => v,
+ Err(_) => return Ok(()), // Not our message format
+ };
+
+ // Check if this is our handler
+ let handler = msg.get("handler").and_then(Value::as_str);
+ if handler != Some(HANDLER_NAME) {
+ return Ok(()); // Not for us
+ }
+
+ // Extract async ID
+ let Some(async_id) = msg.get("id").and_then(Value::as_str) else {
+ tracing::warn!("Message missing 'id' field");
+ return Ok(());
+ };
+ let async_id = async_id.to_string();
+
+ // Check for error
+ if let Some(error) = msg.get("error").and_then(Value::as_str) {
+ if !error.is_empty() {
+ state.complete(&async_id, Err(error.to_string()));
+ return Ok(());
+ }
+ }
+
+ // Extract result
+ let result = msg.get("result").cloned().unwrap_or(Value::Null);
+ state.complete(&async_id, Ok(result));
+ }
+ Ok(())
+ }
+ }
+
+ /// Handler for intercepting JavaScript alert/confirm/prompt dialogs
+ #[implement(ICoreWebView2ScriptDialogOpeningEventHandler)]
+ pub struct ScriptDialogOpeningHandler {
+ alert_state: Arc<AlertState>,
+ }
+
+ // SAFETY: Arc<AlertState> is Send + Sync
+ unsafe impl Send for ScriptDialogOpeningHandler {}
+ unsafe impl Sync for ScriptDialogOpeningHandler {}
+
+ impl ScriptDialogOpeningHandler {
+ pub fn new(alert_state: Arc<AlertState>) -> Self {
+ Self { alert_state }
+ }
+ }
+
+ impl ICoreWebView2ScriptDialogOpeningEventHandler_Impl for ScriptDialogOpeningHandler_Impl {
+ fn Invoke(
+ &self,
+ _sender: windows::core::Ref<'_, ICoreWebView2>,
+ args: windows::core::Ref<'_, ICoreWebView2ScriptDialogOpeningEventArgs>,
+ ) -> windows::core::Result<()> {
+ // Extract data and prepare for async handling inside unsafe block
+ let (args_ptr, deferral_ptr, rx) = unsafe {
+ let Some(args) = args.clone() else {
+ return Ok(());
+ };
+
+ // Get dialog kind
+ let mut kind = std::mem::zeroed();
+ if args.Kind(&raw mut kind).is_err() {
+ tracing::error!("Failed to get script dialog kind");
+ return Ok(());
+ }
+
+ // Get message
+ let mut message_ptr = windows::core::PWSTR::null();
+ if args.Message(&raw mut message_ptr).is_err() {
+ tracing::error!("Failed to get script dialog message");
+ return Ok(());
+ }
+ let message = message_ptr.to_string().unwrap_or_default();
+
+ // Get default text for prompts
+ let mut default_text_ptr = windows::core::PWSTR::null();
+ let default_text = if args.DefaultText(&raw mut default_text_ptr).is_ok() {
+ let text = default_text_ptr.to_string().unwrap_or_default();
+ if text.is_empty() {
+ None
+ } else {
+ Some(text)
+ }
+ } else {
+ None
+ };
+
+ // Map WebView2 dialog kind to our AlertType
+ let alert_type = if kind == COREWEBVIEW2_SCRIPT_DIALOG_KIND_ALERT {
+ AlertType::Alert
+ } else if kind == COREWEBVIEW2_SCRIPT_DIALOG_KIND_CONFIRM {
+ AlertType::Confirm
+ } else if kind == COREWEBVIEW2_SCRIPT_DIALOG_KIND_PROMPT {
+ AlertType::Prompt
+ } else {
+ // BEFOREUNLOAD or unknown - just accept it
+ let _ = args.Accept();
+ return Ok(());
+ };
+
+ tracing::debug!("Intercepted {:?} dialog: {}", alert_type, message);
+
+ // Get deferral to handle asynchronously (avoid blocking UI thread)
+ let deferral = match args.GetDeferral() {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!("Failed to get deferral: {e:?}");
+ let _ = args.Accept();
+ return Ok(());
+ }
+ };
+
+ // Create channel for WebDriver response
+ let (tx, rx) = std::sync::mpsc::channel::<AlertResponse>();
+ self.alert_state.set_pending(PendingAlert {
+ message: message.clone(),
+ default_text: default_text.clone(),
+ alert_type,
+ responder: tx,
+ });
+
+ // Wrap COM objects for thread transfer
+ let args_ptr = SendableComPtr(args.into_raw());
+ let deferral_ptr = SendableComPtr(deferral.into_raw());
+
+ (args_ptr, deferral_ptr, rx)
+ };
+
+ // Spawn thread to wait for WebDriver response (don't block UI thread)
+ std::thread::spawn(move || {
+ let timeout = std::time::Duration::from_secs(30);
+ let response = rx.recv_timeout(timeout);
+
+ // SAFETY: These pointers came from valid COM objects and we're
+ // accessing them from a single thread. All COM method calls are unsafe.
+ unsafe {
+ let args =
+ ICoreWebView2ScriptDialogOpeningEventArgs::from_raw(args_ptr.as_ptr());
+ let deferral = ICoreWebView2Deferral::from_raw(deferral_ptr.as_ptr());
+
+ match response {
+ Ok(AlertResponse {
+ accepted,
+ prompt_text,
+ }) => {
+ if accepted {
+ // Set prompt text if provided
+ if let Some(text) = prompt_text {
+ let result = windows::core::HSTRING::from(text.as_str());
+ let _ =
+ args.SetResultText(windows::core::PCWSTR(result.as_ptr()));
+ }
+ let _ = args.Accept();
+ }
+ // If not accepted, don't call Accept() - dialog returns false/null
+ }
+ Err(_) => {
+ // Timeout - auto-accept
+ let _ = args.Accept();
+ }
+ }
+
+ // Complete the deferral to let WebView2 continue
+ let _ = deferral.Complete();
+ }
+ });
+
+ Ok(())
+ }
+ }
+}
+
+use handlers::{
+ CapturePreviewHandler, ExecuteScriptHandler, ScriptDialogOpeningHandler,
+ WebMessageReceivedHandler,
+};
+
+// =============================================================================
+// Native Message Handler Registration
+// =============================================================================
+
+/// Register the `WebMessage` handler for a webview.
+///
+/// # Safety
+/// Must be called from a COM-initialized thread with a valid webview.
+unsafe fn register_message_handler(webview: &ICoreWebView2, state: &AsyncScriptState) {
+ let handler: ICoreWebView2WebMessageReceivedEventHandler =
+ WebMessageReceivedHandler::new(state).into();
+
+ // We don't need to store the token since we never remove the handler
+ let mut token = std::mem::zeroed();
+ if let Err(e) = webview.add_WebMessageReceived(&handler, &raw mut token) {
+ tracing::error!("Failed to register WebMessageReceived handler: {e:?}");
+ } else {
+ tracing::debug!("Registered native message handler for webview");
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/actions.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/actions.rs
new file mode 100644
index 00000000..efa598d7
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/actions.rs
@@ -0,0 +1,511 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use tauri::Runtime;
+
+use crate::platform::{ModifierState, PointerEventType};
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct ActionsRequest {
+ pub actions: Vec<ActionSequence>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type")]
+pub enum ActionSequence {
+ #[serde(rename = "key")]
+ Key {
+ #[serde(rename = "id")]
+ _id: String,
+ actions: Vec<KeyAction>,
+ },
+ #[serde(rename = "pointer")]
+ Pointer {
+ id: String,
+ actions: Vec<PointerAction>,
+ },
+ #[serde(rename = "wheel")]
+ Wheel {
+ #[serde(rename = "id")]
+ _id: String,
+ actions: Vec<WheelAction>,
+ },
+ #[serde(rename = "none")]
+ None {
+ #[serde(rename = "id")]
+ _id: String,
+ actions: Vec<PauseAction>,
+ },
+}
+
+impl ActionSequence {
+ /// Number of actions in this source. The request's tick count is the max across all sources.
+ fn action_count(&self) -> usize {
+ match self {
+ ActionSequence::Key { actions, .. } => actions.len(),
+ ActionSequence::Pointer { actions, .. } => actions.len(),
+ ActionSequence::Wheel { actions, .. } => actions.len(),
+ ActionSequence::None { actions, .. } => actions.len(),
+ }
+ }
+
+ /// The duration (ms) this source's action at `tick` contributes to the tick. Pause, pointer-move
+ /// and wheel-scroll actions carry a duration; everything else is instantaneous (`None`). The tick's
+ /// duration is the max of these across sources (W3C §17.4.3), not their sum.
+ fn duration_at(&self, tick: usize) -> Option<u64> {
+ match self {
+ ActionSequence::Key { actions, .. } => match actions.get(tick) {
+ Some(KeyAction::Pause { duration }) => *duration,
+ _ => None,
+ },
+ ActionSequence::Pointer { actions, .. } => match actions.get(tick) {
+ Some(PointerAction::PointerMove { duration, .. })
+ | Some(PointerAction::Pause { duration }) => *duration,
+ _ => None,
+ },
+ ActionSequence::Wheel { actions, .. } => match actions.get(tick) {
+ Some(WheelAction::Scroll { duration, .. }) | Some(WheelAction::Pause { duration }) => {
+ *duration
+ }
+ _ => None,
+ },
+ ActionSequence::None { actions, .. } => match actions.get(tick) {
+ Some(PauseAction::Pause { duration }) => *duration,
+ _ => None,
+ },
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type")]
+pub enum KeyAction {
+ #[serde(rename = "keyDown")]
+ KeyDown { value: String },
+ #[serde(rename = "keyUp")]
+ KeyUp { value: String },
+ #[serde(rename = "pause")]
+ Pause { duration: Option<u64> },
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type")]
+pub enum PointerAction {
+ #[serde(rename = "pointerDown")]
+ PointerDown { button: u32 },
+ #[serde(rename = "pointerUp")]
+ PointerUp { button: u32 },
+ #[serde(rename = "pointerMove")]
+ PointerMove {
+ x: i32,
+ y: i32,
+ duration: Option<u64>,
+ #[serde(default)]
+ origin: Option<Origin>,
+ },
+ #[serde(rename = "pause")]
+ Pause { duration: Option<u64> },
+}
+
+/// W3C JSON key identifying a web element reference.
+const ELEMENT_KEY: &str = "element-6066-11e4-a52e-4f735466cecf";
+
+/// Coordinate origin for a `pointerMove`. Per the WebDriver Actions spec the
+/// `origin` is either the string `"viewport"` (the default — x/y are absolute
+/// viewport coordinates) or `"pointer"` (x/y are relative to the current pointer
+/// position), or an element reference object
+/// `{ "element-6066-11e4-a52e-4f735466cecf": "<id>" }` (x/y are offsets from the
+/// element's in-view center point). WebdriverIO sends the element form for
+/// `element.click(options)` with x/y defaulting to 0, so this must resolve to the
+/// element's center rather than viewport (0,0).
+#[derive(Debug, Deserialize)]
+#[serde(untagged)]
+pub enum Origin {
+ Named(String),
+ Element(HashMap<String, String>),
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type")]
+pub enum WheelAction {
+ #[serde(rename = "scroll")]
+ Scroll {
+ x: i32,
+ y: i32,
+ #[serde(rename = "deltaX")]
+ delta_x: i32,
+ #[serde(rename = "deltaY")]
+ delta_y: i32,
+ #[serde(default)]
+ duration: Option<u64>,
+ },
+ #[serde(rename = "pause")]
+ Pause { duration: Option<u64> },
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type")]
+pub enum PauseAction {
+ #[serde(rename = "pause")]
+ Pause { duration: Option<u64> },
+}
+
+/// Current pointer position for actions
+struct PointerState {
+ x: i32,
+ y: i32,
+}
+
+/// POST `/session/{session_id}/actions` - Perform actions
+#[allow(clippy::too_many_lines)]
+pub async fn perform<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<ActionsRequest>,
+) -> WebDriverResult {
+ // Get session info and executor first
+ let (current_window, timeouts, frame_context, pointer_position) = {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ (
+ session.current_window.clone(),
+ session.timeouts.clone(),
+ session.frame_context.clone(),
+ session.action_state.pointer_position,
+ )
+ };
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let mut pointer_state = PointerState {
+ x: pointer_position.0,
+ y: pointer_position.1,
+ };
+ // Position of the last primary-button press, used to synthesize a `click`
+ // when the matching release lands on the same spot (a click, not a drag).
+ let mut primary_down_pos: Option<(i32, i32)> = None;
+ let mut modifier_state = ModifierState::default();
+
+ // Process actions tick-by-tick across sources (W3C): the action at index N from every source runs
+ // before index N+1 from any source, so cross-source chains interleave correctly (e.g. Ctrl+click
+ // built as a key source + a pointer source in one performActions — the modifier is down when the
+ // click lands). A source with fewer actions contributes nothing on later ticks.
+ let tick_count = request
+ .actions
+ .iter()
+ .map(ActionSequence::action_count)
+ .max()
+ .unwrap_or(0);
+ for tick in 0..tick_count {
+ // W3C §17.4.3: a tick lasts the *maximum* pause/move/scroll duration across its sources (not
+ // the sum), slept once after the tick's actions are dispatched.
+ let tick_duration_ms = request
+ .actions
+ .iter()
+ .filter_map(|seq| seq.duration_at(tick))
+ .max()
+ .unwrap_or(0);
+ for action_seq in &request.actions {
+ match action_seq {
+ ActionSequence::Key { _id: _, actions } => {
+ if let Some(action) = actions.get(tick) {
+ match action {
+ KeyAction::KeyDown { value } => {
+ modifier_state.update(value, true);
+ executor
+ .dispatch_key_event(value, true, &modifier_state)
+ .await?;
+ // Track pressed key
+ let mut sessions = state.sessions.write().await;
+ if let Ok(session) = sessions.get_mut(&session_id) {
+ session.action_state.pressed_keys.insert(value.clone());
+ }
+ }
+ KeyAction::KeyUp { value } => {
+ executor
+ .dispatch_key_event(value, false, &modifier_state)
+ .await?;
+ modifier_state.update(value, false);
+ // Remove from tracked keys
+ let mut sessions = state.sessions.write().await;
+ if let Ok(session) = sessions.get_mut(&session_id) {
+ session.action_state.pressed_keys.remove(value);
+ }
+ }
+ KeyAction::Pause { .. } => {}
+ }
+ }
+ }
+ ActionSequence::Pointer { id, actions } => {
+ if let Some(action) = actions.get(tick) {
+ match action {
+ PointerAction::PointerDown { button } => {
+ executor
+ .dispatch_pointer_event(
+ PointerEventType::Down,
+ pointer_state.x,
+ pointer_state.y,
+ *button,
+ )
+ .await?;
+ if *button == 0 {
+ primary_down_pos = Some((pointer_state.x, pointer_state.y));
+ }
+ // Track pressed button
+ let mut sessions = state.sessions.write().await;
+ if let Ok(session) = sessions.get_mut(&session_id) {
+ session
+ .action_state
+ .pressed_buttons
+ .entry(id.clone())
+ .or_default()
+ .insert(*button);
+ }
+ }
+ PointerAction::PointerUp { button } => {
+ executor
+ .dispatch_pointer_event(
+ PointerEventType::Up,
+ pointer_state.x,
+ pointer_state.y,
+ *button,
+ )
+ .await?;
+ // A primary press + release on the same spot is a
+ // click; emit the click event the browser would
+ // synthesize for real input so element handlers fire.
+ // Only the primary button's release consumes/clears
+ // the press state — a non-primary release in between
+ // must not drop it.
+ if *button == 0 {
+ if primary_down_pos == Some((pointer_state.x, pointer_state.y)) {
+ executor
+ .dispatch_pointer_event(
+ PointerEventType::Click,
+ pointer_state.x,
+ pointer_state.y,
+ *button,
+ )
+ .await?;
+ }
+ primary_down_pos = None;
+ }
+ // Remove from tracked buttons
+ let mut sessions = state.sessions.write().await;
+ if let Ok(session) = sessions.get_mut(&session_id) {
+ if let Some(buttons) =
+ session.action_state.pressed_buttons.get_mut(id)
+ {
+ buttons.remove(button);
+ }
+ }
+ }
+ PointerAction::PointerMove { x, y, origin, .. } => {
+ let (target_x, target_y) = match origin {
+ // No origin (the default) or "viewport": x/y are absolute viewport coords.
+ None => (*x, *y),
+ Some(Origin::Named(name)) if name == "viewport" => (*x, *y),
+ Some(Origin::Named(name)) if name == "pointer" => {
+ (pointer_state.x + *x, pointer_state.y + *y)
+ }
+ // The spec defines only "viewport" and "pointer" as named origins;
+ // reject anything else rather than silently treating it as viewport.
+ Some(Origin::Named(name)) => {
+ return Err(WebDriverErrorResponse::invalid_argument(&format!(
+ "pointerMove origin '{name}' is not a recognised named origin (expected 'viewport' or 'pointer')"
+ )));
+ }
+ Some(Origin::Element(refs)) => {
+ let element_id = refs.get(ELEMENT_KEY).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(
+ "pointerMove origin is missing a web element reference",
+ )
+ })?;
+ let js_var = {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ session
+ .elements
+ .get(element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?
+ .js_ref
+ .clone()
+ };
+ let (cx, cy) = executor.get_element_center(&js_var).await?;
+ (cx + *x, cy + *y)
+ }
+ };
+ pointer_state.x = target_x;
+ pointer_state.y = target_y;
+ executor
+ .dispatch_pointer_event(
+ PointerEventType::Move,
+ pointer_state.x,
+ pointer_state.y,
+ 0,
+ )
+ .await?;
+ }
+ PointerAction::Pause { .. } => {}
+ }
+ }
+ }
+ ActionSequence::Wheel { _id: _, actions } => {
+ if let Some(action) = actions.get(tick) {
+ match action {
+ WheelAction::Scroll { x, y, delta_x, delta_y, .. } => {
+ executor
+ .dispatch_scroll_event(*x, *y, *delta_x, *delta_y)
+ .await?;
+ }
+ WheelAction::Pause { .. } => {}
+ }
+ }
+ }
+ ActionSequence::None { _id: _, actions } => {
+ if let Some(action) = actions.get(tick) {
+ match action {
+ PauseAction::Pause { .. } => {}
+ }
+ }
+ }
+ }
+ }
+ // The tick's actions are dispatched; wait its longest source duration once.
+ if tick_duration_ms > 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(tick_duration_ms)).await;
+ }
+ }
+
+ // Persist the final pointer position so a later performActions call with
+ // origin: "pointer" resolves relative to it instead of (0, 0).
+ {
+ let mut sessions = state.sessions.write().await;
+ if let Ok(session) = sessions.get_mut(&session_id) {
+ session.action_state.pointer_position = (pointer_state.x, pointer_state.y);
+ }
+ }
+
+ Ok(WebDriverResponse::null())
+}
+
+/// DELETE `/session/{session_id}/actions` - Release actions
+pub async fn release<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ // Get session state and clear tracked actions
+ let (current_window, timeouts, frame_context, pressed_keys, pressed_buttons) = {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let pressed_keys: Vec<String> = session.action_state.pressed_keys.drain().collect();
+ let pressed_buttons = std::mem::take(&mut session.action_state.pressed_buttons);
+ session.action_state.pointer_position = (0, 0);
+ (
+ session.current_window.clone(),
+ session.timeouts.clone(),
+ session.frame_context.clone(),
+ pressed_keys,
+ pressed_buttons,
+ )
+ };
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let modifier_state = ModifierState::default();
+
+ // Release all pressed keys (keyUp events)
+ for key in pressed_keys {
+ executor
+ .dispatch_key_event(&key, false, &modifier_state)
+ .await?;
+ }
+
+ // Release all pressed pointer buttons (pointerUp events)
+ for (_source_id, buttons) in pressed_buttons {
+ for button in buttons {
+ executor
+ .dispatch_pointer_event(PointerEventType::Up, 0, 0, button)
+ .await?;
+ }
+ }
+
+ Ok(WebDriverResponse::null())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse(json: &str) -> ActionsRequest {
+ serde_json::from_str(json).expect("valid actions request")
+ }
+
+ #[test]
+ fn action_count_returns_actions_len_per_source() {
+ let req = parse(
+ r#"{"actions":[
+ {"type":"key","id":"k","actions":[{"type":"keyDown","value":"a"},{"type":"keyUp","value":"a"}]},
+ {"type":"none","id":"n","actions":[{"type":"pause","duration":0}]}
+ ]}"#,
+ );
+ let counts: Vec<usize> = req.actions.iter().map(ActionSequence::action_count).collect();
+ assert_eq!(counts, vec![2, 1]);
+ }
+
+ #[test]
+ fn tick_count_is_the_max_actions_across_sources() {
+ // The number of ticks is max(actions) across sources, so a shorter source contributes
+ // nothing on later ticks while a longer one keeps going.
+ let req = parse(
+ r#"{"actions":[
+ {"type":"key","id":"k","actions":[{"type":"keyDown","value":"a"}]},
+ {"type":"pointer","id":"p","actions":[
+ {"type":"pointerMove","x":0,"y":0},{"type":"pointerDown","button":0},{"type":"pointerUp","button":0}
+ ]}
+ ]}"#,
+ );
+ let ticks = req
+ .actions
+ .iter()
+ .map(ActionSequence::action_count)
+ .max()
+ .unwrap_or(0);
+ assert_eq!(ticks, 3);
+ }
+
+ #[test]
+ fn tick_count_is_zero_for_no_sources() {
+ let req = parse(r#"{"actions":[]}"#);
+ let ticks = req
+ .actions
+ .iter()
+ .map(ActionSequence::action_count)
+ .max()
+ .unwrap_or(0);
+ assert_eq!(ticks, 0);
+ }
+
+ #[test]
+ fn tick_duration_is_max_across_sources_not_sum() {
+ // W3C §17.4.3: a tick lasts the max pause/move/scroll duration across sources, not their sum.
+ let req = parse(
+ r#"{"actions":[
+ {"type":"none","id":"n","actions":[{"type":"pause","duration":100},{"type":"pause","duration":50}]},
+ {"type":"pointer","id":"p","actions":[
+ {"type":"pointerMove","x":0,"y":0,"duration":200},{"type":"pause","duration":30}
+ ]},
+ {"type":"wheel","id":"w","actions":[{"type":"scroll","x":0,"y":0,"deltaX":0,"deltaY":0,"duration":80}]}
+ ]}"#,
+ );
+ let tick_ms =
+ |tick: usize| req.actions.iter().filter_map(|s| s.duration_at(tick)).max().unwrap_or(0);
+ // tick 0: max(100, 200, 80) = 200 — not the sum (380).
+ assert_eq!(tick_ms(0), 200);
+ // tick 1: max(50, 30) = 50 — the wheel source is exhausted and contributes nothing.
+ assert_eq!(tick_ms(1), 50);
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/alert.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/alert.rs
new file mode 100644
index 00000000..a736f010
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/alert.rs
@@ -0,0 +1,87 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct SendAlertTextRequest {
+ pub text: String,
+}
+
+/// POST `/session/{session_id}/alert/dismiss` - Dismiss alert
+pub async fn dismiss<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.dismiss_alert().await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/alert/accept` - Accept alert
+pub async fn accept<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.accept_alert().await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// GET `/session/{session_id}/alert/text` - Get alert text
+pub async fn get_text<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let text: String = executor.get_alert_text().await?;
+
+ Ok(WebDriverResponse::success(text))
+}
+
+/// POST `/session/{session_id}/alert/text` - Send text to alert (for prompts)
+pub async fn send_text<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<SendAlertTextRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.send_alert_text(&request.text).await?;
+
+ Ok(WebDriverResponse::null())
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/cookie.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/cookie.rs
new file mode 100644
index 00000000..ec106629
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/cookie.rs
@@ -0,0 +1,109 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use tauri::Runtime;
+
+use crate::platform::Cookie;
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct AddCookieRequest {
+ pub cookie: Cookie,
+}
+
+/// GET `/session/{session_id}/cookie` - Get all cookies
+pub async fn get_all<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let cookies = executor.get_all_cookies().await?;
+
+ Ok(WebDriverResponse::success(cookies))
+}
+
+/// GET `/session/{session_id}/cookie/{name}` - Get a specific cookie
+pub async fn get<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, name)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let cookie = executor.get_cookie(&name).await?;
+
+ match cookie {
+ Some(c) => Ok(WebDriverResponse::success(c)),
+ None => Err(WebDriverErrorResponse::no_such_cookie(&name)),
+ }
+}
+
+/// POST `/session/{session_id}/cookie` - Add a cookie
+pub async fn add<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<AddCookieRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.add_cookie(request.cookie).await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// DELETE `/session/{session_id}/cookie/{name}` - Delete a specific cookie
+pub async fn delete<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, name)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.delete_cookie(&name).await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// DELETE `/session/{session_id}/cookie` - Delete all cookies
+pub async fn delete_all<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.delete_all_cookies().await?;
+
+ Ok(WebDriverResponse::null())
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/direct_eval.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/direct_eval.rs
new file mode 100644
index 00000000..86964f20
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/direct_eval.rs
@@ -0,0 +1,112 @@
+use std::sync::Arc;
+
+use axum::extract::State;
+use axum::http::StatusCode;
+use axum::Json;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::Runtime;
+
+use crate::server::AppState;
+use crate::webdriver::Timeouts;
+
+#[derive(Deserialize)]
+pub struct DirectEvalRequest {
+ pub script: String,
+ pub window_label: Option<String>,
+ pub timeout_ms: Option<u64>,
+}
+
+#[derive(Serialize)]
+pub struct DirectEvalResponse {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub value: Option<Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub undef: Option<bool>,
+}
+
+/// POST `/wdio/eval` — execute a pre-wrapped async script directly in a webview window
+/// without going through the W3C WebDriver session layer or Tauri IPC.
+///
+/// The script must use the W3C async-script callback contract:
+/// `arguments[arguments.length - 1]` is the done callback.
+/// The TypeScript `wrapScriptForDirectEval` helper produces scripts in this format.
+pub async fn eval<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Json(req): Json<DirectEvalRequest>,
+) -> (StatusCode, Json<DirectEvalResponse>) {
+ let label = req.window_label.as_deref().unwrap_or("main");
+ let timeouts = Timeouts {
+ script_ms: req.timeout_ms.unwrap_or(30_000),
+ ..Default::default()
+ };
+
+ let executor = match state.get_executor_for_window(label, timeouts, Vec::new()) {
+ Ok(e) => e,
+ Err(e) => {
+ let available = state.get_window_labels().join(", ");
+ tracing::warn!("Direct eval: window '{label}' not found: {}", e.message);
+ return (
+ StatusCode::NOT_FOUND,
+ Json(DirectEvalResponse {
+ value: None,
+ error: Some(format!(
+ "Window '{label}' not found. Available: [{available}]"
+ )),
+ undef: None,
+ }),
+ );
+ }
+ };
+
+ match executor.execute_direct_eval(&req.script).await {
+ Ok(result) => {
+ match result.get("ok").and_then(|v| v.as_bool()) {
+ Some(true) => {
+ let undef = result.get("undef").and_then(|v| v.as_bool()).unwrap_or(false);
+ (
+ StatusCode::OK,
+ Json(DirectEvalResponse {
+ value: result.get("value").cloned(),
+ error: None,
+ undef: if undef { Some(true) } else { None },
+ }),
+ )
+ }
+ Some(false) => {
+ let error = result
+ .get("error")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Script execution failed")
+ .to_string();
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(DirectEvalResponse {
+ value: None,
+ error: Some(error),
+ undef: None,
+ }),
+ )
+ }
+ None => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(DirectEvalResponse {
+ value: None,
+ error: Some("Script result missing required 'ok' field".to_string()),
+ undef: None,
+ }),
+ ),
+ }
+ }
+ Err(err) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(DirectEvalResponse {
+ value: None,
+ error: Some(err.message),
+ undef: None,
+ }),
+ ),
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/document.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/document.rs
new file mode 100644
index 00000000..9a31d392
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/document.rs
@@ -0,0 +1,24 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+/// GET `/session/{session_id}/source` - Get page source
+pub async fn get_source<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let source = executor.get_source().await?;
+ Ok(WebDriverResponse::success(source))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/element.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/element.rs
new file mode 100644
index 00000000..096b91c6
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/element.rs
@@ -0,0 +1,618 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+use crate::webdriver::locator::LocatorStrategy;
+
+#[derive(Debug, Deserialize)]
+pub struct FindElementRequest {
+ pub using: String,
+ pub value: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SendKeysRequest {
+ pub text: String,
+}
+
+/// POST `/session/{session_id}/element` - Find element
+pub async fn find<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ // Store element reference and get ID
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let strategy_js = strategy.to_selector_js(&request.value);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let found = executor.find_element(&strategy_js, &js_var).await?;
+ if !found {
+ return Err(WebDriverErrorResponse::no_such_element());
+ }
+
+ Ok(WebDriverResponse::success(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ })))
+}
+
+/// POST `/session/{session_id}/elements` - Find multiple elements
+pub async fn find_all<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let strategy_js = strategy.to_selector_js_multiple(&request.value);
+
+ // Use a temporary prefix for the trait method
+ let temp_prefix = "__wd_temp_";
+ let count = executor.find_elements(&strategy_js, temp_prefix).await?;
+
+ // Now store each element with proper references
+ let mut elements = Vec::new();
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ for i in 0..count {
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+
+ // Copy from temp storage to element's js_ref
+ let copy_script = format!(
+ "(function() {{ window.{js_var} = window['{temp_prefix}{i}']; return true; }})()"
+ );
+ let _ = executor.evaluate_js(&copy_script).await;
+
+ elements.push(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ }));
+ }
+
+ Ok(WebDriverResponse::success(elements))
+}
+
+/// POST `/session/{session_id}/element/{element_id}/click` - Click element
+pub async fn click<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.click_element(&js_var).await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/element/{element_id}/clear` - Clear element
+pub async fn clear<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.clear_element(&js_var).await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/element/{element_id}/value` - Send keys to element
+pub async fn send_keys<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+ Json(request): Json<SendKeysRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor
+ .send_keys_to_element(&js_var, &request.text)
+ .await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// GET `/session/{session_id}/element/{element_id}/text` - Get element text
+pub async fn get_text<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let text = executor.get_element_text(&js_var).await?;
+ Ok(WebDriverResponse::success(text))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/name` - Get element tag name
+pub async fn get_tag_name<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let tag_name = executor.get_element_tag_name(&js_var).await?;
+ Ok(WebDriverResponse::success(tag_name))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/attribute/{name}` - Get element attribute
+pub async fn get_attribute<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id, name)): Path<(String, String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let attr = executor.get_element_attribute(&js_var, &name).await?;
+ Ok(WebDriverResponse::success(attr))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/property/{name}` - Get element property
+pub async fn get_property<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id, name)): Path<(String, String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let prop = executor.get_element_property(&js_var, &name).await?;
+ Ok(WebDriverResponse::success(prop))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/displayed` - Is element displayed
+pub async fn is_displayed<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let displayed = executor.is_element_displayed(&js_var).await?;
+ Ok(WebDriverResponse::success(displayed))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/enabled` - Is element enabled
+pub async fn is_enabled<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let enabled = executor.is_element_enabled(&js_var).await?;
+ Ok(WebDriverResponse::success(enabled))
+}
+
+/// GET `/session/{session_id}/element/active` - Get active element
+pub async fn get_active<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ // Store element reference for the active element
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let found = executor.get_active_element(&js_var).await?;
+ if !found {
+ return Err(WebDriverErrorResponse::no_such_element());
+ }
+
+ Ok(WebDriverResponse::success(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ })))
+}
+
+/// POST `/session/{session_id}/element/{element_id}/element` - Find element from element
+pub async fn find_from_element<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, parent_element_id)): Path<(String, String)>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ let parent_element = session
+ .elements
+ .get(&parent_element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+ let parent_js_var = parent_element.js_ref.clone();
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ // Store element reference and get ID
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ // Use the locator method that generates expressions expecting `parent` to be defined
+ let strategy_js = strategy.to_selector_js_single_from_element(&request.value);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let found = executor
+ .find_element_from_element(&parent_js_var, &strategy_js, &js_var)
+ .await?;
+ if !found {
+ return Err(WebDriverErrorResponse::no_such_element());
+ }
+
+ Ok(WebDriverResponse::success(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ })))
+}
+
+/// POST `/session/{session_id}/element/{element_id}/elements` - Find elements from element
+pub async fn find_all_from_element<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, parent_element_id)): Path<(String, String)>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let parent_element = session
+ .elements
+ .get(&parent_element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+ let parent_js_var = parent_element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let strategy_js = strategy.to_selector_js_from_element(&request.value);
+
+ // Use a temporary prefix for the trait method
+ let temp_prefix = "__wd_temp_";
+ let count = executor
+ .find_elements_from_element(&parent_js_var, &strategy_js, temp_prefix)
+ .await?;
+
+ // Now store each element with proper references
+ let mut elements = Vec::new();
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ for i in 0..count {
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+
+ // Copy from temp storage to element's js_ref
+ let copy_script = format!(
+ "(function() {{ window.{js_var} = window['{temp_prefix}{i}']; return true; }})()"
+ );
+ let _ = executor.evaluate_js(&copy_script).await;
+
+ elements.push(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ }));
+ }
+
+ Ok(WebDriverResponse::success(elements))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/selected` - Is element selected
+pub async fn is_selected<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let selected = executor.is_element_selected(&js_var).await?;
+ Ok(WebDriverResponse::success(selected))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/css/{property_name}` - Get CSS value
+pub async fn get_css_value<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id, property_name)): Path<(String, String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let value = executor
+ .get_element_css_value(&js_var, &property_name)
+ .await?;
+ Ok(WebDriverResponse::success(value))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/rect` - Get element rect
+pub async fn get_rect<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let rect = executor.get_element_rect(&js_var).await?;
+ Ok(WebDriverResponse::success(json!({
+ "x": rect.x,
+ "y": rect.y,
+ "width": rect.width,
+ "height": rect.height
+ })))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/computedrole` - Get computed ARIA role
+pub async fn get_computed_role<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let role = executor.get_element_computed_role(&js_var).await?;
+ Ok(WebDriverResponse::success(role))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/computedlabel` - Get computed accessible name
+pub async fn get_computed_label<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let label = executor.get_element_computed_label(&js_var).await?;
+ Ok(WebDriverResponse::success(label))
+}
+
+/// GET `/session/{session_id}/element/{element_id}/screenshot` - Take element screenshot
+pub async fn take_screenshot<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let screenshot = executor.take_element_screenshot(&js_var).await?;
+ Ok(WebDriverResponse::success(screenshot))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/frame.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/frame.rs
new file mode 100644
index 00000000..ecbaa86f
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/frame.rs
@@ -0,0 +1,338 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::Value;
+use tauri::Runtime;
+
+use crate::platform::FrameId;
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+fn browsing_context_changed_error<R: Runtime>(
+ state: &AppState<R>,
+ current_window: &str,
+ frame_id: Option<&FrameId>,
+) -> WebDriverErrorResponse {
+ if !state.has_window_label(current_window) {
+ return WebDriverErrorResponse::no_such_window();
+ }
+
+ if matches!(frame_id, Some(FrameId::Element(_))) {
+ return WebDriverErrorResponse::stale_element_reference();
+ }
+
+ WebDriverErrorResponse::unknown_error("Browsing context changed while switching frame")
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum FrameContextCommitError {
+ WindowMissing,
+ BrowsingContextChanged,
+}
+
+enum FrameContextMutation {
+ Clear,
+ Push(FrameId),
+ Pop,
+}
+
+fn commit_frame_context(
+ session: &mut crate::webdriver::session::Session,
+ browsing_context_generation: u64,
+ original_window_exists: bool,
+ mutation: FrameContextMutation,
+) -> Result<(), FrameContextCommitError> {
+ if !original_window_exists {
+ return Err(FrameContextCommitError::WindowMissing);
+ }
+
+ if session.browsing_context_generation != browsing_context_generation {
+ return Err(FrameContextCommitError::BrowsingContextChanged);
+ }
+
+ match mutation {
+ FrameContextMutation::Clear => session.frame_context.clear(),
+ FrameContextMutation::Push(frame_id) => session.frame_context.push(frame_id),
+ FrameContextMutation::Pop => {
+ session.frame_context.pop();
+ }
+ }
+
+ Ok(())
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SwitchFrameRequest {
+ pub id: Value,
+}
+
+/// POST `/session/{session_id}/frame` - Switch to frame
+pub async fn switch_to_frame<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<SwitchFrameRequest>,
+) -> WebDriverResult {
+ // First, read session data without modifying
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ // Get current context for validation (before any changes)
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let current_frame_context = session.frame_context.clone();
+ let browsing_context_generation = session.browsing_context_generation;
+
+ // Parse the frame ID to determine what we're switching to
+ let (frame_id, js_var_for_element) = match &request.id {
+ Value::Null => {
+ drop(sessions);
+
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let original_window_exists = state.has_window_label(&current_window);
+ match commit_frame_context(
+ session,
+ browsing_context_generation,
+ original_window_exists,
+ FrameContextMutation::Clear,
+ ) {
+ Ok(()) => {}
+ Err(FrameContextCommitError::WindowMissing) => {
+ return Err(WebDriverErrorResponse::no_such_window());
+ }
+ Err(FrameContextCommitError::BrowsingContextChanged) => {
+ return Err(browsing_context_changed_error(
+ &state,
+ &current_window,
+ None,
+ ));
+ }
+ }
+
+ return Ok(WebDriverResponse::null());
+ }
+ Value::Number(n) => {
+ let index = n.as_u64().ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(
+ "Frame index must be a non-negative integer",
+ )
+ })?;
+ let index = u32::try_from(index)
+ .map_err(|_| WebDriverErrorResponse::invalid_argument("Frame index too large"))?;
+
+ (FrameId::Index(index), None)
+ }
+ Value::Object(obj) => {
+ // W3C element reference format
+ if let Some(element_id) = obj.get("element-6066-11e4-a52e-4f735466cecf") {
+ let element_id = element_id.as_str().ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument("Element reference must be a string")
+ })?;
+
+ // Look up the element's js_var
+ let element = session
+ .elements
+ .get(element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+
+ let js_var = element.js_ref.clone();
+ (FrameId::Element(js_var.clone()), Some(js_var))
+ } else {
+ return Err(WebDriverErrorResponse::invalid_argument(
+ "Invalid frame identifier object",
+ ));
+ }
+ }
+ _ => {
+ return Err(WebDriverErrorResponse::invalid_argument(
+ "Frame ID must be null, a number, or an element reference",
+ ));
+ }
+ };
+ drop(sessions);
+
+ // Create executor with CURRENT frame context (not the new one) to validate
+ let executor =
+ state.get_executor_for_window(&current_window, timeouts, current_frame_context)?;
+
+ // Validate the frame exists from current context
+ executor.switch_to_frame(frame_id.clone()).await?;
+
+ // Validation passed - now update the session's frame context
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ let frame_id = match frame_id {
+ FrameId::Index(index) => FrameId::Index(index),
+ FrameId::Element(_) => FrameId::Element(
+ js_var_for_element.expect("element frame IDs always have an element reference"),
+ ),
+ };
+ let original_window_exists = state.has_window_label(&current_window);
+ match commit_frame_context(
+ session,
+ browsing_context_generation,
+ original_window_exists,
+ FrameContextMutation::Push(frame_id.clone()),
+ ) {
+ Ok(()) => {}
+ Err(FrameContextCommitError::WindowMissing) => {
+ return Err(WebDriverErrorResponse::no_such_window());
+ }
+ Err(FrameContextCommitError::BrowsingContextChanged) => {
+ return Err(browsing_context_changed_error(
+ &state,
+ &current_window,
+ Some(&frame_id),
+ ));
+ }
+ }
+
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/frame/parent` - Switch to parent frame
+pub async fn switch_to_parent_frame<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ let browsing_context_generation = session.browsing_context_generation;
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.switch_to_parent_frame().await?;
+
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let original_window_exists = state.has_window_label(&current_window);
+ match commit_frame_context(
+ session,
+ browsing_context_generation,
+ original_window_exists,
+ FrameContextMutation::Pop,
+ ) {
+ Ok(()) => {}
+ Err(FrameContextCommitError::WindowMissing) => {
+ return Err(WebDriverErrorResponse::no_such_window());
+ }
+ Err(FrameContextCommitError::BrowsingContextChanged) => {
+ return Err(browsing_context_changed_error(
+ &state,
+ &current_window,
+ None,
+ ));
+ }
+ }
+
+ Ok(WebDriverResponse::null())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{commit_frame_context, FrameContextCommitError, FrameContextMutation};
+ use crate::platform::FrameId;
+ use crate::webdriver::session::Session;
+
+ #[test]
+ fn refuses_to_commit_a_frame_after_the_original_window_is_removed() {
+ let mut session = Session::new("child-left".to_string());
+ let generation = session.browsing_context_generation;
+
+ let result = commit_frame_context(
+ &mut session,
+ generation,
+ false,
+ FrameContextMutation::Push(FrameId::Index(0)),
+ );
+
+ assert_eq!(result, Err(FrameContextCommitError::WindowMissing));
+ assert!(session.frame_context.is_empty());
+ }
+
+ #[test]
+ fn prioritizes_a_removed_window_over_a_changed_browsing_context() {
+ let mut session = Session::new("child-left".to_string());
+ session.browsing_context_generation = 1;
+
+ let result = commit_frame_context(
+ &mut session,
+ 0,
+ false,
+ FrameContextMutation::Push(FrameId::Index(0)),
+ );
+
+ assert_eq!(result, Err(FrameContextCommitError::WindowMissing));
+ assert!(session.frame_context.is_empty());
+ }
+
+ #[test]
+ fn preserves_frame_context_when_top_level_commit_loses_the_selected_window() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+ session.frame_context.push(FrameId::Index(1));
+ let generation = session.browsing_context_generation;
+
+ let result =
+ commit_frame_context(&mut session, generation, false, FrameContextMutation::Clear);
+
+ assert_eq!(result, Err(FrameContextCommitError::WindowMissing));
+ assert!(matches!(
+ session.frame_context.as_slice(),
+ [FrameId::Index(0), FrameId::Index(1)]
+ ));
+ }
+
+ #[test]
+ fn preserves_frame_context_when_parent_commit_loses_the_selected_window() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+ session.frame_context.push(FrameId::Index(1));
+ let generation = session.browsing_context_generation;
+
+ let result =
+ commit_frame_context(&mut session, generation, false, FrameContextMutation::Pop);
+
+ assert_eq!(result, Err(FrameContextCommitError::WindowMissing));
+ assert!(matches!(
+ session.frame_context.as_slice(),
+ [FrameId::Index(0), FrameId::Index(1)]
+ ));
+ }
+
+ #[test]
+ fn clears_frame_context_when_switching_to_top_level() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+ let generation = session.browsing_context_generation;
+
+ let result =
+ commit_frame_context(&mut session, generation, true, FrameContextMutation::Clear);
+
+ assert_eq!(result, Ok(()));
+ assert!(session.frame_context.is_empty());
+ }
+
+ #[test]
+ fn pops_one_frame_context_when_switching_to_parent() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+ session.frame_context.push(FrameId::Index(1));
+ let generation = session.browsing_context_generation;
+
+ let result =
+ commit_frame_context(&mut session, generation, true, FrameContextMutation::Pop);
+
+ assert_eq!(result, Ok(()));
+ assert!(matches!(
+ session.frame_context.as_slice(),
+ [FrameId::Index(0)]
+ ));
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/mod.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/mod.rs
new file mode 100644
index 00000000..92904c8d
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/mod.rs
@@ -0,0 +1,46 @@
+use std::sync::Arc;
+
+use axum::extract::State;
+use serde_json::json;
+use tauri::Runtime;
+
+use super::response::{WebDriverResponse, WebDriverResult};
+use super::AppState;
+
+pub mod actions;
+pub mod alert;
+pub mod cookie;
+pub mod direct_eval;
+pub mod document;
+pub mod element;
+pub mod frame;
+pub mod navigation;
+pub mod print;
+pub mod screenshot;
+pub mod script;
+pub mod session;
+pub mod shadow;
+pub mod timeouts;
+pub mod window;
+
+/// GET `/status` - `WebDriver` server status
+///
+/// Returns ready=true only when at least one webview window is available.
+/// This ensures the WebView2/WebKit/WKWebView is fully initialized before
+/// clients attempt to create sessions.
+pub async fn status<R: Runtime>(state: State<Arc<AppState<R>>>) -> WebDriverResult {
+ // Check if any webview windows are available
+ // This is a proxy for WebView2 readiness - windows become available
+ // only after the webview is fully initialized
+ let window_labels = state.get_window_labels();
+ let ready = !window_labels.is_empty();
+
+ Ok(WebDriverResponse::success(json!({
+ "ready": ready,
+ "message": if ready {
+ "tauri-plugin-webdriver is ready"
+ } else {
+ "waiting for webview initialization"
+ }
+ })))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/navigation.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/navigation.rs
new file mode 100644
index 00000000..cfbc3e18
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/navigation.rs
@@ -0,0 +1,127 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+use crate::webdriver::ActionState;
+
+#[derive(Debug, Deserialize)]
+pub struct NavigateRequest {
+ pub url: String,
+}
+
+/// POST `/session/{session_id}/url` - Navigate to URL
+pub async fn navigate<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<NavigateRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ // Clear action state on navigation
+ session.action_state = ActionState::default();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.navigate(&request.url).await?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// GET `/session/{session_id}/url` - Get current URL
+pub async fn get_url<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let url = executor.get_url().await?;
+ Ok(WebDriverResponse::success(url))
+}
+
+/// GET `/session/{session_id}/title` - Get page title
+pub async fn get_title<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let title = executor.get_title().await?;
+ Ok(WebDriverResponse::success(title))
+}
+
+/// POST `/session/{session_id}/back` - Navigate back
+pub async fn back<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ // Clear action state on navigation
+ session.action_state = ActionState::default();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.go_back().await?;
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/forward` - Navigate forward
+pub async fn forward<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ // Clear action state on navigation
+ session.action_state = ActionState::default();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.go_forward().await?;
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/refresh` - Refresh page
+pub async fn refresh<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ // Clear action state on navigation
+ session.action_state = ActionState::default();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.refresh().await?;
+ Ok(WebDriverResponse::null())
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/print.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/print.rs
new file mode 100644
index 00000000..4fc2b892
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/print.rs
@@ -0,0 +1,73 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use tauri::Runtime;
+
+use crate::platform::PrintOptions;
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Default, Deserialize)]
+pub struct PrintRequest {
+ #[serde(default)]
+ pub orientation: Option<String>,
+ #[serde(default)]
+ pub scale: Option<f64>,
+ #[serde(default)]
+ pub background: Option<bool>,
+ #[serde(default, rename = "pageWidth")]
+ pub page_width: Option<f64>,
+ #[serde(default, rename = "pageHeight")]
+ pub page_height: Option<f64>,
+ #[serde(default, rename = "marginTop")]
+ pub margin_top: Option<f64>,
+ #[serde(default, rename = "marginBottom")]
+ pub margin_bottom: Option<f64>,
+ #[serde(default, rename = "marginLeft")]
+ pub margin_left: Option<f64>,
+ #[serde(default, rename = "marginRight")]
+ pub margin_right: Option<f64>,
+ #[serde(default, rename = "shrinkToFit")]
+ pub shrink_to_fit: Option<bool>,
+ #[serde(default, rename = "pageRanges")]
+ pub page_ranges: Option<Vec<String>>,
+}
+
+impl From<PrintRequest> for PrintOptions {
+ fn from(req: PrintRequest) -> Self {
+ PrintOptions {
+ orientation: req.orientation,
+ scale: req.scale,
+ background: req.background,
+ page_width: req.page_width,
+ page_height: req.page_height,
+ margin_top: req.margin_top,
+ margin_bottom: req.margin_bottom,
+ margin_left: req.margin_left,
+ margin_right: req.margin_right,
+ shrink_to_fit: req.shrink_to_fit,
+ page_ranges: req.page_ranges,
+ }
+ }
+}
+
+/// POST `/session/{session_id}/print` - Print page to PDF
+pub async fn print<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<PrintRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let pdf_base64 = executor.print_page(request.into()).await?;
+
+ Ok(WebDriverResponse::success(pdf_base64))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/screenshot.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/screenshot.rs
new file mode 100644
index 00000000..06311d9e
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/screenshot.rs
@@ -0,0 +1,24 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+/// GET `/session/{session_id}/screenshot` - Take screenshot
+pub async fn take<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let screenshot = executor.take_screenshot().await?;
+ Ok(WebDriverResponse::success(screenshot))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/script.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/script.rs
new file mode 100644
index 00000000..66708665
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/script.rs
@@ -0,0 +1,57 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::Value;
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct ExecuteScriptRequest {
+ pub script: String,
+ #[serde(default)]
+ pub args: Vec<Value>,
+}
+
+/// POST `/session/{session_id}/execute/sync` - Execute synchronous script
+pub async fn execute_sync<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<ExecuteScriptRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let result = executor
+ .execute_script(&request.script, &request.args)
+ .await?;
+ Ok(WebDriverResponse::success(result))
+}
+
+/// POST `/session/{session_id}/execute/async` - Execute asynchronous script
+pub async fn execute_async<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<ExecuteScriptRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let result = executor
+ .execute_async_script(&request.script, &request.args)
+ .await?;
+ Ok(WebDriverResponse::success(result))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/session.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/session.rs
new file mode 100644
index 00000000..cf4edf3d
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/session.rs
@@ -0,0 +1,217 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+use crate::webdriver::Timeouts;
+
+/// Wait for a window to become available, polling with timeout
+async fn wait_for_window<R: Runtime>(
+ state: &AppState<R>,
+ timeout_ms: u64,
+ target_label: Option<&str>,
+) -> Result<String, WebDriverErrorResponse> {
+ let start = std::time::Instant::now();
+ let timeout = std::time::Duration::from_millis(timeout_ms);
+ let poll_interval = std::time::Duration::from_millis(100);
+
+ loop {
+ let window_labels = state.get_window_labels();
+
+ // If a specific label was requested, check for it
+ if let Some(label) = target_label {
+ if window_labels.contains(&label.to_string()) {
+ return Ok(label.to_string());
+ }
+ } else if let Some(label) = window_labels.first().cloned() {
+ // No specific label requested, use first available
+ return Ok(label);
+ }
+
+ if start.elapsed() >= timeout {
+ return Err(WebDriverErrorResponse::no_such_window());
+ }
+
+ tokio::time::sleep(poll_interval).await;
+ }
+}
+
+/// Extract window label from WDIO capabilities
+fn extract_window_label(capabilities: &serde_json::Value) -> Option<String> {
+ // Check alwaysMatch first (WDIO typically uses this)
+ if let Some(window_label) = capabilities
+ .get("alwaysMatch")
+ .and_then(|v| v.get("wdio:tauriServiceOptions"))
+ .and_then(|v| v.get("windowLabel"))
+ .and_then(|v| v.as_str())
+ {
+ return Some(window_label.to_string());
+ }
+
+ // Check firstMatch - it's an array per W3C spec, iterate to find the first match
+ if let Some(arr) = capabilities.get("firstMatch").and_then(|v| v.as_array()) {
+ for item in arr {
+ if let Some(window_label) = item
+ .get("wdio:tauriServiceOptions")
+ .and_then(|v| v.get("windowLabel"))
+ .and_then(|v| v.as_str())
+ {
+ return Some(window_label.to_string());
+ }
+ }
+ }
+
+ None
+}
+
+/// W3C `WebDriver` session request (capabilities are accepted but not processed)
+#[derive(Debug, Deserialize)]
+pub struct CreateSessionRequest {
+ #[allow(dead_code)] // Accepted for protocol compliance but not processed
+ pub capabilities: Value,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionResponse {
+ pub session_id: String,
+ pub capabilities: Value,
+}
+
+/// Parse user agent to extract browser name and version
+fn parse_user_agent(user_agent: &str) -> (String, String) {
+ // Windows WebView2: "... Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
+ if user_agent.contains("Edg/") {
+ let version = user_agent
+ .split("Edg/")
+ .nth(1)
+ .and_then(|s| s.split_whitespace().next())
+ .unwrap_or("unknown");
+ return ("msedge".to_string(), version.to_string());
+ }
+
+ // Android WebView: "... (Linux; Android 14; ...) AppleWebKit/... Chrome/120.0.0.0 ..."
+ // Must check before Linux since Android UA contains "Linux"
+ if user_agent.contains("Android") {
+ let version = user_agent
+ .split("Chrome/")
+ .nth(1)
+ .and_then(|s| s.split_whitespace().next())
+ .unwrap_or("unknown");
+ return ("chrome".to_string(), version.to_string());
+ }
+
+ // Linux WebKitGTK: "... (X11; Linux ...) AppleWebKit/... Version/2.44..."
+ if user_agent.contains("Linux") || user_agent.contains("X11") {
+ let version = user_agent
+ .split("AppleWebKit/")
+ .nth(1)
+ .and_then(|s| s.split_whitespace().next())
+ .unwrap_or("unknown");
+ return ("WebKitGTK".to_string(), version.to_string());
+ }
+
+ // iOS WKWebView: "... (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 ..."
+ // Also handles iPad and iPod
+ if (user_agent.contains("iPhone") || user_agent.contains("iPad") || user_agent.contains("iPod"))
+ && user_agent.contains("AppleWebKit/")
+ {
+ let version = user_agent
+ .split("AppleWebKit/")
+ .nth(1)
+ .and_then(|s| s.split_whitespace().next())
+ .and_then(|s| s.split('(').next()) // Remove trailing (KHTML if present
+ .unwrap_or("unknown");
+ return ("webkit".to_string(), version.to_string());
+ }
+
+ // macOS WebKit/WKWebView: "... (Macintosh; ...) AppleWebKit/605.1.15 ..."
+ // Note: WKWebView may not include "Safari/" or "Version/"
+ if user_agent.contains("Macintosh") && user_agent.contains("AppleWebKit/") {
+ let version = user_agent
+ .split("AppleWebKit/")
+ .nth(1)
+ .and_then(|s| s.split_whitespace().next())
+ .and_then(|s| s.split('(').next()) // Remove trailing (KHTML if present
+ .unwrap_or("unknown");
+ return ("webkit".to_string(), version.to_string());
+ }
+
+ ("webview".to_string(), "unknown".to_string())
+}
+
+/// POST `/session` - Create a new session
+pub async fn create<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Json(request): Json<CreateSessionRequest>,
+) -> WebDriverResult {
+ // Extract window label from capabilities if provided
+ let target_window = extract_window_label(&request.capabilities);
+
+ // Wait for the target window (or first available if no target)
+ let initial_window = wait_for_window(&state, 10_000, target_window.as_deref()).await?;
+
+ // Query the webview for its user agent to get browser info
+ let executor =
+ state.get_executor_for_window(&initial_window, Timeouts::default(), Vec::new())?;
+ let user_agent_result = executor
+ .evaluate_js("(function() { return navigator.userAgent; })()")
+ .await;
+
+ let (browser_name, browser_version) = match user_agent_result {
+ Ok(result) => {
+ let user_agent = result.get("value").and_then(|v| v.as_str()).unwrap_or("");
+ parse_user_agent(user_agent)
+ }
+ Err(_) => ("webview".to_string(), "unknown".to_string()),
+ };
+
+ let mut sessions = state.sessions.write().await;
+
+ // Create session with initial window
+ let session = sessions.create(initial_window);
+
+ // Mobile platforms don't support window rect manipulation
+ #[cfg(mobile)]
+ let set_window_rect = false;
+ #[cfg(desktop)]
+ let set_window_rect = true;
+
+ let response = SessionResponse {
+ session_id: session.id.clone(),
+ capabilities: json!({
+ "browserName": browser_name,
+ "browserVersion": browser_version,
+ "platformName": std::env::consts::OS,
+ "acceptInsecureCerts": false,
+ "pageLoadStrategy": "normal",
+ "setWindowRect": set_window_rect,
+ "timeouts": {
+ "implicit": session.timeouts.implicit_ms,
+ "pageLoad": session.timeouts.page_load_ms,
+ "script": session.timeouts.script_ms
+ }
+ }),
+ };
+
+ Ok(WebDriverResponse::success(response))
+}
+
+/// DELETE `/session/{session_id}` - Delete a session
+pub async fn delete<R: Runtime>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+
+ if sessions.delete(&session_id) {
+ Ok(WebDriverResponse::null())
+ } else {
+ Err(WebDriverErrorResponse::invalid_session_id(&session_id))
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/shadow.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/shadow.rs
new file mode 100644
index 00000000..4b7e3311
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/shadow.rs
@@ -0,0 +1,155 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde_json::json;
+use tauri::Runtime;
+
+use crate::server::handlers::element::FindElementRequest;
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+use crate::webdriver::locator::LocatorStrategy;
+
+/// GET `/session/{session_id}/element/{element_id}/shadow` - Get shadow root
+pub async fn get_shadow_root<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, element_id)): Path<(String, String)>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ let element = session
+ .elements
+ .get(&element_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_element)?;
+ let element_js_var = element.js_ref.clone();
+
+ // Create a new element ref for the shadow root
+ let shadow_ref = session.elements.store();
+ let shadow_js_var = shadow_ref.js_ref.clone();
+ let shadow_id = shadow_ref.id.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let found = executor
+ .get_element_shadow_root(&element_js_var, &shadow_js_var)
+ .await?;
+
+ if !found {
+ return Err(WebDriverErrorResponse::no_such_shadow_root());
+ }
+
+ Ok(WebDriverResponse::success(json!({
+ "shadow-6066-11e4-a52e-4f735466cecf": shadow_id
+ })))
+}
+
+/// POST `/session/{session_id}/shadow/{shadow_id}/element` - Find element in shadow root
+pub async fn find_element_in_shadow<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, shadow_id)): Path<(String, String)>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ // Shadow roots are stored in the same element store
+ let shadow_element = session
+ .elements
+ .get(&shadow_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_shadow_root)?;
+ let shadow_js_var = shadow_element.js_ref.clone();
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ // Use the locator method that generates expressions expecting `shadow` to be defined
+ let strategy_js = strategy.to_selector_js_single_from_shadow(&request.value);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let found = executor
+ .find_element_from_shadow(&shadow_js_var, &strategy_js, &js_var)
+ .await?;
+
+ if !found {
+ return Err(WebDriverErrorResponse::no_such_element());
+ }
+
+ Ok(WebDriverResponse::success(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ })))
+}
+
+/// POST `/session/{session_id}/shadow/{shadow_id}/elements` - Find elements in shadow root
+pub async fn find_elements_in_shadow<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path((session_id, shadow_id)): Path<(String, String)>,
+ Json(request): Json<FindElementRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ let shadow_element = session
+ .elements
+ .get(&shadow_id)
+ .ok_or_else(WebDriverErrorResponse::no_such_shadow_root)?;
+ let shadow_js_var = shadow_element.js_ref.clone();
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let strategy = LocatorStrategy::from_string(&request.using).ok_or_else(|| {
+ WebDriverErrorResponse::invalid_argument(&format!(
+ "Unknown locator strategy: {}",
+ request.using
+ ))
+ })?;
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let strategy_js = strategy.to_selector_js_from_shadow(&request.value);
+
+ // Use a temporary prefix for the trait method
+ let temp_prefix = "__wd_temp_";
+ let count = executor
+ .find_elements_from_shadow(&shadow_js_var, &strategy_js, temp_prefix)
+ .await?;
+
+ // Now store each element with proper references
+ let mut elements = Vec::new();
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ for i in 0..count {
+ let element_ref = session.elements.store();
+ let js_var = element_ref.js_ref.clone();
+ let element_id = element_ref.id.clone();
+
+ // Copy from temp storage to element's js_ref
+ let copy_script = format!(
+ "(function() {{ window.{js_var} = window['{temp_prefix}{i}']; return true; }})()"
+ );
+ let _ = executor.evaluate_js(&copy_script).await;
+
+ elements.push(json!({
+ "element-6066-11e4-a52e-4f735466cecf": element_id
+ }));
+ }
+
+ Ok(WebDriverResponse::success(elements))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/timeouts.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/timeouts.rs
new file mode 100644
index 00000000..eb9eaefc
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/timeouts.rs
@@ -0,0 +1,57 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use tauri::Runtime;
+
+use crate::server::response::{WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct TimeoutsRequest {
+ #[serde(default)]
+ pub implicit: Option<u64>,
+ #[serde(rename = "pageLoad", default)]
+ pub page_load: Option<u64>,
+ #[serde(default)]
+ pub script: Option<u64>,
+}
+
+/// GET `/session/{session_id}/timeouts` - Get session timeouts
+pub async fn get<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+
+ Ok(WebDriverResponse::success(json!({
+ "implicit": session.timeouts.implicit_ms,
+ "pageLoad": session.timeouts.page_load_ms,
+ "script": session.timeouts.script_ms
+ })))
+}
+
+/// POST `/session/{session_id}/timeouts` - Set session timeouts
+pub async fn set<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<TimeoutsRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ if let Some(implicit) = request.implicit {
+ session.timeouts.implicit_ms = implicit;
+ }
+ if let Some(page_load) = request.page_load {
+ session.timeouts.page_load_ms = page_load;
+ }
+ if let Some(script) = request.script {
+ session.timeouts.script_ms = script;
+ }
+
+ Ok(WebDriverResponse::null())
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/window.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/window.rs
new file mode 100644
index 00000000..40ecb3ae
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/handlers/window.rs
@@ -0,0 +1,262 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use tauri::{Manager, Runtime};
+
+use crate::platform::WindowRect;
+use crate::server::response::{WebDriverErrorResponse, WebDriverResponse, WebDriverResult};
+use crate::server::AppState;
+
+#[derive(Debug, Deserialize)]
+pub struct SwitchWindowRequest {
+ pub handle: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NewWindowRequest {
+ #[allow(dead_code)] // Part of W3C protocol but not used in current implementation
+ #[serde(rename = "type", default)]
+ pub window_type: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct WindowRectRequest {
+ #[serde(default)]
+ pub x: Option<i32>,
+ #[serde(default)]
+ pub y: Option<i32>,
+ #[serde(default)]
+ pub width: Option<u32>,
+ #[serde(default)]
+ pub height: Option<u32>,
+}
+
+/// GET `/session/{session_id}/window` - Get current window handle
+pub async fn get_window_handle<R: Runtime>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ drop(sessions);
+
+ // Return the session's current window handle
+ Ok(WebDriverResponse::success(current_window))
+}
+
+/// GET `/session/{session_id}/window/handles` - Get all window handles
+pub async fn get_window_handles<R: Runtime>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let _session = sessions.get(&session_id)?;
+ drop(sessions);
+
+ // Return all window labels as handles
+ let handles: Vec<String> = state.app.webview_windows().keys().cloned().collect();
+
+ Ok(WebDriverResponse::success(handles))
+}
+
+/// DELETE `/session/{session_id}/window` - Close current window
+pub async fn close_window<R: Runtime>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ // Window closing is not supported on mobile platforms
+ #[cfg(mobile)]
+ {
+ let _ = (state, session_id);
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Closing windows is not supported on mobile platforms",
+ ))
+ }
+
+ #[cfg(desktop)]
+ {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ drop(sessions);
+
+ // Close the current window
+ if let Some(window) = state.app.webview_windows().get(&current_window).cloned() {
+ window
+ .destroy()
+ .map_err(|e| WebDriverErrorResponse::unknown_error(&e.to_string()))?;
+
+ // Return remaining window handles
+ let handles: Vec<String> = state.app.webview_windows().keys().cloned().collect();
+
+ Ok(WebDriverResponse::success(handles))
+ } else {
+ Err(WebDriverErrorResponse::no_such_window())
+ }
+ }
+}
+
+/// POST `/session/{session_id}/window` - Switch to window
+pub async fn switch_to_window<R: Runtime>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<SwitchWindowRequest>,
+) -> WebDriverResult {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&session_id)?;
+
+ // Verify the window exists
+ if !state.app.webview_windows().contains_key(&request.handle) {
+ return Err(WebDriverErrorResponse::no_such_window());
+ }
+
+ session.switch_to_window(request.handle).map_err(|_| {
+ WebDriverErrorResponse::unknown_error("Browsing context generation overflowed")
+ })?;
+
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/window/new` - Create new window
+pub async fn new_window<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(_request): Json<NewWindowRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let _session = sessions.get(&session_id)?;
+ drop(sessions);
+
+ // Note: Creating new windows in Tauri requires app-specific logic
+ // This is a stub that returns an error - apps should handle this via commands
+ Err(WebDriverErrorResponse::unsupported_operation(
+ "Creating new windows is not supported in this context",
+ ))
+}
+
+/// GET `/session/{session_id}/window/rect` - Get window rect
+pub async fn get_rect<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let rect = executor.get_window_rect().await?;
+
+ Ok(WebDriverResponse::success(json!({
+ "x": rect.x,
+ "y": rect.y,
+ "width": rect.width,
+ "height": rect.height
+ })))
+}
+
+/// POST `/session/{session_id}/window/rect` - Set window rect
+pub async fn set_rect<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+ Json(request): Json<WindowRectRequest>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+
+ // Get current rect to fill in missing values
+ let current = executor.get_window_rect().await?;
+
+ let new_rect = WindowRect {
+ x: request.x.unwrap_or(current.x),
+ y: request.y.unwrap_or(current.y),
+ width: request.width.unwrap_or(current.width),
+ height: request.height.unwrap_or(current.height),
+ };
+
+ let rect = executor.set_window_rect(new_rect).await?;
+
+ Ok(WebDriverResponse::success(json!({
+ "x": rect.x,
+ "y": rect.y,
+ "width": rect.width,
+ "height": rect.height
+ })))
+}
+
+/// POST `/session/{session_id}/window/maximize` - Maximize window
+pub async fn maximize<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let rect = executor.maximize_window().await?;
+
+ Ok(WebDriverResponse::success(json!({
+ "x": rect.x,
+ "y": rect.y,
+ "width": rect.width,
+ "height": rect.height
+ })))
+}
+
+/// POST `/session/{session_id}/window/minimize` - Minimize window
+pub async fn minimize<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ executor.minimize_window().await?;
+
+ // Return null per W3C spec (minimized window has no meaningful rect)
+ Ok(WebDriverResponse::null())
+}
+
+/// POST `/session/{session_id}/window/fullscreen` - Fullscreen window
+pub async fn fullscreen<R: Runtime + 'static>(
+ State(state): State<Arc<AppState<R>>>,
+ Path(session_id): Path<String>,
+) -> WebDriverResult {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&session_id)?;
+ let current_window = session.current_window.clone();
+ let timeouts = session.timeouts.clone();
+ let frame_context = session.frame_context.clone();
+ drop(sessions);
+
+ let executor = state.get_executor_for_window(&current_window, timeouts, frame_context)?;
+ let rect = executor.fullscreen_window().await?;
+
+ Ok(WebDriverResponse::success(json!({
+ "x": rect.x,
+ "y": rect.y,
+ "width": rect.width,
+ "height": rect.height
+ })))
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/mod.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/mod.rs
new file mode 100644
index 00000000..c1c657f7
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/mod.rs
@@ -0,0 +1,96 @@
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use tauri::{AppHandle, Manager, Runtime};
+use tokio::runtime::Runtime as TokioRuntime;
+use tokio::sync::RwLock;
+
+pub mod handlers;
+pub mod response;
+pub mod router;
+
+use crate::platform::{create_executor, FrameId, PlatformExecutor};
+use crate::server::response::WebDriverErrorResponse;
+use crate::webdriver::{SessionManager, Timeouts};
+
+/// Shared state for the `WebDriver` server
+pub struct AppState<R: Runtime> {
+ pub app: AppHandle<R>,
+ pub sessions: RwLock<SessionManager>,
+}
+
+impl<R: Runtime + 'static> AppState<R> {
+ pub fn new(app: AppHandle<R>) -> Self {
+ Self {
+ app,
+ sessions: RwLock::new(SessionManager::new()),
+ }
+ }
+
+ /// Get a platform executor for a specific window by label
+ pub fn get_executor_for_window(
+ &self,
+ window_label: &str,
+ timeouts: Timeouts,
+ frame_context: Vec<FrameId>,
+ ) -> Result<Arc<dyn PlatformExecutor<R>>, WebDriverErrorResponse> {
+ self.app
+ .webview_windows()
+ .get(window_label)
+ .cloned()
+ .map(|window| create_executor(window, timeouts, frame_context))
+ .ok_or_else(WebDriverErrorResponse::no_such_window)
+ }
+
+ /// Whether a window with this label is still registered
+ pub fn has_window_label(&self, window_label: &str) -> bool {
+ self.app.webview_windows().contains_key(window_label)
+ }
+
+ /// Get all window labels
+ pub fn get_window_labels(&self) -> Vec<String> {
+ self.app.webview_windows().keys().cloned().collect()
+ }
+}
+
+/// Start the `WebDriver` HTTP server on the specified port
+pub fn start<R: Runtime + 'static>(app: AppHandle<R>, port: u16) {
+ std::thread::spawn(move || {
+ let rt = match TokioRuntime::new() {
+ Ok(rt) => rt,
+ Err(e) => {
+ tracing::error!("Failed to create Tokio runtime for WebDriver server: {}", e);
+ return;
+ }
+ };
+
+ rt.block_on(async {
+ let state = Arc::new(AppState::new(app));
+ let router = router::create_router(state);
+
+ // On Android, bind to all interfaces for WiFi accessibility
+ // On other platforms, bind to localhost only for security
+ #[cfg(target_os = "android")]
+ let addr = SocketAddr::from(([0, 0, 0, 0], port));
+ #[cfg(not(target_os = "android"))]
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+
+ let listener = match tokio::net::TcpListener::bind(addr).await {
+ Ok(l) => l,
+ Err(e) => {
+ tracing::error!(
+ "Failed to bind WebDriver server to {} — port may already be in use: {}",
+ addr, e
+ );
+ return;
+ }
+ };
+
+ tracing::info!("WebDriver server listening on http://{}", addr);
+
+ if let Err(e) = axum::serve(listener, router).await {
+ tracing::error!("WebDriver server error: {}", e);
+ }
+ });
+ });
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/response.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/response.rs
new file mode 100644
index 00000000..6d0797ea
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/response.rs
@@ -0,0 +1,241 @@
+use axum::{
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Serialize;
+use serde_json::{json, Value};
+
+/// W3C `WebDriver` success response
+#[derive(Debug, Serialize)]
+pub struct WebDriverResponse {
+ pub value: Value,
+}
+
+impl WebDriverResponse {
+ pub fn success<T: Serialize>(value: T) -> Self {
+ Self {
+ value: serde_json::to_value(value).unwrap_or(Value::Null),
+ }
+ }
+
+ pub fn null() -> Self {
+ Self { value: Value::Null }
+ }
+}
+
+impl IntoResponse for WebDriverResponse {
+ fn into_response(self) -> Response {
+ (
+ StatusCode::OK,
+ [("Content-Type", "application/json; charset=utf-8")],
+ Json(self),
+ )
+ .into_response()
+ }
+}
+
+/// W3C `WebDriver` error response
+#[derive(Debug)]
+pub struct WebDriverErrorResponse {
+ pub status: StatusCode,
+ pub error: String,
+ pub message: String,
+ pub stacktrace: Option<String>,
+}
+
+impl WebDriverErrorResponse {
+ pub fn new(status: StatusCode, error: &str, message: &str, stacktrace: Option<String>) -> Self {
+ Self {
+ status,
+ error: error.to_string(),
+ message: message.to_string(),
+ stacktrace,
+ }
+ }
+
+ pub fn invalid_session_id(session_id: &str) -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "invalid session id",
+ &format!("Session {session_id} not found"),
+ None,
+ )
+ }
+
+ pub fn no_such_element() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such element",
+ "Unable to locate element",
+ None,
+ )
+ }
+
+ pub fn no_such_window() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such window",
+ "No window could be found",
+ None,
+ )
+ }
+
+ pub fn no_such_alert() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such alert",
+ "No alert is currently open",
+ None,
+ )
+ }
+
+ pub fn javascript_error(message: &str, stacktrace: Option<String>) -> Self {
+ // Map known JS error messages to their correct W3C error codes
+ if message.contains("stale element reference") {
+ return Self::stale_element_reference();
+ }
+
+ Self::new(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "javascript error",
+ message,
+ stacktrace,
+ )
+ }
+
+ pub fn stale_element_reference() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "stale element reference",
+ "Element is no longer attached to the DOM",
+ None,
+ )
+ }
+
+ pub fn unknown_error(message: &str) -> Self {
+ Self::new(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unknown error",
+ message,
+ None,
+ )
+ }
+
+ pub fn invalid_argument(message: &str) -> Self {
+ Self::new(StatusCode::BAD_REQUEST, "invalid argument", message, None)
+ }
+
+ pub fn unsupported_operation(message: &str) -> Self {
+ Self::new(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unsupported operation",
+ message,
+ None,
+ )
+ }
+
+ pub fn no_such_shadow_root() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such shadow root",
+ "Element does not have a shadow root",
+ None,
+ )
+ }
+
+ pub fn script_timeout() -> Self {
+ Self::new(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "script timeout",
+ "Script execution timed out",
+ None,
+ )
+ }
+
+ pub fn no_such_cookie(name: &str) -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such cookie",
+ &format!("Cookie '{name}' not found"),
+ None,
+ )
+ }
+
+ pub fn no_such_frame() -> Self {
+ Self::new(
+ StatusCode::NOT_FOUND,
+ "no such frame",
+ "Unable to locate frame",
+ None,
+ )
+ }
+
+ pub fn element_not_interactable(message: &str) -> Self {
+ Self::new(
+ StatusCode::BAD_REQUEST,
+ "element not interactable",
+ message,
+ None,
+ )
+ }
+}
+
+impl IntoResponse for WebDriverErrorResponse {
+ fn into_response(self) -> Response {
+ let body = json!({
+ "value": {
+ "error": self.error,
+ "message": self.message,
+ "stacktrace": self.stacktrace.unwrap_or_default()
+ }
+ });
+
+ (
+ self.status,
+ [("Content-Type", "application/json; charset=utf-8")],
+ Json(body),
+ )
+ .into_response()
+ }
+}
+
+/// Result type for `WebDriver` handlers
+pub type WebDriverResult = Result<WebDriverResponse, WebDriverErrorResponse>;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn javascript_error_maps_stale_element_reference() {
+ let err = WebDriverErrorResponse::javascript_error("stale element reference", None);
+ assert_eq!(err.status, StatusCode::NOT_FOUND);
+ assert_eq!(err.error, "stale element reference");
+ }
+
+ #[test]
+ fn javascript_error_preserves_generic_errors() {
+ let err = WebDriverErrorResponse::javascript_error("TypeError: x is not a function", None);
+ assert_eq!(err.status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(err.error, "javascript error");
+ assert_eq!(err.message, "TypeError: x is not a function");
+ }
+
+ #[test]
+ fn javascript_error_preserves_stacktrace_for_generic_errors() {
+ let err = WebDriverErrorResponse::javascript_error(
+ "ReferenceError: foo is not defined",
+ Some("at eval:1:1".to_string()),
+ );
+ assert_eq!(err.error, "javascript error");
+ assert_eq!(err.stacktrace, Some("at eval:1:1".to_string()));
+ }
+
+ #[test]
+ fn stale_element_reference_returns_not_found() {
+ let err = WebDriverErrorResponse::stale_element_reference();
+ assert_eq!(err.status, StatusCode::NOT_FOUND);
+ assert_eq!(err.error, "stale element reference");
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/router.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/router.rs
new file mode 100644
index 00000000..8b0fc0aa
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/server/router.rs
@@ -0,0 +1,243 @@
+use std::sync::Arc;
+
+use axum::{
+ routing::{delete, get, post},
+ Router,
+};
+use tauri::Runtime;
+
+use super::handlers;
+use super::AppState;
+
+/// Create the `WebDriver` router with all W3C `WebDriver` endpoints
+#[allow(clippy::too_many_lines)]
+pub fn create_router<R: Runtime + 'static>(state: Arc<AppState<R>>) -> Router {
+ Router::new()
+ // Status
+ .route("/status", get(handlers::status::<R>))
+ // wdio-specific non-W3C endpoints
+ .route("/wdio/eval", post(handlers::direct_eval::eval::<R>))
+ // =================================================================
+ // W3C WebDriver Standard Endpoints
+ // =================================================================
+ // Session management
+ .route("/session", post(handlers::session::create::<R>))
+ .route(
+ "/session/{session_id}",
+ delete(handlers::session::delete::<R>),
+ )
+ // Timeouts
+ .route(
+ "/session/{session_id}/timeouts",
+ get(handlers::timeouts::get::<R>).post(handlers::timeouts::set::<R>),
+ )
+ // Navigation
+ .route(
+ "/session/{session_id}/url",
+ get(handlers::navigation::get_url::<R>).post(handlers::navigation::navigate::<R>),
+ )
+ .route(
+ "/session/{session_id}/title",
+ get(handlers::navigation::get_title::<R>),
+ )
+ .route(
+ "/session/{session_id}/back",
+ post(handlers::navigation::back::<R>),
+ )
+ .route(
+ "/session/{session_id}/forward",
+ post(handlers::navigation::forward::<R>),
+ )
+ .route(
+ "/session/{session_id}/refresh",
+ post(handlers::navigation::refresh::<R>),
+ )
+ // Elements
+ .route(
+ "/session/{session_id}/element",
+ post(handlers::element::find::<R>),
+ )
+ .route(
+ "/session/{session_id}/elements",
+ post(handlers::element::find_all::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/active",
+ get(handlers::element::get_active::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/element",
+ post(handlers::element::find_from_element::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/elements",
+ post(handlers::element::find_all_from_element::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/click",
+ post(handlers::element::click::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/clear",
+ post(handlers::element::clear::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/value",
+ post(handlers::element::send_keys::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/text",
+ get(handlers::element::get_text::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/name",
+ get(handlers::element::get_tag_name::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/attribute/{name}",
+ get(handlers::element::get_attribute::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/property/{name}",
+ get(handlers::element::get_property::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/css/{property_name}",
+ get(handlers::element::get_css_value::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/rect",
+ get(handlers::element::get_rect::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/selected",
+ get(handlers::element::is_selected::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/displayed",
+ get(handlers::element::is_displayed::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/enabled",
+ get(handlers::element::is_enabled::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/computedrole",
+ get(handlers::element::get_computed_role::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/computedlabel",
+ get(handlers::element::get_computed_label::<R>),
+ )
+ .route(
+ "/session/{session_id}/element/{element_id}/screenshot",
+ get(handlers::element::take_screenshot::<R>),
+ )
+ // Shadow DOM
+ .route(
+ "/session/{session_id}/element/{element_id}/shadow",
+ get(handlers::shadow::get_shadow_root::<R>),
+ )
+ .route(
+ "/session/{session_id}/shadow/{shadow_id}/element",
+ post(handlers::shadow::find_element_in_shadow::<R>),
+ )
+ .route(
+ "/session/{session_id}/shadow/{shadow_id}/elements",
+ post(handlers::shadow::find_elements_in_shadow::<R>),
+ )
+ // Execute Script
+ .route(
+ "/session/{session_id}/execute/sync",
+ post(handlers::script::execute_sync::<R>),
+ )
+ .route(
+ "/session/{session_id}/execute/async",
+ post(handlers::script::execute_async::<R>),
+ )
+ // Screenshot
+ .route(
+ "/session/{session_id}/screenshot",
+ get(handlers::screenshot::take::<R>),
+ )
+ // Document
+ .route(
+ "/session/{session_id}/source",
+ get(handlers::document::get_source::<R>),
+ )
+ // Window
+ .route(
+ "/session/{session_id}/window",
+ get(handlers::window::get_window_handle::<R>)
+ .post(handlers::window::switch_to_window::<R>)
+ .delete(handlers::window::close_window::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/new",
+ post(handlers::window::new_window::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/handles",
+ get(handlers::window::get_window_handles::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/rect",
+ get(handlers::window::get_rect::<R>).post(handlers::window::set_rect::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/maximize",
+ post(handlers::window::maximize::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/minimize",
+ post(handlers::window::minimize::<R>),
+ )
+ .route(
+ "/session/{session_id}/window/fullscreen",
+ post(handlers::window::fullscreen::<R>),
+ )
+ // Frames
+ .route(
+ "/session/{session_id}/frame",
+ post(handlers::frame::switch_to_frame::<R>),
+ )
+ .route(
+ "/session/{session_id}/frame/parent",
+ post(handlers::frame::switch_to_parent_frame::<R>),
+ )
+ // Actions
+ .route(
+ "/session/{session_id}/actions",
+ post(handlers::actions::perform::<R>).delete(handlers::actions::release::<R>),
+ )
+ // Cookies
+ .route(
+ "/session/{session_id}/cookie",
+ get(handlers::cookie::get_all::<R>)
+ .post(handlers::cookie::add::<R>)
+ .delete(handlers::cookie::delete_all::<R>),
+ )
+ .route(
+ "/session/{session_id}/cookie/{name}",
+ get(handlers::cookie::get::<R>).delete(handlers::cookie::delete::<R>),
+ )
+ // Alerts
+ .route(
+ "/session/{session_id}/alert/dismiss",
+ post(handlers::alert::dismiss::<R>),
+ )
+ .route(
+ "/session/{session_id}/alert/accept",
+ post(handlers::alert::accept::<R>),
+ )
+ .route(
+ "/session/{session_id}/alert/text",
+ get(handlers::alert::get_text::<R>).post(handlers::alert::send_text::<R>),
+ )
+ // Print
+ .route(
+ "/session/{session_id}/print",
+ post(handlers::print::print::<R>),
+ )
+ .with_state(state)
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/element.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/element.rs
new file mode 100644
index 00000000..9d7bfd74
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/element.rs
@@ -0,0 +1,90 @@
+use std::collections::HashMap;
+
+use uuid::Uuid;
+
+/// Represents a `WebDriver` element reference
+#[derive(Debug, Clone)]
+pub struct ElementRef {
+ /// `WebDriver` element ID (returned to client)
+ pub id: String,
+ /// JavaScript variable name holding the element reference
+ pub js_ref: String,
+}
+
+/// Storage for element references within a session
+#[derive(Debug, Default)]
+pub struct ElementStore {
+ elements: HashMap<String, ElementRef>,
+}
+
+impl ElementStore {
+ pub fn new() -> Self {
+ Self {
+ elements: HashMap::new(),
+ }
+ }
+
+ /// Store a new element and return its reference
+ pub fn store(&mut self) -> ElementRef {
+ let id = Uuid::new_v4().to_string();
+ // Remove hyphens from UUID for valid JS variable name
+ let id_no_hyphens = id.replace('-', "");
+ let js_ref = format!("__wd_el_{id_no_hyphens}");
+
+ let elem_ref = ElementRef {
+ id: id.clone(),
+ js_ref,
+ };
+
+ self.elements.insert(id, elem_ref.clone());
+ elem_ref
+ }
+
+ /// Get element by `WebDriver` ID
+ pub fn get(&self, id: &str) -> Option<&ElementRef> {
+ self.elements.get(id)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_store_element() {
+ let mut store = ElementStore::new();
+ let elem = store.store();
+
+ assert!(!elem.id.is_empty());
+ assert!(elem.js_ref.starts_with("__wd_el_"));
+ // js_ref uses ID without hyphens
+ assert!(elem.js_ref.contains(&elem.id.replace('-', "")));
+ }
+
+ #[test]
+ fn test_get_element() {
+ let mut store = ElementStore::new();
+ let elem = store.store();
+ let id = elem.id.clone();
+
+ let retrieved = store.get(&id).expect("element should exist");
+ assert_eq!(retrieved.id, id);
+ }
+
+ #[test]
+ fn test_js_ref_uses_id_without_hyphens() {
+ let mut store = ElementStore::new();
+ let elem1 = store.store();
+ let elem2 = store.store();
+
+ // js_ref should use ID with hyphens removed for valid JS variable name
+ assert_eq!(
+ elem1.js_ref,
+ format!("__wd_el_{}", elem1.id.replace('-', ""))
+ );
+ assert_eq!(
+ elem2.js_ref,
+ format!("__wd_el_{}", elem2.id.replace('-', ""))
+ );
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/locator.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/locator.rs
new file mode 100644
index 00000000..8e744194
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/locator.rs
@@ -0,0 +1,278 @@
+/// Locator strategies for finding elements
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LocatorStrategy {
+ CssSelector,
+ LinkText,
+ PartialLinkText,
+ TagName,
+ XPath,
+}
+
+impl LocatorStrategy {
+ /// Parse locator strategy from `WebDriver` string
+ pub fn from_string(s: &str) -> Option<Self> {
+ match s {
+ "css selector" => Some(Self::CssSelector),
+ "link text" => Some(Self::LinkText),
+ "partial link text" => Some(Self::PartialLinkText),
+ "tag name" => Some(Self::TagName),
+ "xpath" => Some(Self::XPath),
+ _ => None,
+ }
+ }
+
+ /// Generate JavaScript expression to find element (just the selector, no wrapper)
+ pub fn to_selector_js(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector => {
+ format!("document.querySelector('{escaped}')")
+ }
+ LocatorStrategy::TagName => {
+ format!("document.getElementsByTagName('{escaped}')[0] || null")
+ }
+ LocatorStrategy::XPath => {
+ format!(
+ r"(function() {{
+ var result = document.evaluate('{escaped}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(document.querySelectorAll('a')).find(a => a.textContent.trim() === '{escaped}') || null"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(document.querySelectorAll('a')).find(a => a.textContent.includes('{escaped}')) || null"
+ )
+ }
+ }
+ }
+
+ /// Generate JavaScript expression to find multiple elements
+ pub fn to_selector_js_multiple(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector => {
+ format!("Array.from(document.querySelectorAll('{escaped}'))")
+ }
+ LocatorStrategy::TagName => {
+ format!("Array.from(document.getElementsByTagName('{escaped}'))")
+ }
+ LocatorStrategy::XPath => {
+ format!(
+ r"(function() {{
+ var result = [];
+ var iter = document.evaluate('{escaped}', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
+ var node;
+ while ((node = iter.iterateNext())) {{
+ result.push(node);
+ }}
+ return result;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(document.querySelectorAll('a')).filter(a => a.textContent.trim() === '{escaped}')"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(document.querySelectorAll('a')).filter(a => a.textContent.includes('{escaped}'))"
+ )
+ }
+ }
+ }
+
+ /// Generate JavaScript expression to find a single element from a parent element
+ /// Returns an expression that evaluates to a single element (or null)
+ /// Assumes `parent` variable is defined
+ pub fn to_selector_js_single_from_element(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector => {
+ format!("parent.querySelector('{escaped}')")
+ }
+ LocatorStrategy::TagName => {
+ format!("parent.getElementsByTagName('{escaped}')[0] || null")
+ }
+ LocatorStrategy::XPath => {
+ format!(
+ r"(function() {{
+ var result = document.evaluate('{escaped}', parent, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(parent.querySelectorAll('a')).find(a => a.textContent.trim() === '{escaped}') || null"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(parent.querySelectorAll('a')).find(a => a.textContent.includes('{escaped}')) || null"
+ )
+ }
+ }
+ }
+
+ /// Generate JavaScript expression to find multiple elements from a parent element
+ /// Returns an expression that evaluates to an array-like collection
+ /// Assumes `parent` variable is defined
+ pub fn to_selector_js_from_element(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector => {
+ format!("Array.from(parent.querySelectorAll('{escaped}'))")
+ }
+ LocatorStrategy::TagName => {
+ format!("Array.from(parent.getElementsByTagName('{escaped}'))")
+ }
+ LocatorStrategy::XPath => {
+ format!(
+ r"(function() {{
+ var result = [];
+ var iter = document.evaluate('{escaped}', parent, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
+ var node;
+ while ((node = iter.iterateNext())) {{
+ result.push(node);
+ }}
+ return result;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(parent.querySelectorAll('a')).filter(a => a.textContent.trim() === '{escaped}')"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(parent.querySelectorAll('a')).filter(a => a.textContent.includes('{escaped}'))"
+ )
+ }
+ }
+ }
+
+ /// Generate JavaScript expression to find a single element from a shadow root
+ /// Returns an expression that evaluates to a single element (or null)
+ /// Assumes `shadow` variable is defined
+ pub fn to_selector_js_single_from_shadow(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector | LocatorStrategy::TagName => {
+ format!("shadow.querySelector('{escaped}')")
+ }
+ LocatorStrategy::XPath => {
+ // XPath from shadow root context
+ format!(
+ r"(function() {{
+ var result = document.evaluate('{escaped}', shadow, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
+ return result.singleNodeValue;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(shadow.querySelectorAll('a')).find(a => a.textContent.trim() === '{escaped}') || null"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(shadow.querySelectorAll('a')).find(a => a.textContent.includes('{escaped}')) || null"
+ )
+ }
+ }
+ }
+
+ /// Generate JavaScript expression to find multiple elements from a shadow root
+ /// Returns an expression that evaluates to an array-like collection
+ /// Assumes `shadow` variable is defined
+ pub fn to_selector_js_from_shadow(self, value: &str) -> String {
+ let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
+
+ match self {
+ LocatorStrategy::CssSelector | LocatorStrategy::TagName => {
+ format!("Array.from(shadow.querySelectorAll('{escaped}'))")
+ }
+ LocatorStrategy::XPath => {
+ format!(
+ r"(function() {{
+ var result = [];
+ var iter = document.evaluate('{escaped}', shadow, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
+ var node;
+ while ((node = iter.iterateNext())) {{
+ result.push(node);
+ }}
+ return result;
+ }})()"
+ )
+ }
+ LocatorStrategy::LinkText => {
+ format!(
+ r"Array.from(shadow.querySelectorAll('a')).filter(a => a.textContent.trim() === '{escaped}')"
+ )
+ }
+ LocatorStrategy::PartialLinkText => {
+ format!(
+ r"Array.from(shadow.querySelectorAll('a')).filter(a => a.textContent.includes('{escaped}'))"
+ )
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_strategy() {
+ assert_eq!(
+ LocatorStrategy::from_string("css selector"),
+ Some(LocatorStrategy::CssSelector)
+ );
+ assert_eq!(
+ LocatorStrategy::from_string("xpath"),
+ Some(LocatorStrategy::XPath)
+ );
+ assert_eq!(LocatorStrategy::from_string("unknown"), None);
+ }
+
+ #[test]
+ fn test_css_selector_js() {
+ let strategy = LocatorStrategy::CssSelector;
+ let js = strategy.to_selector_js("#my-button");
+
+ assert!(js.contains("querySelector"));
+ assert!(js.contains("#my-button"));
+ }
+
+ #[test]
+ fn test_xpath_js() {
+ let strategy = LocatorStrategy::XPath;
+ let js = strategy.to_selector_js("//div[@id='test']");
+
+ assert!(js.contains("document.evaluate"));
+ // Single quotes are escaped in the output
+ assert!(js.contains("//div[@id=\\'test\\']"));
+ }
+
+ #[test]
+ fn test_escaping() {
+ let strategy = LocatorStrategy::CssSelector;
+ let js = strategy.to_selector_js("div[data-value='test']");
+
+ assert!(js.contains("div[data-value=\\'test\\']"));
+ }
+}
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/mod.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/mod.rs
new file mode 100644
index 00000000..018ff2ae
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/mod.rs
@@ -0,0 +1,5 @@
+pub mod element;
+pub mod locator;
+pub mod session;
+
+pub use session::{ActionState, SessionManager, Timeouts};
diff --git a/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/session.rs b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/session.rs
new file mode 100644
index 00000000..611d05e5
--- /dev/null
+++ b/src-tauri/vendor/tauri-plugin-wdio-webdriver/src/webdriver/session.rs
@@ -0,0 +1,172 @@
+use std::collections::{HashMap, HashSet};
+
+use serde::Serialize;
+use uuid::Uuid;
+
+use super::element::ElementStore;
+use crate::platform::FrameId;
+use crate::server::response::WebDriverErrorResponse;
+
+/// Tracks currently pressed keys and pointer buttons for action state
+#[derive(Debug, Default, Clone)]
+pub struct ActionState {
+ /// Currently pressed keyboard keys (`WebDriver` key codes)
+ pub pressed_keys: HashSet<String>,
+ /// Currently pressed pointer buttons by source ID
+ pub pressed_buttons: HashMap<String, HashSet<u32>>,
+ /// Last pointer position in viewport coordinates. Persisted across
+ /// `performActions` calls so an `origin: "pointer"` move resolves relative to
+ /// where the pointer actually is, not (0, 0) at the start of every call.
+ pub pointer_position: (i32, i32),
+}
+
+/// Session timeouts configuration
+#[derive(Debug, Clone, Serialize)]
+#[allow(clippy::struct_field_names)]
+pub struct Timeouts {
+ /// Implicit wait timeout in milliseconds
+ pub implicit_ms: u64,
+ /// Page load timeout in milliseconds
+ pub page_load_ms: u64,
+ /// Script execution timeout in milliseconds
+ pub script_ms: u64,
+}
+
+impl Default for Timeouts {
+ fn default() -> Self {
+ Self {
+ implicit_ms: 0,
+ page_load_ms: 300_000,
+ script_ms: 30_000,
+ }
+ }
+}
+
+/// Represents a `WebDriver` session
+#[derive(Debug)]
+pub struct Session {
+ /// Unique session identifier
+ pub id: String,
+ /// Session timeouts
+ pub timeouts: Timeouts,
+ /// Element reference storage
+ pub elements: ElementStore,
+ /// Current window handle
+ pub current_window: String,
+ /// Current frame context (stack of frame selectors)
+ pub frame_context: Vec<FrameId>,
+ /// Increments whenever the selected top-level browsing context changes
+ pub browsing_context_generation: u64,
+ /// Action state tracking for pressed keys/buttons
+ pub action_state: ActionState,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum SwitchWindowError {
+ BrowsingContextGenerationOverflow,
+}
+
+impl Session {
+ pub fn new(initial_window: String) -> Self {
+ Self {
+ id: Uuid::new_v4().to_string(),
+ timeouts: Timeouts::default(),
+ elements: ElementStore::new(),
+ current_window: initial_window,
+ frame_context: Vec::new(),
+ browsing_context_generation: 0,
+ action_state: ActionState::default(),
+ }
+ }
+
+ pub fn switch_to_window(&mut self, window: String) -> Result<(), SwitchWindowError> {
+ let browsing_context_generation = self
+ .browsing_context_generation
+ .checked_add(1)
+ .ok_or(SwitchWindowError::BrowsingContextGenerationOverflow)?;
+
+ self.current_window = window;
+ self.frame_context.clear();
+ self.browsing_context_generation = browsing_context_generation;
+
+ Ok(())
+ }
+}
+
+/// Manages `WebDriver` sessions
+#[derive(Debug, Default)]
+pub struct SessionManager {
+ sessions: HashMap<String, Session>,
+}
+
+impl SessionManager {
+ pub fn new() -> Self {
+ Self {
+ sessions: HashMap::new(),
+ }
+ }
+
+ /// Create a new session
+ pub fn create(&mut self, initial_window: String) -> &Session {
+ let session = Session::new(initial_window);
+ let id = session.id.clone();
+ self.sessions.insert(id.clone(), session);
+ self.sessions.get(&id).expect("session was just inserted")
+ }
+
+ /// Get a session by ID
+ pub fn get(&self, id: &str) -> Result<&Session, WebDriverErrorResponse> {
+ self.sessions
+ .get(id)
+ .ok_or_else(|| WebDriverErrorResponse::invalid_session_id(id))
+ }
+
+ /// Get a mutable session by ID
+ pub fn get_mut(&mut self, id: &str) -> Result<&mut Session, WebDriverErrorResponse> {
+ self.sessions
+ .get_mut(id)
+ .ok_or_else(|| WebDriverErrorResponse::invalid_session_id(id))
+ }
+
+ /// Delete a session
+ pub fn delete(&mut self, id: &str) -> bool {
+ self.sessions.remove(id).is_some()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{FrameId, Session, SwitchWindowError};
+
+ #[test]
+ fn switching_windows_updates_context_and_generation_together() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+
+ assert_eq!(session.switch_to_window("child-right".to_string()), Ok(()));
+
+ assert_eq!(session.current_window, "child-right");
+ assert!(session.frame_context.is_empty());
+ assert_eq!(session.browsing_context_generation, 1);
+ }
+
+ #[test]
+ fn switching_windows_at_max_generation_leaves_session_unchanged() {
+ let mut session = Session::new("child-left".to_string());
+ session.frame_context.push(FrameId::Index(0));
+ session.browsing_context_generation = u64::MAX;
+
+ let result = session.switch_to_window("child-right".to_string());
+
+ assert_eq!(
+ result,
+ Err(SwitchWindowError::BrowsingContextGenerationOverflow)
+ );
+ assert_eq!(session.current_window, "child-left");
+ assert!(matches!(
+ session.frame_context.as_slice(),
+ [FrameId::Index(0)]
+ ));
+ assert_eq!(session.browsing_context_generation, u64::MAX);
+ }
+}