From d33ebe5a04e82f991e120e3c65e68c4dc13a1f6d Mon Sep 17 00:00:00 2001
From: JackCaow <158038224+JackCaow@users.noreply.github.com>
Date: Tue, 10 Nov 2026 21:35:24 +0800
Subject: [PATCH 1/3] release: prepare v0.8.0 hot swap for apps under
development
Hot swap
- Add aua_hot_swap: compile edited sources, diff class bytes against what
the process runs, and redefine them in place through a JVMTI agent.
Resources are relinked with stable IDs and loaded into the process.
- Keep UI state: Compose recomposes over its existing state; View
activities are rebuilt with scroll offsets, typed text and the keyboard.
- Detect Gradle projects from the root or a module directory; settings
and caches stay in the project's build/ directory.
- Fall back to a full build, install and launch when a swap is not
possible, and report compile errors without touching the app.
- status reports the host toolchain and what the next call would do.
A paused device refuses swap and build.
- The engine lives in src/android_use/hotswap and uses only the standard
library; script/hotswap holds the command line, lab apps and the
on-device suite.
Docs: docs/hot-swap.md, README sections, guide tool tables and the skill.
Bump every version source to 0.8.0 and add release notes.
---
.claude-plugin/plugin.json | 2 +-
.codex-plugin/plugin.json | 2 +-
README.md | 8 +-
README.zh-CN.md | 8 +-
docs/guide.md | 7 +-
docs/guide.zh-CN.md | 7 +-
docs/hot-swap.md | 50 +
docs/releases/v0.8.0.md | 44 +
pyproject.toml | 2 +-
script/hotswap/.gitignore | 3 +
script/hotswap/app/AndroidManifest.xml | 13 +
script/hotswap/app/hotswap.json | 8 +
script/hotswap/app/res/layout/main.xml | 32 +
script/hotswap/app/res/values/colors.xml | 4 +
script/hotswap/app/res/values/strings.xml | 4 +
script/hotswap/app/src/lab/hotswap/Greeter.kt | 9 +
.../app/src/lab/hotswap/MainActivity.java | 63 +
.../hotswap/app/src/lab/hotswap/Message.java | 8 +
script/hotswap/app/src/lab/hotswap/Util.kt | 4 +
script/hotswap/gradle-sample/.gitignore | 4 +
.../gradle-sample/app/build.gradle.kts | 38 +
.../app/src/main/AndroidManifest.xml | 11 +
.../java/lab/hotswap/gradle/JavaMessage.java | 7 +
.../main/java/lab/hotswap/gradle/Labels.kt | 5 +
.../java/lab/hotswap/gradle/MainActivity.kt | 20 +
.../main/java/lab/hotswap/gradle/Screen.kt | 59 +
.../app/src/main/res/values/strings.xml | 4 +
script/hotswap/gradle-sample/build.gradle.kts | 4 +
.../hotswap/gradle-sample/gradle.properties | 2 +
.../hotswap/gradle-sample/settings.gradle.kts | 15 +
script/hotswap/hotswap.py | 13 +
script/hotswap/verify.py | 261 +++++
skills/android-use/SKILL.md | 2 +
src/android_use/__init__.py | 2 +-
src/android_use/assets/phone-screen.html | 2 +-
src/android_use/hotswap/__init__.py | 5 +
src/android_use/hotswap/agent/agent.cpp | 581 ++++++++++
.../hotswap/daemon/HotswapDaemon.java | 136 +++
src/android_use/hotswap/engine.py | 1021 +++++++++++++++++
.../helper/hotswap/agent/HotswapState.java | 153 +++
src/android_use/hotswap/hotswap.init.gradle | 69 ++
src/android_use/models.py | 10 +
src/android_use/runtime.py | 36 +
src/android_use/server.py | 17 +
tests/test_hotswap.py | 131 +++
tests/test_mcp.py | 6 +-
ui/package-lock.json | 4 +-
ui/package.json | 2 +-
ui/src/app.ts | 2 +-
uv.lock | 2 +-
50 files changed, 2881 insertions(+), 21 deletions(-)
create mode 100644 docs/hot-swap.md
create mode 100644 docs/releases/v0.8.0.md
create mode 100644 script/hotswap/.gitignore
create mode 100644 script/hotswap/app/AndroidManifest.xml
create mode 100644 script/hotswap/app/hotswap.json
create mode 100644 script/hotswap/app/res/layout/main.xml
create mode 100644 script/hotswap/app/res/values/colors.xml
create mode 100644 script/hotswap/app/res/values/strings.xml
create mode 100644 script/hotswap/app/src/lab/hotswap/Greeter.kt
create mode 100644 script/hotswap/app/src/lab/hotswap/MainActivity.java
create mode 100644 script/hotswap/app/src/lab/hotswap/Message.java
create mode 100644 script/hotswap/app/src/lab/hotswap/Util.kt
create mode 100644 script/hotswap/gradle-sample/.gitignore
create mode 100644 script/hotswap/gradle-sample/app/build.gradle.kts
create mode 100644 script/hotswap/gradle-sample/app/src/main/AndroidManifest.xml
create mode 100644 script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/JavaMessage.java
create mode 100644 script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Labels.kt
create mode 100644 script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/MainActivity.kt
create mode 100644 script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Screen.kt
create mode 100644 script/hotswap/gradle-sample/app/src/main/res/values/strings.xml
create mode 100644 script/hotswap/gradle-sample/build.gradle.kts
create mode 100644 script/hotswap/gradle-sample/gradle.properties
create mode 100644 script/hotswap/gradle-sample/settings.gradle.kts
create mode 100644 script/hotswap/hotswap.py
create mode 100755 script/hotswap/verify.py
create mode 100644 src/android_use/hotswap/__init__.py
create mode 100644 src/android_use/hotswap/agent/agent.cpp
create mode 100644 src/android_use/hotswap/daemon/HotswapDaemon.java
create mode 100755 src/android_use/hotswap/engine.py
create mode 100644 src/android_use/hotswap/helper/hotswap/agent/HotswapState.java
create mode 100644 src/android_use/hotswap/hotswap.init.gradle
create mode 100644 tests/test_hotswap.py
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 56a67b7..74a8824 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "android-use",
"displayName": "Android Use",
- "version": "0.7.1",
+ "version": "0.8.0",
"description": "通过 ADB 和 UiAutomator2 操作 Android,支持控件树、截图、中文输入、批处理和浏览器实时屏幕。",
"author": {
"name": "arcships",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 1620be0..b226bc0 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "android-use",
- "version": "0.7.1",
+ "version": "0.8.0",
"description": "通过 ADB 和 UiAutomator2 操作 Android,支持实时屏幕侧边栏、控件树、截图、中文输入和批处理。",
"skills": "./skills/",
"mcpServers": "./.mcp.json",
diff --git a/README.md b/README.md
index d756373..c845e32 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
English · 简体中文
- Use in Dim Agent → · Download v0.7.1 · Set up Jev · User guide · Report an issue
+ Use in Dim Agent → · Download v0.8.0 · Set up Jev · User guide · Report an issue
## Android tasks, inside Dim Agent
@@ -162,6 +162,10 @@ Enabling Jev sends the subgoal, visible UI text and supplied input values to Typ
| **Input with verification** | Unicode/emoji, replace/append and native text readback. A stable field can offer one focus → input → readback decision. |
| **Keep control clear** | User takeover for authentication, partial/uncertain action ledgers and no automatic replay. |
+## Edit code, see it on the phone · v0.8.0
+
+When the agent is developing an Android app from local source, `aua_hot_swap` pushes each edit into the running debuggable app in about a second. Classes are redefined in place and resources reloaded, so the app is not reinstalled or restarted: Compose keeps its remembered state, View screens keep scroll position and typed text, and the live screen shows the result. Gradle projects need no setup; anything that cannot be swapped falls back to a full build. [Hot swap →](docs/hot-swap.md)
+
## Other clients and manual setup
### Let your agent install it
@@ -327,7 +331,7 @@ Development comparisons include **18 source-level trials** and **12 live Agent /
## Project status
-**v0.7.1 · MIT · 487 Python tests · 25 browser tests.** Native install/upgrade/rollback acceptance was last run for v0.7.0 and passed on macOS ARM64/Intel (15 scenarios each), Linux x86_64 and Windows x86_64 (13 each). These package checks use no phone or model; earlier Android 16 physical-device and emulator acceptance remain separate. [Validation evidence →](docs/validation.md)
+**v0.8.0 · MIT · 497 Python tests · 25 browser tests.** Native install/upgrade/rollback acceptance was last run for v0.7.0 and passed on macOS ARM64/Intel (15 scenarios each), Linux x86_64 and Windows x86_64 (13 each). These package checks use no phone or model; earlier Android 16 physical-device and emulator acceptance remain separate. [Validation evidence →](docs/validation.md)
Multi-touch, arbitrary gesture paths, fine-grained text selection and custom-editor input fallbacks are not implemented. A matched UI condition proves that condition; the Agent must verify business outcomes. Control and preview run locally, and tool results are handled by your chosen client/model.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index f64066e..ee4629f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -8,7 +8,7 @@
English · 简体中文
- 在 Dim Agent 中使用 → · 下载 v0.7.1 · 配置 Jev · 使用指南 · 反馈问题
+ 在 Dim Agent 中使用 → · 下载 v0.8.0 · 配置 Jev · 使用指南 · 反馈问题
## 在 Dim Agent 中,直接完成 Android 任务
@@ -159,6 +159,10 @@ Dim Agent 会调用 Android 工具,通过 `aua_screen` 在桌面端右侧打
| **输入与核对** | 中文、emoji、替换/追加和原生回读;稳定输入框可一次决策完成聚焦→输入→回读。 |
| **清楚交接控制** | 认证由用户接管;保留 partial/uncertain 动作账本,不自动重放。 |
+## 改完代码,手机上立刻看到 · v0.8.0
+
+Agent 在本机开发 Android App 时,`aua_hot_swap` 约一秒内把改动送进运行中的可调试 App:类在进程内重定义,资源重新加载,不重装、不重启。Compose 保留 remember 状态,View 页面保留滚动位置和已输入的文字,实时屏幕里直接看到结果。Gradle 工程无需配置;不能热更新的改动自动退回完整构建。[说明](docs/hot-swap.md)
+
## 其他客户端与手动安装
### 让 Agent 自己安装
@@ -325,7 +329,7 @@ v0.5.0 通过 **277 项 Python 测试、17 项界面测试**。内置 OCR 目前
## 项目状态
-**v0.7.1 · MIT · 487 项 Python 测试 · 25 项浏览器测试。** 原生安装、升级和回滚验收最近一次针对 v0.7.0 执行,在 macOS ARM64/Intel 各通过 15 项,Linux x86_64/Windows x86_64 各通过 13 项。这些包验收不操作手机、不调用模型;历史 Android 16 真机与模拟器验收分开记录。[验证记录](docs/validation.md)。
+**v0.8.0 · MIT · 497 项 Python 测试 · 25 项浏览器测试。** 原生安装、升级和回滚验收最近一次针对 v0.7.0 执行,在 macOS ARM64/Intel 各通过 15 项,Linux x86_64/Windows x86_64 各通过 13 项。这些包验收不操作手机、不调用模型;历史 Android 16 真机与模拟器验收分开记录。[验证记录](docs/validation.md)。
多指手势、任意轨迹、精细文本选区及自绘编辑器输入兜底尚未实现。UI 条件满足仅证明该条件,Agent 仍需验收业务结果。控制和预览运行于本机,工具结果由你选择的客户端与模型处理。
diff --git a/docs/guide.md b/docs/guide.md
index e734f52..2447d10 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -144,12 +144,12 @@ Choose a release ZIP or a source checkout. If you already use `android-use-local
### Install the release ZIP
-Download `android-use-0.7.1-plugin.zip` and `SHA256SUMS` from [GitHub Release v0.7.1](https://github.com/arcships/android-use/releases/tag/v0.7.1). The ZIP includes the compiled UI, Python source/lockfile, stable installer, skills, bilingual docs and a local marketplace. Prepare uv, ADB, ffmpeg and the Codex CLI; dependencies are downloaded on first installation.
+Download `android-use-0.8.0-plugin.zip` and `SHA256SUMS` from [GitHub Release v0.8.0](https://github.com/arcships/android-use/releases/tag/v0.8.0). The ZIP includes the compiled UI, Python source/lockfile, stable installer, skills, bilingual docs and a local marketplace. Prepare uv, ADB, ffmpeg and the Codex CLI; dependencies are downloaded on first installation.
```bash
shasum -a 256 -c SHA256SUMS # Linux: sha256sum -c SHA256SUMS
-unzip android-use-0.7.1-plugin.zip -d android-use-v0.7.1
-cd android-use-v0.7.1
+unzip android-use-0.8.0-plugin.zip -d android-use-v0.8.0
+cd android-use-v0.8.0
uv run --no-project --python 3.13 python scripts/install.py doctor
uv run --no-project --python 3.13 python scripts/install.py install --source . --codex
```
@@ -414,6 +414,7 @@ uv run android-use tools
| `aua_scroll_until` | Bounded visible-target search without clicking. |
| `aua_apps / aua_launch_app / aua_press_button` | Package IDs, app launch, system buttons. |
| `aua_batch` | Bounded serial batches. |
+| `aua_hot_swap` | Apply source edits to the running debuggable app without reinstalling. [Hot swap →](hot-swap.md) |
| `aua_pause / aua_resume` | User authentication handoff. |
| `aua_screen` | Open/reuse live preview. |
| `aua_screen_frame / aua_screen_action` | App-only cached video/UI interfaces; not agent refresh tools. |
diff --git a/docs/guide.zh-CN.md b/docs/guide.zh-CN.md
index c054edb..e281f87 100644
--- a/docs/guide.zh-CN.md
+++ b/docs/guide.zh-CN.md
@@ -188,12 +188,12 @@ uv run android-use --serial SERIAL ready
### 安装发行包 ZIP
-从 [GitHub Release v0.7.1](https://github.com/arcships/android-use/releases/tag/v0.7.1) 下载 `android-use-0.7.1-plugin.zip` 和 `SHA256SUMS`。包内包含编译好的界面、源码与锁文件、固定入口安装器、技能和双语说明;先准备 uv、ADB、ffmpeg 和 Codex CLI,首次安装需下载 Python 依赖。
+从 [GitHub Release v0.8.0](https://github.com/arcships/android-use/releases/tag/v0.8.0) 下载 `android-use-0.8.0-plugin.zip` 和 `SHA256SUMS`。包内包含编译好的界面、源码与锁文件、固定入口安装器、技能和双语说明;先准备 uv、ADB、ffmpeg 和 Codex CLI,首次安装需下载 Python 依赖。
```bash
shasum -a 256 -c SHA256SUMS # Linux: sha256sum -c SHA256SUMS
-unzip android-use-0.7.1-plugin.zip -d android-use-v0.7.1
-cd android-use-v0.7.1
+unzip android-use-0.8.0-plugin.zip -d android-use-v0.8.0
+cd android-use-v0.8.0
uv run --no-project --python 3.13 python scripts/install.py doctor
uv run --no-project --python 3.13 python scripts/install.py install --source . --codex
```
@@ -405,6 +405,7 @@ MCP 工具以 `aua_` 为前缀:
| `aua_scroll_until` | 有界滚动查找可见目标,不自动点击 |
| `aua_apps / aua_launch_app / aua_press_button` | 包名查询、启动与系统按钮 |
| `aua_batch` | 有界批处理 |
+| `aua_hot_swap` | 把源码改动热更新到运行中的可调试 App,不重装、不重启。[说明](hot-swap.md) |
| `aua_pause / aua_resume` | 用户认证接管 |
| `aua_screen` | 打开 / 复用实时屏幕侧边栏 |
| `aua_screen_frame / aua_screen_action` | App 专属视频缓存和工具栏接口,供 UI 使用 |
diff --git a/docs/hot-swap.md b/docs/hot-swap.md
new file mode 100644
index 0000000..8533027
--- /dev/null
+++ b/docs/hot-swap.md
@@ -0,0 +1,50 @@
+# Hot swap: apply source edits to the running app
+
+`aua_hot_swap` is for developing an Android app whose source is on the same computer. After an edit, one call compiles what changed and redefines the classes inside the running process. The app is not reinstalled or restarted, so the screen the agent was looking at stays where it was. With the live screen open, the change shows up there about a second later.
+
+It uses the JDK and the Android SDK directly (javac, the Kotlin compiler, D8, aapt2, a small JVMTI agent). There is no Gradle plugin and nothing is added to the app's build.
+
+## Use
+
+```bash
+# What would happen, and is the host ready? Changes nothing.
+uv run android-use hot_swap '{"project":"/path/to/MyApp","action":"status"}'
+
+# After each edit. The first call does the full build, install and launch.
+uv run android-use hot_swap '{"project":"/path/to/MyApp","observe":"screenshot"}'
+```
+
+| Argument | Meaning |
+| --- | --- |
+| `project` | Absolute path of a Gradle root, of a module directory below it, or of a directory with a `hotswap.json`. |
+| `action` | `swap` (default), `build` (force the full build, install and launch) or `status`. |
+| `refresh` | `auto` (default), `recreate` (rebuild every activity) or `none` (leave the UI alone). |
+| `module`, `variant` | Gradle only; default `:app` and `Debug`. Remembered in `build/hotswap-config.json`; changing one forces a full build. |
+| `observe` | `none` (default), `tree`, `screenshot` or `both`: return the screen after the swap in the same call. |
+
+The result is one of:
+
+- `swapped`: classes and/or resources were replaced in place. `applied` says how many classes were redefined or added, whether Compose recomposed and whether an activity was rebuilt.
+- `installed`: a full build ran instead; `reason` says why (first call, the app was not running, a manifest or build file changed, a source file was deleted, the runtime refused the swap).
+- `unchanged`: nothing differs from what the process runs.
+
+A compile error returns `compile_failed` with the compiler output and leaves the app as it was. Fix the source and call again. `verified` is always `false`: the tool reports what was loaded, the agent checks the UI.
+
+## What is kept
+
+- Compose: the functions run again over their existing state. `remember` values and scroll positions stay. A structural change to a composable (calls added or removed) resets that function's state only.
+- Views: the activity is rebuilt with its saved state, plus scroll offsets, the text of input fields without an ID, and the keyboard. Instance fields of the activity are not kept.
+- The process: statics, singletons, the back stack, the login session.
+
+## Requirements and limits
+
+- The app must be debuggable (`android:debuggable="true"`, the default for debug builds) and the device must run Android 8 or later. Resource edits need Android 11 or later.
+- Host: a JDK on `PATH`, the Android SDK (`ANDROID_HOME`, or the default location) with build-tools and a platform. The NDK is needed once per device ABI to compile the agent; the result is cached under the Android Use state directory. macOS and Linux.
+- Gradle projects are detected from `settings.gradle(.kts)`. Gradle does the full builds; the swaps reuse the classpath and compiler flags it exports. Settings and caches go to the project's `build/` directory.
+- A plain project describes itself in `hotswap.json`; see `script/hotswap/app/hotswap.json`.
+- Not yet covered: annotation processors (kapt, KSP, Hilt, Room) that must rerun for an edit, edits spanning several Gradle modules, Kotlin 2.x. Those edits still work through the full-build fallback when the swap is refused, but an edit that needs regenerated code should use `action=build`.
+- Paused devices (authentication handoff) refuse `swap` and `build`.
+
+## Check it on a device
+
+`script/hotswap/verify.py [-s SERIAL] [--gradle]` builds the lab apps in `script/hotswap/`, edits their sources and confirms from the app's own log what the running process executes: method bodies, new methods, fields and classes, lambdas, Kotlin inline functions, resource values, colours and new resources, and that typed text, scroll offsets and Compose state survive.
diff --git a/docs/releases/v0.8.0.md b/docs/releases/v0.8.0.md
new file mode 100644
index 0000000..3bac4a1
--- /dev/null
+++ b/docs/releases/v0.8.0.md
@@ -0,0 +1,44 @@
+# Android Use v0.8.0
+
+**Edit code, see it on the phone: hot swap for apps under development.**
+
+A new tool, `aua_hot_swap`, pushes source edits into a running debuggable app without reinstalling or restarting it. An agent that is developing an Android app from local source can change a line, call the tool once, and read the updated screen from the same call. The 26 existing MCP tools, keyless host decisions, optional Jev and the Dim / Codex / Claude Code integrations are unchanged; the tool count is now 27.
+
+[English README](https://github.com/arcships/android-use/blob/v0.8.0/README.md) · [中文 README](https://github.com/arcships/android-use/blob/v0.8.0/README.zh-CN.md) · [Hot swap](https://github.com/arcships/android-use/blob/v0.8.0/docs/hot-swap.md) · [Native installation and rollback](https://github.com/arcships/android-use/blob/v0.8.0/docs/standalone.md)
+
+## What's new
+
+- **`aua_hot_swap(project=...)`.** Compiles the files that changed, finds the classes whose bytes differ from what the process runs, and has a small JVMTI agent redefine them in place. Edited resources are relinked with stable IDs and loaded into the process the same way. It uses the JDK and the Android SDK directly; nothing is added to the app's build.
+- **UI state is kept.** Compose functions run again over their existing state, so `remember` values and scroll positions stay. View screens are rebuilt with their saved state plus scroll offsets, typed text in fields without an ID, and the keyboard. The process, its statics and the back stack are untouched.
+- **Gradle projects need no setup.** Pass the Gradle root or a module directory. Gradle keeps doing the full builds and the swaps reuse the classpath and compiler flags it exports. Settings and caches go to the project's `build/` directory; project files are not modified. A plain project can describe itself in a `hotswap.json`.
+- **One call, explicit outcomes.** The result is `swapped`, `installed` or `unchanged`. Whatever cannot be swapped (first call, app not running, manifest or build file change, deleted source, a swap the runtime refuses) falls back to a full build, install and launch, with the reason. A compile error returns `compile_failed` with the compiler output and leaves the app as it was. `observe` returns the tree or a screenshot after the swap; `action=status` reports the host toolchain and what the next call would do, changing nothing.
+- **Authentication handoff applies.** A paused device refuses `swap` and `build`.
+
+## Requirements
+
+- A debuggable build (`android:debuggable="true"`, the default for debug variants) on Android 8 or later; resource edits need Android 11 or later.
+- On the computer: a JDK on `PATH` and the Android SDK with build-tools and a platform. The NDK is needed once per device ABI to compile the agent, which is then cached. macOS and Linux.
+- The standalone runtime includes the tool but not a JDK or the Android SDK.
+
+Installation and asset names are as in [v0.7.1](https://github.com/arcships/android-use/blob/v0.8.0/docs/releases/v0.7.1.md), with the new version number.
+
+## Validation and scope
+
+- **497 Python tests and 25 browser tests** are in the suite, with Ruff and the UI build. Ten are new and cover project detection, the tool's arguments, takeover, and failure reporting.
+- On one physical phone (Android 16, HyperOS 3, USB), through a real MCP stdio session: a one-line Java edit was swapped in 0.55 to 0.64 seconds and the returned tree showed the new text; the whole call took about 1.4 seconds. A full build of the plain lab app took 4.7 seconds.
+- The end-to-end suite `script/hotswap/verify.py` edits two lab apps and reads the app's own log to confirm what the process executes: method bodies, added methods, fields and classes, lambdas, Kotlin inline functions, resource values, colours, new resources, and kept text, scroll and Compose state. On the phone the plain app passed 22 of 22 checks. The Compose sample passed all of its checks in the preceding run; that run's single failure was the plain app's scroll check reading its baseline during a fling, which was then fixed in the test, and the Compose half was not repeated afterwards. An Android 15 emulator passed 31 of 31 before the code moved into the package.
+- Not exercised: automatic Gradle detection on a device (unit tests only; the sample uses a hand-written configuration), Windows hosts, the standalone runtime build with this tool, annotation processors that must rerun for an edit (kapt, KSP, Hilt, Room), edits spanning several Gradle modules, and Kotlin 2.x.
+- Known limits: a structural change to a composable resets that function's state; activity instance fields are lost when a View screen is rebuilt; the first Gradle build can take minutes and may exceed a client's tool timeout, in which case call again.
+- Native install, upgrade and rollback acceptance was last run for v0.7.0 and has not been repeated for this version before tagging; the release pipeline re-runs its package checks on the v0.8.0 artifacts.
+
+## 中文
+
+v0.8.0 新增热更新工具 `aua_hot_swap`:Agent 在本机开发 Android App 时,改完代码调用一次,改动约一秒内进入运行中的可调试 App,不重装、不重启。原有 26 个 MCP 工具及各客户端集成方式不变,工具数变为 27。
+
+- **进程内替换。** 只编译改动的文件,对比出字节有变化的类,由 JVMTI agent 在进程内重定义;资源以稳定 ID 重新链接后加载。直接使用 JDK 和 Android SDK,不向 App 的构建添加任何东西。
+- **保留界面状态。** Compose 保留 `remember` 状态和滚动位置;View 页面重建后保留滚动位置、已输入的文字和键盘;进程、静态变量和返回栈不变。
+- **Gradle 工程免配置。** 传 Gradle 根目录或模块目录即可,设置和缓存写在工程的 `build/` 下,不改工程文件。
+- **一次调用,结果明确。** `swapped`、`installed`(自动退回完整构建并说明原因)或 `unchanged`;编译错误返回 `compile_failed` 和编译器输出,App 保持原状;`observe` 在同一次调用返回更新后的界面;`action=status` 只读。
+- **要求:** debug 构建,Android 8 及以上(资源热更新需 Android 11);主机需 JDK 和 Android SDK,NDK 仅在首次为某个设备 ABI 编译 agent 时需要。支持 macOS 和 Linux。
+
+**验证范围:** 套件共 497 项 Python 测试、25 项浏览器测试。一台 Android 16 真机上经真实 MCP 会话验证,单行 Java 改动热更新耗时 0.55–0.64 秒;端到端套件普通 App 部分 22/22 通过,Compose 样例在此前一轮全部通过,测试修正后未重跑。Gradle 自动识别仅有单元测试,Windows 主机、独立运行包、kapt/KSP/Hilt/Room、多模块 Gradle、Kotlin 2.x 尚未验证。原生安装、升级和回滚验收最近一次针对 v0.7.0 执行。
diff --git a/pyproject.toml b/pyproject.toml
index 60708e6..dcd8327 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "android-use"
-version = "0.7.1"
+version = "0.8.0"
requires-python = ">=3.11"
description = "Local Android device control for coding agents over MCP and ADB"
license = "MIT"
diff --git a/script/hotswap/.gitignore b/script/hotswap/.gitignore
new file mode 100644
index 0000000..4397820
--- /dev/null
+++ b/script/hotswap/.gitignore
@@ -0,0 +1,3 @@
+build/
+.gradle/
+__pycache__/
diff --git a/script/hotswap/app/AndroidManifest.xml b/script/hotswap/app/AndroidManifest.xml
new file mode 100644
index 0000000..64d607b
--- /dev/null
+++ b/script/hotswap/app/AndroidManifest.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/script/hotswap/app/hotswap.json b/script/hotswap/app/hotswap.json
new file mode 100644
index 0000000..45d0520
--- /dev/null
+++ b/script/hotswap/app/hotswap.json
@@ -0,0 +1,8 @@
+{
+ "package": "lab.hotswap",
+ "activity": ".MainActivity",
+ "manifest": "AndroidManifest.xml",
+ "sources": ["src"],
+ "res": ["res"],
+ "min_api": 26
+}
diff --git a/script/hotswap/app/res/layout/main.xml b/script/hotswap/app/res/layout/main.xml
new file mode 100644
index 0000000..43ca98d
--- /dev/null
+++ b/script/hotswap/app/res/layout/main.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/script/hotswap/app/res/values/colors.xml b/script/hotswap/app/res/values/colors.xml
new file mode 100644
index 0000000..508dc15
--- /dev/null
+++ b/script/hotswap/app/res/values/colors.xml
@@ -0,0 +1,4 @@
+
+
+ #FF336699
+
diff --git a/script/hotswap/app/res/values/strings.xml b/script/hotswap/app/res/values/strings.xml
new file mode 100644
index 0000000..3886aaf
--- /dev/null
+++ b/script/hotswap/app/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ res 1
+
diff --git a/script/hotswap/app/src/lab/hotswap/Greeter.kt b/script/hotswap/app/src/lab/hotswap/Greeter.kt
new file mode 100644
index 0000000..b24b24a
--- /dev/null
+++ b/script/hotswap/app/src/lab/hotswap/Greeter.kt
@@ -0,0 +1,9 @@
+package lab.hotswap
+
+/** Kotlin target: a lambda plus a call into an inline function from another file. */
+object Greeter {
+ fun greet(): String {
+ val parts = listOf("kotlin", "A").map { it.uppercase() }
+ return twice { parts.joinToString(" ") }
+ }
+}
diff --git a/script/hotswap/app/src/lab/hotswap/MainActivity.java b/script/hotswap/app/src/lab/hotswap/MainActivity.java
new file mode 100644
index 0000000..7b3f8bd
--- /dev/null
+++ b/script/hotswap/app/src/lab/hotswap/MainActivity.java
@@ -0,0 +1,63 @@
+package lab.hotswap;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Process;
+import android.util.Log;
+import android.widget.EditText;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+public class MainActivity extends Activity {
+ // Process state: survives a hot swap (even with the activity rebuilt), not a restart.
+ static int ticks;
+ static int creations;
+ private TextView status;
+ private EditText input;
+ private ScrollView scroll;
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private final Runnable tick = new Runnable() {
+ @Override
+ public void run() {
+ ticks++;
+ String line = Message.text() + " | " + Greeter.INSTANCE.greet() + " | "
+ + getString(R.string.title);
+ status.setText(line.replace(" | ", "\n") + "\nticks=" + ticks + " creations=" + creations
+ + "\npid=" + Process.myPid());
+ // Machine-readable evidence for the experiment, including the view state a
+ // rebuilt activity has to bring back: typed text and scroll position.
+ Log.i("hotswap-app", line + " | ticks=" + ticks + " creations=" + creations
+ + " pid=" + Process.myPid() + " input=" + input.getText() + " scroll="
+ + scroll.getScrollY() + " color="
+ + Integer.toHexString(status.getCurrentTextColor()));
+ handler.postDelayed(this, 500);
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle state) {
+ super.onCreate(state);
+ creations++;
+ setContentView(R.layout.main);
+ status = findViewById(R.id.status);
+ input = findViewById(R.id.input);
+ scroll = findViewById(R.id.scroll);
+ if (state == null) {
+ input.requestFocus();
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ handler.post(tick);
+ }
+
+ @Override
+ protected void onPause() {
+ handler.removeCallbacks(tick);
+ super.onPause();
+ }
+}
diff --git a/script/hotswap/app/src/lab/hotswap/Message.java b/script/hotswap/app/src/lab/hotswap/Message.java
new file mode 100644
index 0000000..cb6f611
--- /dev/null
+++ b/script/hotswap/app/src/lab/hotswap/Message.java
@@ -0,0 +1,8 @@
+package lab.hotswap;
+
+/** Java target: edit text() and swap. */
+public class Message {
+ public static String text() {
+ return "java A";
+ }
+}
diff --git a/script/hotswap/app/src/lab/hotswap/Util.kt b/script/hotswap/app/src/lab/hotswap/Util.kt
new file mode 100644
index 0000000..62e319a
--- /dev/null
+++ b/script/hotswap/app/src/lab/hotswap/Util.kt
@@ -0,0 +1,4 @@
+package lab.hotswap
+
+/** Inline: its body is copied into every caller, so editing it must recompile them. */
+inline fun twice(block: () -> String): String = block() + " x1"
diff --git a/script/hotswap/gradle-sample/.gitignore b/script/hotswap/gradle-sample/.gitignore
new file mode 100644
index 0000000..ab2b020
--- /dev/null
+++ b/script/hotswap/gradle-sample/.gitignore
@@ -0,0 +1,4 @@
+build/
+.gradle/
+local.properties
+hotswap.json
diff --git a/script/hotswap/gradle-sample/app/build.gradle.kts b/script/hotswap/gradle-sample/app/build.gradle.kts
new file mode 100644
index 0000000..c03ad65
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/build.gradle.kts
@@ -0,0 +1,38 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "lab.hotswap.gradle"
+ compileSdk = 34
+ defaultConfig {
+ applicationId = "lab.hotswap.gradle"
+ minSdk = 26
+ targetSdk = 34
+ versionCode = 1
+ versionName = "1.0"
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+ kotlinOptions {
+ jvmTarget = "1.8"
+ }
+ buildFeatures {
+ compose = true
+ }
+ composeOptions {
+ kotlinCompilerExtensionVersion = "1.5.8"
+ }
+}
+
+dependencies {
+ implementation("androidx.core:core-ktx:1.12.0")
+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
+ implementation("androidx.activity:activity-compose:1.8.2")
+ implementation(platform("androidx.compose:compose-bom:2024.06.00"))
+ implementation("androidx.compose.ui:ui")
+ implementation("androidx.compose.material3:material3")
+}
diff --git a/script/hotswap/gradle-sample/app/src/main/AndroidManifest.xml b/script/hotswap/gradle-sample/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..1a018d9
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/AndroidManifest.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/JavaMessage.java b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/JavaMessage.java
new file mode 100644
index 0000000..d7de202
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/JavaMessage.java
@@ -0,0 +1,7 @@
+package lab.hotswap.gradle;
+
+public class JavaMessage {
+ public static String text() {
+ return "java A";
+ }
+}
diff --git a/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Labels.kt b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Labels.kt
new file mode 100644
index 0000000..4cf4401
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Labels.kt
@@ -0,0 +1,5 @@
+package lab.hotswap.gradle
+
+object Labels {
+ fun title(): String = "kotlin A"
+}
diff --git a/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/MainActivity.kt b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/MainActivity.kt
new file mode 100644
index 0000000..d7f1b5a
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/MainActivity.kt
@@ -0,0 +1,20 @@
+package lab.hotswap.gradle
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+
+/** Process state: survives a hot swap, not a process restart. */
+object Counter {
+ var ticks = 0
+ var creations = 0
+ var label = ""
+}
+
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ Counter.creations++
+ setContent { Screen() }
+ }
+}
diff --git a/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Screen.kt b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Screen.kt
new file mode 100644
index 0000000..a045ed5
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/java/lab/hotswap/gradle/Screen.kt
@@ -0,0 +1,59 @@
+package lab.hotswap.gradle
+
+import android.os.Process
+import android.util.Log
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import kotlinx.coroutines.delay
+
+@Composable
+fun Screen() {
+ var ticks by remember { mutableIntStateOf(0) }
+ // Plain remember, not saveable: lost if the composition is thrown away.
+ var local by remember { mutableIntStateOf(0) }
+ val scroll = rememberScrollState()
+ val context = LocalContext.current
+ // Recorded during composition, so the log proves which composable body ran.
+ Counter.label = "compose A"
+ LaunchedEffect(Unit) {
+ while (true) {
+ delay(500)
+ ticks = ++Counter.ticks
+ local++
+ Log.i(
+ "hotswap-app",
+ "${Counter.label} | ${Labels.title()} | ${JavaMessage.text()} | " +
+ "${context.getString(R.string.title)} | " +
+ "ticks=${Counter.ticks} creations=${Counter.creations} pid=${Process.myPid()} " +
+ "local=$local scroll=${scroll.value}",
+ )
+ }
+ }
+ Column(
+ modifier = Modifier.fillMaxSize().verticalScroll(scroll),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(Counter.label)
+ Text(Labels.title())
+ Text(JavaMessage.text())
+ Text(stringResource(R.string.title))
+ Text("ticks=$ticks local=$local")
+ Spacer(Modifier.height(2000.dp))
+ }
+}
diff --git a/script/hotswap/gradle-sample/app/src/main/res/values/strings.xml b/script/hotswap/gradle-sample/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..3886aaf
--- /dev/null
+++ b/script/hotswap/gradle-sample/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ res 1
+
diff --git a/script/hotswap/gradle-sample/build.gradle.kts b/script/hotswap/gradle-sample/build.gradle.kts
new file mode 100644
index 0000000..ab1a6ab
--- /dev/null
+++ b/script/hotswap/gradle-sample/build.gradle.kts
@@ -0,0 +1,4 @@
+plugins {
+ id("com.android.application") version "8.9.1" apply false
+ id("org.jetbrains.kotlin.android") version "1.9.22" apply false
+}
diff --git a/script/hotswap/gradle-sample/gradle.properties b/script/hotswap/gradle-sample/gradle.properties
new file mode 100644
index 0000000..c335529
--- /dev/null
+++ b/script/hotswap/gradle-sample/gradle.properties
@@ -0,0 +1,2 @@
+android.useAndroidX=true
+org.gradle.jvmargs=-Xmx2g
diff --git a/script/hotswap/gradle-sample/settings.gradle.kts b/script/hotswap/gradle-sample/settings.gradle.kts
new file mode 100644
index 0000000..d573dfa
--- /dev/null
+++ b/script/hotswap/gradle-sample/settings.gradle.kts
@@ -0,0 +1,15 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "HotswapGradleSample"
+include(":app")
diff --git a/script/hotswap/hotswap.py b/script/hotswap/hotswap.py
new file mode 100644
index 0000000..e1ad633
--- /dev/null
+++ b/script/hotswap/hotswap.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python3
+"""Command line for the hot-swap engine in src/android_use/hotswap, defaulting to the lab app."""
+
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parents[1] / "src"))
+
+from android_use.hotswap.engine import main # noqa: E402
+
+if __name__ == "__main__":
+ main(default_project=str(HERE / "app"))
diff --git a/script/hotswap/verify.py b/script/hotswap/verify.py
new file mode 100755
index 0000000..c57d78b
--- /dev/null
+++ b/script/hotswap/verify.py
@@ -0,0 +1,261 @@
+#!/usr/bin/env python3
+"""End-to-end check of hotswap.py against a connected device, using the lab app.
+
+ verify.py [-s SERIAL] [--gradle]
+
+Edits the lab sources, swaps, and reads the app's own log line to confirm what the
+running process executes. Sources are restored afterwards. --gradle also runs the
+Compose sample in gradle-sample/ (run `hotswap.py -p gradle-sample gradle-setup` first).
+"""
+
+import argparse
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+APP = HERE / "app"
+SRC = APP / "src/lab/hotswap"
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-s", "--serial")
+ parser.add_argument("--gradle", action="store_true")
+ args = parser.parse_args()
+ adb = ["adb", *(["-s", args.serial] if args.serial else [])]
+ tool = [sys.executable, str(HERE / "hotswap.py"), *(["-s", args.serial] if args.serial else [])]
+ results = []
+ target = {"package": "lab.hotswap", "project": []}
+
+ def device(*command):
+ try:
+ return subprocess.run([*adb, *command], capture_output=True, text=True, timeout=30).stdout
+ except subprocess.TimeoutExpired:
+ sys.exit("the device stopped answering (disconnected?)")
+
+ def sh(command):
+ return device("shell", command)
+
+ def hotswap(*extra):
+ started = time.time()
+ done = subprocess.run([*tool, *target["project"], *extra], capture_output=True, text=True)
+ return done.returncode, (done.stdout + done.stderr).strip(), time.time() - started
+
+ def line(wanted=None, timeout=12):
+ """Newest log line from the app, waiting until it contains `wanted`."""
+ deadline = time.time() + timeout
+ last = ""
+ while time.time() < deadline:
+ # Only this app's process: other lab apps log under the same tag.
+ pid = sh(f"pidof {target['package']}").strip() or "0"
+ out = device("logcat", "-d", f"--pid={pid}", "-s", "hotswap-app:I").strip().splitlines()
+ out = [text for text in out if "hotswap-app: " in text]
+ last = out[-1].split("hotswap-app: ", 1)[-1] if out else ""
+ if last and (wanted is None or wanted in last):
+ return last
+ time.sleep(0.3)
+ return last
+
+ def field(text, name):
+ found = re.search(rf"{name}=(\d+)", text)
+ return int(found.group(1)) if found else -1
+
+ def edit(name, old, new):
+ path = SRC / name
+ text = path.read_text()
+ assert old in text, f"{old!r} not in {name}"
+ path.write_text(text.replace(old, new))
+ time.sleep(0.02)
+
+ def check(title, ok, detail):
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'} {title}: {detail}")
+
+ backup = Path(tempfile.mkdtemp())
+ shutil.copytree(APP / "src", backup / "src")
+ shutil.copytree(APP / "res", backup / "res")
+ try:
+ code, out, took = hotswap("build")
+ start = line("java A")
+ check("full build", code == 0 and "java A" in start, f"{took:.1f}s")
+ pid = field(start, "pid")
+ # Give the views state worth keeping: typed text and a scroll offset.
+ sh("input text hello")
+ sh("input swipe 540 1000 540 500 300")
+ offset = None
+ for _ in range(8): # some phones let a fling coast for a while: wait for it to stop
+ time.sleep(1.5)
+ typed = line("input=hello")
+ if field(typed, "scroll") == offset:
+ break
+ offset = field(typed, "scroll")
+ check("typed text and scrolled", "input=hello" in typed and offset > 0,
+ f"input=hello scroll={offset}")
+
+ def swap_case(title, wanted, verdict="", same_pid=True, extra=()):
+ code, out, took = hotswap(*extra, "swap")
+ seen = line(wanted)
+ ok = code == 0 and wanted in seen and verdict in out
+ ok = ok and (field(seen, "pid") == pid) == same_pid
+ check(title, ok, f"{took:.2f}s | {out.splitlines()[-1] if out else ''} | {seen}")
+ return seen
+
+ edit("Message.java", '"java A"', '"java B"')
+ swap_case("java method body", "java B", "structural=0")
+
+ edit("Greeter.kt", '"A")', '"B")')
+ swap_case("kotlin method body", "KOTLIN B")
+
+ edit("Util.kt", '" x1"', '" x2"')
+ swap_case("kotlin inline function in another file", "x2")
+
+ edit("Message.java", 'return "java B";',
+ 'return "java C" + extra();\n }\n\n static int calls;\n\n'
+ ' static String extra() {\n return "+" + (++calls > 0 ? "m" : "");')
+ swap_case("added method and field", "java C+m", "structural=1")
+
+ (SRC / "Extra.java").write_text(
+ 'package lab.hotswap;\n\npublic class Extra {\n'
+ ' public static String value() {\n return "new1";\n }\n}\n')
+ edit("Message.java", 'return "java C" + extra();', 'return "java D" + Extra.value();')
+ swap_case("brand-new class", "java Dnew1", "added=1")
+
+ edit("Extra.java", '"new1"', '"new2"')
+ swap_case("edit the class added by a swap", "java Dnew2", "added=0")
+
+ edit("Message.java", 'return "java D" + Extra.value();',
+ 'java.util.function.Supplier s = () -> "lam1";\n'
+ ' return "java E" + s.get();')
+ swap_case("java lambda introduced", "java Elam1")
+ edit("Message.java", '"lam1"', '"lam2"')
+ swap_case("java lambda body edited", "java Elam2")
+
+ before = line()
+ edit("Message.java", '"java E"', '"java F"')
+ after = swap_case("--refresh none leaves the activity alone", "java F",
+ extra=("--refresh", "none"))
+ check(" activity not rebuilt", field(after, "creations") == field(before, "creations"),
+ f"creations {field(before, 'creations')} -> {field(after, 'creations')}")
+ check(" process state kept across all swaps",
+ field(after, "ticks") > field(start, "ticks") and field(after, "pid") == pid,
+ f"ticks {field(start, 'ticks')} -> {field(after, 'ticks')}, pid {pid}")
+
+ edit("Message.java", '"java F"', '"java G')
+ code, out, took = hotswap("swap")
+ seen = line()
+ check("compile error is reported, app untouched",
+ code != 0 and "java F" in seen and "Message.java" in out,
+ f"exit {code} | {out.splitlines()[0][:40]} | {seen}")
+ edit("Message.java", '"java G', '"java G"')
+ swap_case("recovers after the error is fixed", "java G")
+
+ colors = APP / "res/values/colors.xml"
+ colors.write_text(colors.read_text().replace("#FF336699", "#FFCC0000"))
+ styled = swap_case("style edit (a colour) is applied", "color=ffcc0000", "resources=1")
+ time.sleep(2.5) # past the moment the rebuilt window is still settling
+ styled = line("color=ffcc0000")
+ check(" view state kept: typed text and scroll position",
+ "input=hello" in styled and field(styled, "scroll") == offset,
+ f"after 10 swaps: input=hello scroll {offset} -> {field(styled, 'scroll')}")
+
+ strings = APP / "res/values/strings.xml"
+ strings.write_text(strings.read_text().replace("res 1", "res 2"))
+ swap_case("resource value edited, no restart", "res 2", "resources=1")
+
+ # A name sorting before "title" would take title's ID unless IDs are kept stable.
+ strings.write_text(strings.read_text().replace(
+ "", '\n x').replace(
+ "res 2", "res 3"))
+ swap_case("resource added before an existing one", "res 3", "resources=1")
+
+ package = "lab.hotswap"
+ sh(f"am force-stop {package}")
+ sh(f"am start -n {package}/.MainActivity")
+ stale = line("java A")
+ check("restarted process runs the stale APK", "java A" in stale and "res 1" in stale, stale)
+ pid = field(stale, "pid")
+ swap_case("next swap re-applies code and resources", "java Glam2 | KOTLIN B x2 | res 3")
+
+ edit("Message.java", "public class Message {", "public class Message implements Runnable {\n"
+ " public void run() {\n }\n")
+ edit("Message.java", '"java G"', '"java H"')
+ swap_case("hierarchy change falls back to reinstall", "java Hlam2 | KOTLIN B x2 | res 3",
+ "swap refused", same_pid=False)
+ finally:
+ for name in ("src", "res"):
+ shutil.rmtree(APP / name)
+ shutil.copytree(backup / name, APP / name)
+ shutil.rmtree(backup)
+ hotswap("build")
+ if args.gradle:
+ sample = HERE / "gradle-sample"
+ code_dir = sample / "app/src/main/java/lab/hotswap/gradle"
+ strings = sample / "app/src/main/res/values/strings.xml"
+ target.update(package="lab.hotswap.gradle", project=["-p", str(sample)])
+ saved = {p: p.read_text() for p in [*code_dir.iterdir(), strings]}
+
+ def change(path, old, new):
+ assert old in path.read_text(), old
+ path.write_text(path.read_text().replace(old, new))
+
+ def gradle_case(title, wanted, verdict=""):
+ code, out, took = hotswap("swap")
+ seen = line(wanted)
+ ok = code == 0 and wanted in seen and verdict in out and field(seen, "pid") == pid
+ check("gradle: " + title, ok, f"{took:.2f}s | {out.splitlines()[-1] if out else ''}")
+
+ try:
+ code, out, took = hotswap("build")
+ start = line("compose A | kotlin A | java A | res 1")
+ check("gradle: full build of the Compose sample", code == 0 and "res 1" in start,
+ f"{took:.1f}s")
+ pid = field(start, "pid")
+ sh("input swipe 540 1000 540 500 300")
+ time.sleep(1.5)
+ before = line()
+ change(code_dir / "JavaMessage.java", '"java A"', '"java B"')
+ gradle_case("java method body", "java B")
+ change(code_dir / "Labels.kt", '"kotlin A"', '"kotlin B"')
+ gradle_case("kotlin method body", "kotlin B")
+ change(code_dir / "Screen.kt", '"compose A"', '"compose B"')
+ gradle_case("composable body", "compose B")
+ change(strings, "res 1", "res 2")
+ gradle_case("resource value edited, no restart", "res 2", "resources=1")
+ change(strings, "", '\n x')
+ change(strings, "res 2", "res 3")
+ gradle_case("resource added before an existing one", "res 3", "resources=1")
+ after = line("res 3")
+ # The remembered counter ticks in step with a static one: any reset of the
+ # composition would break the pairing.
+ kept = (field(after, "creations") == 1 and field(before, "scroll") > 0
+ and field(after, "scroll") == field(before, "scroll")
+ and field(after, "local") - field(before, "local")
+ == field(after, "ticks") - field(before, "ticks"))
+ check("gradle: Compose state kept, activity never rebuilt", kept,
+ f"creations {field(after, 'creations')}, remembered counter "
+ f"{field(before, 'local')} -> {field(after, 'local')} over "
+ f"{field(after, 'ticks') - field(before, 'ticks')} ticks, "
+ f"scroll {field(before, 'scroll')} -> {field(after, 'scroll')}")
+ change(code_dir / "Screen.kt", ' Spacer(Modifier.height(2000.dp))\n',
+ ' Badge()\n Spacer(Modifier.height(2000.dp))\n')
+ (code_dir / "Screen.kt").write_text(
+ (code_dir / "Screen.kt").read_text()
+ + '\n@Composable\nfun Badge() {\n Column { Text("badge") }\n}\n')
+ change(code_dir / "Labels.kt", '"kotlin B"', '"kotlin C"')
+ gradle_case("new composable function", "kotlin C", "structural=1")
+ check("gradle: still the same activity", field(line(), "creations") == 1, "creations 1")
+ finally:
+ for path, text in saved.items():
+ path.write_text(text)
+ hotswap("build")
+ print(f"\n{sum(results)}/{len(results)} passed")
+ sys.exit(0 if all(results) else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/android-use/SKILL.md b/skills/android-use/SKILL.md
index a058730..1b1eb35 100644
--- a/skills/android-use/SKILL.md
+++ b/skills/android-use/SKILL.md
@@ -39,6 +39,8 @@ batch 中动作等待超时停止为 postcondition_timeout,scroll_until 未找
密码、PIN、验证码和生物认证由用户本人完成。先 aua_pause,再用宿主提问工具等待用户明确完成(首个选项「已完成继续」);接管期间不读取、不截图、不操作。用户完成后 aua_resume,再重新观察;真正锁屏还需要 READY。pause 状态在该设备的 CLI 和 MCP 之间共享,不影响用户直接操作手机。
+开发本机源码的 Android App 时,每次改完代码或资源调用 `aua_hot_swap(project=<工程绝对路径>)`,不要重新构建安装:改动约一秒内进入运行中的可调试 App,不重启,页面、滚动位置、输入内容和 Compose 状态保留。project 可以是 Gradle 根目录或模块目录(自动识别,无需配置)。首次调用、App 未运行或改了 Manifest/构建文件时自动完整构建并安装(result=installed,带 reason,可能需要几分钟);result=swapped 为已热更新,unchanged 为无改动。`compile_failed` 附带编译器输出,App 保持原状,改正源码后再调用。传 observe=tree/screenshot 在同一次调用里拿到更新后的界面;verified=false,界面效果由你验收。先用 action=status 可查看主机工具链和下次调用会做什么。仅适用于 debug 构建。
+
aua_apps 查询已安装的第三方 **包名**,不支持按 App 显示名查找。不要连续猜包名。aua_launch_app 使用已核实的 package,不强停或清除 App 数据。发送、下单等外部变更需用户授权,并核对目标与内容,执行一次后验收结果。
独立运行包的固定入口也支持 `cli <操作> ''`,使用安装返回的启动命令,将最后的 `auto-serve` 改为 `cli` 并追加操作及参数,无需 uv。回滚使用固定入口的 `rollback`;后台更新只影响后续 MCP 会话,不重启当前任务。
diff --git a/src/android_use/__init__.py b/src/android_use/__init__.py
index 9603107..201eb23 100644
--- a/src/android_use/__init__.py
+++ b/src/android_use/__init__.py
@@ -1,3 +1,3 @@
"""Android Use: an ADB/UiAutomator bridge for agents."""
-__version__ = "0.7.1"
+__version__ = "0.8.0"
diff --git a/src/android_use/assets/phone-screen.html b/src/android_use/assets/phone-screen.html
index 56372b2..4cfb4f4 100644
--- a/src/android_use/assets/phone-screen.html
+++ b/src/android_use/assets/phone-screen.html
@@ -242,5 +242,5 @@
- omitted: host decides border`)}),X4=d.object({method:d.literal("ui/request-display-mode"),params:d.object({mode:qi.describe("The display mode being requested.")})}),FS=d.object({mode:qi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),qS=d.union([d.literal("model"),d.literal("app")]).describe("Tool visibility scope - who can access the tool."),Y4=d.object({resourceUri:d.string().optional(),visibility:d.array(qS).optional().describe(`Who can access this tool. Default: ["model", "app"]
- "model": Tool visible to and callable by the agent
- "app": Tool callable by the app from this server only`),csp:d.never().optional(),permissions:d.never().optional()}),eN=d.object({mimeTypes:d.array(d.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),tN=d.object({method:d.literal("ui/download-file"),params:d.object({contents:d.array(d.union([mf,pf])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),rN=d.object({method:d.literal("ui/message"),params:d.object({role:d.literal("user").describe('Message role, currently only "user" is supported.'),content:d.array(sn).describe("Message content blocks (text, image, etc.).")})}),nN=d.object({method:d.literal("ui/notifications/sandbox-resource-ready"),params:d.object({html:d.string().describe("HTML content to load into the inner iframe."),sandbox:d.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:xf.optional().describe("CSP configuration from resource metadata."),permissions:kf.optional().describe("Sandbox permissions from resource metadata.")})}),JS=d.object({method:d.literal("ui/notifications/tool-result"),params:cn.describe("Standard MCP tool execution result.")}),ty=d.object({toolInfo:d.object({id:nn.optional().describe("JSON-RPC id of the tools/call request."),tool:oc.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:jS.optional().describe("Current color theme preference."),styles:ZS.optional().describe("Style configuration for theming the app."),displayMode:qi.optional().describe("How the UI is currently displayed."),availableDisplayModes:d.array(qi).optional().describe("Display modes the host supports."),containerDimensions:d.union([d.object({height:d.number().describe("Fixed container height in pixels.")}),d.object({maxHeight:d.union([d.number(),d.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(d.union([d.object({width:d.number().describe("Fixed container width in pixels.")}),d.object({maxWidth:d.union([d.number(),d.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
-container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:d.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:d.string().optional().describe("User's timezone in IANA format."),userAgent:d.string().optional().describe("Host application identifier."),platform:d.union([d.literal("web"),d.literal("desktop"),d.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:d.object({touch:d.boolean().optional().describe("Whether the device supports touch input."),hover:d.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:d.object({top:d.number().describe("Top safe area inset in pixels."),right:d.number().describe("Right safe area inset in pixels."),bottom:d.number().describe("Bottom safe area inset in pixels."),left:d.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),BS=d.object({method:d.literal("ui/notifications/host-context-changed"),params:ty.describe("Partial context update containing only changed fields.")}),iN=d.object({method:d.literal("ui/update-model-context"),params:d.object({content:d.array(sn).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:d.record(d.string(),d.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),oN=d.object({method:d.literal("ui/initialize"),params:d.object({appInfo:Ci.describe("App identification (name and version)."),appCapabilities:VS.describe("Features and capabilities this app provides."),protocolVersion:d.string().describe("Protocol version this app supports.")})}),HS=d.object({protocolVersion:d.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ci.describe("Host application identification and version."),hostCapabilities:MS.describe("Features and capabilities provided by the host."),hostContext:ty.describe("Rich context about the host environment.")}).passthrough(),KS={target:"draft-2020-12"};async function Y$(e,r){let i=e["~standard"];if(i.jsonSchema)return i.jsonSchema[r](KS);if(i.vendor==="zod"){let{z:o}=await Promise.resolve().then(()=>(Ni(),Xp));return o.toJSONSchema(e,{io:r})}throw Error(`Schema (vendor: ${i.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function ey(e,r,i=""){let o=await e["~standard"].validate(r);if(o.issues){let t=o.issues.map(n=>{let a=n.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${n.message}`:n.message}).join("; ");throw Error(i+t)}return o.value}var sc=class e extends bf{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(r){if(this._initializedSent)return;let i=`[ext-apps] App.${r}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(i);console.warn(`${i}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:ES,toolresult:JS,toolcancelled:CS,hostcontextchanged:BS};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(r){if(!e.ONE_SHOT_EVENTS.has(r)||this._everHadListener.has(r)||(this._everHadListener.add(r),!this._initializedSent))return;let i=`[ext-apps] "${String(r)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(i);console.warn(i)}setEventHandler(r,i){i&&this._assertHandlerTiming(r),super.setEventHandler(r,i)}addEventListener(r,i){this._assertHandlerTiming(r),super.addEventListener(r,i)}onEventDispatch(r,i){r==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i})}constructor(r,i={},o={autoResize:!0}){super(o),this._appInfo=r,this._capabilities=i,this.options=o,o.allowUnsafeEval||d.config({jitless:!0}),this.setRequestHandler(on,t=>(console.log("Received ping:",t.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(r){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Q$(this._capabilities,r)}registerTool(r,i,o){if(this._registeredTools[r])throw Error(`Tool ${r} is already registered`);let t=this,n=()=>{t._initializedSent&&t._capabilities.tools?.listChanged&&t.sendToolListChanged()},a=i.inputSchema!==void 0,s={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){t._registeredTools[r]===s&&(delete t._registeredTools[r],n())},handler:async(c,u)=>{if(!s.enabled)throw Error(`Tool ${r} is disabled`);let l;if(a){let m=s.inputSchema,p=m?await ey(m,c??{},`Invalid input for tool ${r}: `):c??{};l=await o(p,u)}else l=await o(u);return s.outputSchema&&!l.isError&&(l.structuredContent=await ey(s.outputSchema,l.structuredContent,`Invalid output for tool ${r}: `)),l}};return this._registeredTools[r]=s,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),n(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(r,i)=>{let o=this._registeredTools[r.name];if(!o)throw Error(`Tool ${r.name} not found`);return o.handler(r.arguments,i)},this.onlisttools=async(r,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,t])=>t.enabled).map(async([o,t])=>{let n={name:o,title:t.title,description:t.description,inputSchema:t.inputSchema?await Y$(t.inputSchema,"input"):{type:"object",properties:{}}};return t.outputSchema&&(n.outputSchema=await Y$(t.outputSchema,"output")),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(r={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:r})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(r){this.setEventHandler("toolinput",r)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(r){this.setEventHandler("toolinputpartial",r)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(r){this.setEventHandler("toolresult",r)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(r){this.setEventHandler("toolcancelled",r)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(r){this.setEventHandler("hostcontextchanged",r)}_onteardown;get onteardown(){return this._onteardown}set onteardown(r){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,r),this._onteardown=r,this.replaceRequestHandler(LS,(i,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i.params,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(r){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,r),this._oncalltool=r,this.replaceRequestHandler(gf,(i,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(r){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,r),this._onlisttools=r,this.replaceRequestHandler(ff,(i,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,o)})}assertCapabilityForMethod(r){switch(r){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${r})`);break}}assertRequestHandlerCapability(r){switch(r){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${r})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${r} registered`)}}assertNotificationCapability(r){}assertTaskCapability(r){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(r){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(r,i){if(this._assertInitialized("callServerTool"),typeof r=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${r}"). Did you mean: callServerTool({ name: "${r}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:r},cn,{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(r,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:r},cf,i)}async listServerResources(r,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:r},af,i)}async createSamplingMessage(r,i){this._assertInitialized("createSamplingMessage");let o=r.tools?vf:hf;return await this.request({method:"sampling/createMessage",params:r},o,i)}sendMessage(r,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:r},AS,i)}sendLog(r){return this.notification({method:"notifications/message",params:r})}updateModelContext(r,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:r},Ws,i)}openLink(r,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:r},OS,i)}sendOpenLink=this.openLink;downloadFile(r,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:r},NS,i)}requestTeardown(r={}){return this.notification({method:"ui/notifications/request-teardown",params:r})}requestDisplayMode(r,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:r},FS,i)}sendSizeChanged(r){return this.notification({method:"ui/notifications/size-changed",params:r})}setupSizeChangedNotifications(){let r=!1,i=0,o=0,t=()=>{r||(r=!0,requestAnimationFrame(()=>{r=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let u=Math.ceil(window.innerWidth);(u!==i||c!==o)&&(i=u,o=c,this.sendSizeChanged({width:u,height:c}))}))};t();let n=new ResizeObserver(t);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(r=new _f(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(r);try{let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:IS}},HS,i);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};var Xe=document.querySelector("#app"),fr=document.querySelector("#frame"),Qi=document.querySelector("#device"),ry=document.querySelector("#overlay"),WS=document.querySelector("#overlay-text"),GS=document.querySelector("#overlay-detail"),QS=document.querySelector("#status-text"),Ji=document.querySelector("#notice"),Ki=document.querySelector("#pointer"),Bi=document.querySelector("#resume"),hr=Object.fromEntries(["refresh","back","home","copy"].map(e=>[e,document.getElementById(e)])),iy=window.__ANDROID_USE_STANDALONE__===!0,gr=iy?void 0:new sc({name:"Android Use Screen",version:"0.7.1"},{availableDisplayModes:["fullscreen"]},{autoResize:!1}),Ne,ln=0,uc="",Sf=!1,zf=!1,lt=!1,wf=!1,dt,Wi="",Le=0,oy=!1,lc=!1,XS=5e3,un,Ge,Gi,dc=document.querySelector("#settings"),mc=document.querySelector("#jev-settings"),Ye=document.querySelector("#jev-key"),jt=document.querySelector("#jev-message"),If=document.querySelector("#jev-enable"),pc=document.querySelector("#jev-test"),Xi=document.querySelector("#jev-disable"),Yi=document.querySelector("#jev-clear"),Tt=document.querySelector("#jev-images"),Qe,Be=!1,YS={connecting:"\u8FDE\u63A5\u4E2D",live:"Live",buffering:"\u7F13\u51B2\u4E2D",paused:"\u5DF2\u6682\u505C",offline:"\u672A\u8FDE\u63A5",unsupported:"\u4E0D\u652F\u6301\u9884\u89C8"};function Dt(e,r=""){Gi&&clearTimeout(Gi),Ji.textContent=e,Ji.title=r,Gi=setTimeout(()=>{Ji.textContent="",Ji.title=""},3e3)}function Te(e,r,i){Xe.dataset.state=e,QS.textContent=YS[e],ry.hidden=e==="live"||e==="buffering",ry.hidden||(WS.textContent=r??"\u6B63\u5728\u8FDE\u63A5\u624B\u673A\u2026",GS.textContent=i??"\u5B9E\u65F6\u89C6\u9891\u5C06\u5728\u8FD9\u91CC\u663E\u793A"),Bi.hidden=!(e==="paused"&&Ne?.pause_reason==="authentication");for(let o of["home","back","copy"])hr[o].disabled=lt||e!=="live";hr.refresh.disabled=lt}async function mn(e,r={}){if(iy){let o=await fetch(`api/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(e==="action"?2e4:8e3)});if(!o.ok){if(e==="action"&&String(r.action).startsWith("jev_"))try{let t=await o.json();if(t?.error?.code)return t}catch{}throw new Error("preview_unreachable")}return o.json()}return(await gr.callServerTool({name:e==="frame"?"aua_screen_frame":"aua_screen_action",arguments:e==="frame"?r:e==="refresh"?{action:"refresh"}:r},{timeout:e==="action"?2e4:8e3})).structuredContent}function eo(e){Qe=e,dc.dataset.enabled=String(e.enabled),document.querySelector("#jev-state").textContent=e.demo?"\u6587\u6863\u793A\u4F8B\uFF0C\u8BF7\u5728\u5B9E\u9645\u624B\u673A\u5C4F\u5E55\u4E2D\u914D\u7F6E":e.enabled?"Jev \u5DF2\u542F\u7528":e.configured?"\u5DF2\u914D\u7F6E Key\uFF0CJev \u672A\u542F\u7528":"\u5C1A\u672A\u914D\u7F6E\uFF0C\u586B\u5165 Key \u5373\u53EF\u5F00\u59CB",document.querySelector("#jev-provider").textContent=`${e.model} \xB7 ${e.base_url}`,Ye.placeholder=e.configured?"\u5DF2\u6709 Key\uFF0C\u7559\u7A7A\u7EE7\u7EED\u4F7F\u7528":"\u7C98\u8D34\u4F60\u7684 API Key",Ye.disabled=!!e.demo||Be,If.disabled=!!e.demo||Be||!e.configured&&!Ye.value.trim(),pc.disabled=!e.configured||!!e.demo||Be,Xi.hidden=!e.enabled,Yi.hidden=!e.has_saved_key,Xi.disabled=Be,Yi.disabled=Be,Tt.checked=!!e.images_enabled,Tt.disabled=!!e.demo||Be}function ew(e){return e?.error?.code==="jev_http_error"?e.error.status===401?"Key \u65E0\u6548\u6216\u5DF2\u5931\u6548":e.error.status===429?"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"\u670D\u52A1\u62D2\u7EDD\u8BF7\u6C42\uFF0C\u8BF7\u68C0\u67E5 Key \u6743\u9650\u548C\u8D26\u6237\u72B6\u6001":{jev_configuration:"\u8BF7\u586B\u5199\u6709\u6548\u7684 TypeSafe API Key",jev_transport_error:"\u65E0\u6CD5\u8FDE\u63A5 TypeSafe\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5",jev_settings_unavailable:"\u65E0\u6CD5\u8BFB\u53D6\u6216\u4FDD\u5B58\u672C\u673A\u8BBE\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650",jev_validation_failed:"\u8FDE\u63A5\u6D4B\u8BD5\u672A\u901A\u8FC7\uFF0C\u8BBE\u7F6E\u5C1A\u672A\u66F4\u6539",device_busy:"\u53E6\u4E00\u9879\u8BBE\u7F6E\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}[e?.error?.code||""]||"\u8BBE\u7F6E\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u540E\u91CD\u8BD5"}async function ro(e){if(!(Be||!Qe||Qe.demo)){Be=!0,jt.textContent=e==="jev_save"?"\u6B63\u5728\u9A8C\u8BC1 Key\u2026":e==="jev_test"?"\u6B63\u5728\u6D4B\u8BD5\u8FDE\u63A5\u2026":"\u6B63\u5728\u66F4\u65B0\u8BBE\u7F6E\u2026",jt.dataset.error="false",Ye.disabled=!0,dc.disabled=!0,document.querySelector("#settings-close").disabled=!0;for(let r of[If,pc,Xi,Yi,Tt])r.disabled=!0;try{let r=await mn("action",{action:e,...e==="jev_save"?{api_key:Ye.value}:{}});if(!r?.ok){jt.textContent=ew(r),jt.dataset.error="true";return}e.startsWith("jev_images")||(Ye.value=""),eo(r),jt.textContent=r.tested?`${e==="jev_save"?"\u5DF2\u4FDD\u5B58\u5E76\u542F\u7528":"\u8FDE\u63A5\u6B63\u5E38"} \xB7 ${r.latency_ms} ms`:e==="jev_images_on"?"\u5DF2\u5141\u8BB8\u53D1\u9001\u622A\u56FE":e==="jev_images_off"?"\u5DF2\u5173\u95ED\u622A\u56FE\u53D1\u9001":e==="jev_clear"?"\u672C\u673A Key \u5DF2\u79FB\u9664\uFF0CJev \u5DF2\u505C\u7528":"Jev \u5DF2\u505C\u7528"}catch{jt.textContent="\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A\u8BBE\u7F6E\u670D\u52A1\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55",jt.dataset.error="true"}finally{Be=!1,dc.disabled=!1,document.querySelector("#settings-close").disabled=!1,Qe&&eo(Qe)}}}dc.onclick=()=>{Be||(Qe=void 0,Ye.value="",Ye.disabled=!0,jt.textContent="",mc.showModal(),If.disabled=!0,pc.disabled=!0,Xi.hidden=!0,Yi.hidden=!0,Tt.disabled=!0,Tt.checked=!1,mn("action",{action:"jev_status"}).then(e=>{if(!e?.ok)throw new Error("settings_unavailable");eo(e)}).catch(()=>{document.querySelector("#jev-state").textContent="\u65E0\u6CD5\u8BFB\u53D6\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55"}))};document.querySelector("#jev-form").onsubmit=e=>{e.preventDefault(),ro("jev_save")};Tt.onchange=()=>{let e=Tt.checked;Qe&&(Tt.checked=!!Qe.images_enabled),ro(e?"jev_images_on":"jev_images_off")};pc.onclick=()=>void ro("jev_test");Xi.onclick=()=>void ro("jev_disable");Yi.onclick=()=>void ro("jev_clear");document.querySelector("#settings-close").onclick=()=>mc.close();mc.addEventListener("close",()=>{Ye.value=""});mc.addEventListener("cancel",e=>{Be&&e.preventDefault()});Ye.oninput=()=>{Qe&&eo(Qe)};function pr(){Le++,fr.removeAttribute("src"),Wi="",ln=0}function Hi(e,r=!1,i=!1){un??=performance.now();let o=performance.now()-un>=XS;if(!o&&r&&Wi){Te("buffering");return}o&&pr(),Te(o?"offline":"connecting",o?i?"\u672C\u5730\u9884\u89C8\u670D\u52A1\u672A\u54CD\u5E94":"\u89C6\u9891\u6682\u4E0D\u53EF\u7528":e,o?i?"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u5931\u8D25\uFF0C\u8BF7\u8BA9 Agent \u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55":"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u4E5F\u53EF\u70B9\u51FB\u300C\u91CD\u8FDE\u300D":"\u6B63\u5728\u81EA\u52A8\u6062\u590D\uFF0C\u65E0\u9700\u624B\u52A8\u91CD\u8FDE")}function ny(){let e=Ne?.interaction_ready===!1?"buffering":"live";Te(e),e==="live"&&lc&&(lc=!1,Dt("\u5DF2\u91CD\u65B0\u8FDE\u63A5"))}function ay(e){if(!e?.ok)throw new Error("preview_unreachable");if(Ne=e,document.querySelector("#model").textContent=e.device?.model||"Android",uc!==e.stream_id&&(uc=e.stream_id,pr(),Ge=void 0),e.paused){pr(),Ge=void 0,un=void 0,Te("paused","\u8BF7\u5728\u624B\u673A\u4E0A\u63A5\u7BA1\u64CD\u4F5C",e.pause_reason==="device_locked"?"\u624B\u673A\u5DF2\u9501\u5B9A\uFF0C\u89E3\u9501\u540E\u81EA\u52A8\u6062\u590D":"\u8BA4\u8BC1\u5B8C\u6210\u540E\u70B9\u51FB\u4E0B\u65B9\u6309\u94AE\uFF0C\u6216\u7531 agent \u6062\u590D\u9884\u89C8");return}if(!e.connected){pr(),Te("offline","\u624B\u673A\u672A\u8FDE\u63A5","\u8BF7\u68C0\u67E5 USB \u6216\u65E0\u7EBF ADB \u8FDE\u63A5");return}if(e.error==="video_stream_ended"){Ge===void 0&&(Ge=e.seq,Le++),Hi("\u6B63\u5728\u6062\u590D\u89C6\u9891\u2026",!0);return}if(e.error==="preview_unsupported_device"){pr(),Te("unsupported","\u6B64\u624B\u673A\u4E0D\u652F\u6301\u5B9E\u65F6\u9884\u89C8","\u7CFB\u7EDF\u672A\u63D0\u4F9B screenrecord\uFF1B\u622A\u56FE\u3001\u8BFB\u5C4F\u548C\u64CD\u4F5C\u4ECD\u53EF\u6B63\u5E38\u4F7F\u7528");return}if(e.error){pr(),Te("offline","\u89C6\u9891\u8FDE\u63A5\u6682\u4E0D\u53EF\u7528",e.error==="preview_dependency_missing"?"\u8BF7\u5B89\u88C5 ffmpeg \u540E\u91CD\u8FDE":"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u4E5F\u53EF\u70B9\u51FB\u300C\u91CD\u8FDE\u300D");return}if(Ge!==void 0&&e.seq<=Ge){Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026",!0);return}let r=e.frame;if(r&&r.seq>ln&&r.data&&r.width>0&&r.height>0){ln=r.seq;let i=++Le,o=`data:${r.mimeType};base64,${r.data}`,t=new Image;t.onload=()=>{Sf||wf||i!==Le||Ne?.paused||(Wi=o,fr.src=o,Qi.style.aspectRatio=`${r.width}/${r.height}`,Xe.style.setProperty("--screen-ratio",String(r.width/r.height)),Xe.dataset.orientation=r.width>r.height?"landscape":"portrait",Xe.dataset.frameSeq=String(ln),un=void 0,Ge=void 0,ny())},t.onerror=()=>Te("offline","\u753B\u9762\u89E3\u7801\u5931\u8D25","\u70B9\u51FB\u300C\u91CD\u8FDE\u300D\u91CD\u8BD5"),t.src=o}else e.frame_available&&Wi?(un=void 0,ny()):Wi?(Ge===void 0&&(Ge=e.seq,Le++),Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026",!0)):un!==void 0?Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026"):Te("connecting","\u6B63\u5728\u8FDE\u63A5\u89C6\u9891\u2026","\u901A\u8FC7 ADB \u89C6\u9891\u901A\u9053\u4F20\u8F93")}var cc=()=>!Sf&&!wf&&document.visibilityState!=="hidden";function vr(e=150){dt&&clearTimeout(dt),cc()&&(dt=setTimeout(tw,e))}async function tw(){if(!cc()||zf)return;zf=!0;let e=Le;try{let r=await mn("frame",{after_seq:ln});cc()&&e===Le&&ay(r)}catch{cc()&&e===Le&&(pr(),Hi("\u89C6\u9891\u8FDE\u63A5\u6062\u590D\u4E2D\u2026",!1,!0))}finally{zf=!1,vr(Ne?.paused?500:Xe.dataset.state==="offline"?1e3:150)}}async function to(e,r={}){if(!(lt||Ne?.paused)){lt=!0,Ji.textContent="";for(let i of Object.values(hr))i.disabled=!0;e==="refresh"&&(lc=!0,Ge=ln,Le++,Dt("\u6B63\u5728\u91CD\u8FDE\u2026"));try{let i=await mn(e==="refresh"?"refresh":"action",{action:e,...r});if(!i?.ok)throw new Error(i?.error?.code||"action_failed");e==="refresh"&&ay(i)}catch(i){e==="refresh"&&(lc=!1,Dt(String(i).includes("device_busy")?"\u624B\u673A\u6B63\u5728\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":"\u91CD\u8FDE\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u8BA9 Agent \u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55"))}finally{lt=!1,Te(Xe.dataset.state||"connecting"),vr(50)}}}Bi.onclick=async()=>{if(!Bi.disabled){Bi.disabled=!0;try{if(!(await mn("action",{action:"resume"}))?.ok)throw new Error("resume_failed")}catch{Dt("\u6062\u590D\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u6216\u8BA9 Agent \u6062\u590D")}finally{Bi.disabled=!1,vr(0)}}};hr.refresh.onclick=()=>{if(Ne?.paused){Dt("\u63A5\u7BA1\u671F\u95F4\u4FDD\u6301\u6682\u505C");return}to("refresh")};hr.home.onclick=()=>void to("home");hr.back.onclick=()=>void to("back");hr.copy.onclick=()=>{if(lt||Ne?.paused||Xe.dataset.state!=="live"||!fr.naturalWidth)return;if(!navigator.clipboard?.write||typeof ClipboardItem>"u"){Dt("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u590D\u5236\u56FE\u7247");return}let e=document.createElement("canvas");e.width=fr.naturalWidth,e.height=fr.naturalHeight;let r=e.getContext("2d");if(!r)return;r.drawImage(fr,0,0);let i=new Promise((o,t)=>e.toBlob(n=>n?o(n):t(new Error("encode_failed")),"image/png"));lt=!0,Te(Xe.dataset.state||"live"),navigator.clipboard.write([new ClipboardItem({"image/png":i})]).then(()=>Dt("\u753B\u9762\u5DF2\u590D\u5236")).catch(()=>Dt("\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u5141\u8BB8\u5199\u5165\u526A\u8D34\u677F")).finally(()=>{lt=!1,Te(Xe.dataset.state||"live")})};var dn;function sy(e){if(Xe.dataset.state!=="live"||lt||!Ne?.viewport)return;let r=fr.getBoundingClientRect(),[i,o]=Ne.viewport;if(!(Math.abs(r.width/r.height-i/o)>.08))return[Math.max(0,Math.min(i-1,Math.round((e.clientX-r.left)/r.width*i))),Math.max(0,Math.min(o-1,Math.round((e.clientY-r.top)/r.height*o)))]}Qi.onpointerdown=e=>{let r=sy(e);!r||!Ne?.viewport||(dn={x:r[0],y:r[1],at:performance.now(),stream:uc,size:[...Ne.viewport]},Qi.setPointerCapture(e.pointerId),Ki.style.display="block",Ki.style.left=`${r[0]/dn.size[0]*100}%`,Ki.style.top=`${r[1]/dn.size[1]*100}%`)};Qi.onpointerup=e=>{Ki.style.display="none";let r=dn;dn=void 0;let i=sy(e);if(!r||!i||r.stream!==uc||r.size.join()!==Ne?.viewport?.join())return;let o=i[0]-r.x,t=i[1]-r.y;Math.hypot(o,t)<20?to("tap",{x:i[0],y:i[1]}):to("swipe",{direction:Math.abs(o)>Math.abs(t)?o>0?"right":"left":t>0?"down":"up"})};Qi.onpointercancel=()=>{dn=void 0,Ki.style.display="none"};document.addEventListener("visibilitychange",()=>{document.hidden?(Le++,dt&&clearTimeout(dt)):vr(0)});window.addEventListener("pagehide",()=>{Sf=!0,Le++,dt&&clearTimeout(dt),Gi&&clearTimeout(Gi)});gr&&(gr.ontoolresult=()=>{oy&&vr(0)},gr.onhostcontextchanged=e=>{let r=e.displayMode==="inline";wf=r,r?(Le++,dt&&clearTimeout(dt)):vr(0)});async function rw(){Te("connecting");try{if(gr){await gr.connect(void 0,{timeout:8e3});try{await gr.requestDisplayMode({mode:"fullscreen"},{timeout:3e3})}catch{}}oy=!0,vr(0),mn("action",{action:"jev_status"}).then(e=>{e?.ok&&eo(e)}).catch(()=>{})}catch{Te("offline","\u65E0\u6CD5\u8FDE\u63A5\u5BBF\u4E3B","\u8BF7\u91CD\u65B0\u6253\u5F00 Android \u624B\u673A\u5C4F\u5E55")}}rw();
+container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:d.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:d.string().optional().describe("User's timezone in IANA format."),userAgent:d.string().optional().describe("Host application identifier."),platform:d.union([d.literal("web"),d.literal("desktop"),d.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:d.object({touch:d.boolean().optional().describe("Whether the device supports touch input."),hover:d.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:d.object({top:d.number().describe("Top safe area inset in pixels."),right:d.number().describe("Right safe area inset in pixels."),bottom:d.number().describe("Bottom safe area inset in pixels."),left:d.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),BS=d.object({method:d.literal("ui/notifications/host-context-changed"),params:ty.describe("Partial context update containing only changed fields.")}),iN=d.object({method:d.literal("ui/update-model-context"),params:d.object({content:d.array(sn).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:d.record(d.string(),d.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),oN=d.object({method:d.literal("ui/initialize"),params:d.object({appInfo:Ci.describe("App identification (name and version)."),appCapabilities:VS.describe("Features and capabilities this app provides."),protocolVersion:d.string().describe("Protocol version this app supports.")})}),HS=d.object({protocolVersion:d.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ci.describe("Host application identification and version."),hostCapabilities:MS.describe("Features and capabilities provided by the host."),hostContext:ty.describe("Rich context about the host environment.")}).passthrough(),KS={target:"draft-2020-12"};async function Y$(e,r){let i=e["~standard"];if(i.jsonSchema)return i.jsonSchema[r](KS);if(i.vendor==="zod"){let{z:o}=await Promise.resolve().then(()=>(Ni(),Xp));return o.toJSONSchema(e,{io:r})}throw Error(`Schema (vendor: ${i.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function ey(e,r,i=""){let o=await e["~standard"].validate(r);if(o.issues){let t=o.issues.map(n=>{let a=n.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${n.message}`:n.message}).join("; ");throw Error(i+t)}return o.value}var sc=class e extends bf{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(r){if(this._initializedSent)return;let i=`[ext-apps] App.${r}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(i);console.warn(`${i}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:ES,toolresult:JS,toolcancelled:CS,hostcontextchanged:BS};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(r){if(!e.ONE_SHOT_EVENTS.has(r)||this._everHadListener.has(r)||(this._everHadListener.add(r),!this._initializedSent))return;let i=`[ext-apps] "${String(r)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(i);console.warn(i)}setEventHandler(r,i){i&&this._assertHandlerTiming(r),super.setEventHandler(r,i)}addEventListener(r,i){this._assertHandlerTiming(r),super.addEventListener(r,i)}onEventDispatch(r,i){r==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i})}constructor(r,i={},o={autoResize:!0}){super(o),this._appInfo=r,this._capabilities=i,this.options=o,o.allowUnsafeEval||d.config({jitless:!0}),this.setRequestHandler(on,t=>(console.log("Received ping:",t.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(r){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Q$(this._capabilities,r)}registerTool(r,i,o){if(this._registeredTools[r])throw Error(`Tool ${r} is already registered`);let t=this,n=()=>{t._initializedSent&&t._capabilities.tools?.listChanged&&t.sendToolListChanged()},a=i.inputSchema!==void 0,s={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){t._registeredTools[r]===s&&(delete t._registeredTools[r],n())},handler:async(c,u)=>{if(!s.enabled)throw Error(`Tool ${r} is disabled`);let l;if(a){let m=s.inputSchema,p=m?await ey(m,c??{},`Invalid input for tool ${r}: `):c??{};l=await o(p,u)}else l=await o(u);return s.outputSchema&&!l.isError&&(l.structuredContent=await ey(s.outputSchema,l.structuredContent,`Invalid output for tool ${r}: `)),l}};return this._registeredTools[r]=s,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),n(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(r,i)=>{let o=this._registeredTools[r.name];if(!o)throw Error(`Tool ${r.name} not found`);return o.handler(r.arguments,i)},this.onlisttools=async(r,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,t])=>t.enabled).map(async([o,t])=>{let n={name:o,title:t.title,description:t.description,inputSchema:t.inputSchema?await Y$(t.inputSchema,"input"):{type:"object",properties:{}}};return t.outputSchema&&(n.outputSchema=await Y$(t.outputSchema,"output")),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(r={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:r})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(r){this.setEventHandler("toolinput",r)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(r){this.setEventHandler("toolinputpartial",r)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(r){this.setEventHandler("toolresult",r)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(r){this.setEventHandler("toolcancelled",r)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(r){this.setEventHandler("hostcontextchanged",r)}_onteardown;get onteardown(){return this._onteardown}set onteardown(r){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,r),this._onteardown=r,this.replaceRequestHandler(LS,(i,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i.params,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(r){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,r),this._oncalltool=r,this.replaceRequestHandler(gf,(i,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(r){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,r),this._onlisttools=r,this.replaceRequestHandler(ff,(i,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,o)})}assertCapabilityForMethod(r){switch(r){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${r})`);break}}assertRequestHandlerCapability(r){switch(r){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${r})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${r} registered`)}}assertNotificationCapability(r){}assertTaskCapability(r){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(r){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(r,i){if(this._assertInitialized("callServerTool"),typeof r=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${r}"). Did you mean: callServerTool({ name: "${r}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:r},cn,{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(r,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:r},cf,i)}async listServerResources(r,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:r},af,i)}async createSamplingMessage(r,i){this._assertInitialized("createSamplingMessage");let o=r.tools?vf:hf;return await this.request({method:"sampling/createMessage",params:r},o,i)}sendMessage(r,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:r},AS,i)}sendLog(r){return this.notification({method:"notifications/message",params:r})}updateModelContext(r,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:r},Ws,i)}openLink(r,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:r},OS,i)}sendOpenLink=this.openLink;downloadFile(r,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:r},NS,i)}requestTeardown(r={}){return this.notification({method:"ui/notifications/request-teardown",params:r})}requestDisplayMode(r,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:r},FS,i)}sendSizeChanged(r){return this.notification({method:"ui/notifications/size-changed",params:r})}setupSizeChangedNotifications(){let r=!1,i=0,o=0,t=()=>{r||(r=!0,requestAnimationFrame(()=>{r=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let u=Math.ceil(window.innerWidth);(u!==i||c!==o)&&(i=u,o=c,this.sendSizeChanged({width:u,height:c}))}))};t();let n=new ResizeObserver(t);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(r=new _f(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(r);try{let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:IS}},HS,i);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};var Xe=document.querySelector("#app"),fr=document.querySelector("#frame"),Qi=document.querySelector("#device"),ry=document.querySelector("#overlay"),WS=document.querySelector("#overlay-text"),GS=document.querySelector("#overlay-detail"),QS=document.querySelector("#status-text"),Ji=document.querySelector("#notice"),Ki=document.querySelector("#pointer"),Bi=document.querySelector("#resume"),hr=Object.fromEntries(["refresh","back","home","copy"].map(e=>[e,document.getElementById(e)])),iy=window.__ANDROID_USE_STANDALONE__===!0,gr=iy?void 0:new sc({name:"Android Use Screen",version:"0.8.0"},{availableDisplayModes:["fullscreen"]},{autoResize:!1}),Ne,ln=0,uc="",Sf=!1,zf=!1,lt=!1,wf=!1,dt,Wi="",Le=0,oy=!1,lc=!1,XS=5e3,un,Ge,Gi,dc=document.querySelector("#settings"),mc=document.querySelector("#jev-settings"),Ye=document.querySelector("#jev-key"),jt=document.querySelector("#jev-message"),If=document.querySelector("#jev-enable"),pc=document.querySelector("#jev-test"),Xi=document.querySelector("#jev-disable"),Yi=document.querySelector("#jev-clear"),Tt=document.querySelector("#jev-images"),Qe,Be=!1,YS={connecting:"\u8FDE\u63A5\u4E2D",live:"Live",buffering:"\u7F13\u51B2\u4E2D",paused:"\u5DF2\u6682\u505C",offline:"\u672A\u8FDE\u63A5",unsupported:"\u4E0D\u652F\u6301\u9884\u89C8"};function Dt(e,r=""){Gi&&clearTimeout(Gi),Ji.textContent=e,Ji.title=r,Gi=setTimeout(()=>{Ji.textContent="",Ji.title=""},3e3)}function Te(e,r,i){Xe.dataset.state=e,QS.textContent=YS[e],ry.hidden=e==="live"||e==="buffering",ry.hidden||(WS.textContent=r??"\u6B63\u5728\u8FDE\u63A5\u624B\u673A\u2026",GS.textContent=i??"\u5B9E\u65F6\u89C6\u9891\u5C06\u5728\u8FD9\u91CC\u663E\u793A"),Bi.hidden=!(e==="paused"&&Ne?.pause_reason==="authentication");for(let o of["home","back","copy"])hr[o].disabled=lt||e!=="live";hr.refresh.disabled=lt}async function mn(e,r={}){if(iy){let o=await fetch(`api/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(e==="action"?2e4:8e3)});if(!o.ok){if(e==="action"&&String(r.action).startsWith("jev_"))try{let t=await o.json();if(t?.error?.code)return t}catch{}throw new Error("preview_unreachable")}return o.json()}return(await gr.callServerTool({name:e==="frame"?"aua_screen_frame":"aua_screen_action",arguments:e==="frame"?r:e==="refresh"?{action:"refresh"}:r},{timeout:e==="action"?2e4:8e3})).structuredContent}function eo(e){Qe=e,dc.dataset.enabled=String(e.enabled),document.querySelector("#jev-state").textContent=e.demo?"\u6587\u6863\u793A\u4F8B\uFF0C\u8BF7\u5728\u5B9E\u9645\u624B\u673A\u5C4F\u5E55\u4E2D\u914D\u7F6E":e.enabled?"Jev \u5DF2\u542F\u7528":e.configured?"\u5DF2\u914D\u7F6E Key\uFF0CJev \u672A\u542F\u7528":"\u5C1A\u672A\u914D\u7F6E\uFF0C\u586B\u5165 Key \u5373\u53EF\u5F00\u59CB",document.querySelector("#jev-provider").textContent=`${e.model} \xB7 ${e.base_url}`,Ye.placeholder=e.configured?"\u5DF2\u6709 Key\uFF0C\u7559\u7A7A\u7EE7\u7EED\u4F7F\u7528":"\u7C98\u8D34\u4F60\u7684 API Key",Ye.disabled=!!e.demo||Be,If.disabled=!!e.demo||Be||!e.configured&&!Ye.value.trim(),pc.disabled=!e.configured||!!e.demo||Be,Xi.hidden=!e.enabled,Yi.hidden=!e.has_saved_key,Xi.disabled=Be,Yi.disabled=Be,Tt.checked=!!e.images_enabled,Tt.disabled=!!e.demo||Be}function ew(e){return e?.error?.code==="jev_http_error"?e.error.status===401?"Key \u65E0\u6548\u6216\u5DF2\u5931\u6548":e.error.status===429?"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"\u670D\u52A1\u62D2\u7EDD\u8BF7\u6C42\uFF0C\u8BF7\u68C0\u67E5 Key \u6743\u9650\u548C\u8D26\u6237\u72B6\u6001":{jev_configuration:"\u8BF7\u586B\u5199\u6709\u6548\u7684 TypeSafe API Key",jev_transport_error:"\u65E0\u6CD5\u8FDE\u63A5 TypeSafe\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5",jev_settings_unavailable:"\u65E0\u6CD5\u8BFB\u53D6\u6216\u4FDD\u5B58\u672C\u673A\u8BBE\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650",jev_validation_failed:"\u8FDE\u63A5\u6D4B\u8BD5\u672A\u901A\u8FC7\uFF0C\u8BBE\u7F6E\u5C1A\u672A\u66F4\u6539",device_busy:"\u53E6\u4E00\u9879\u8BBE\u7F6E\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}[e?.error?.code||""]||"\u8BBE\u7F6E\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u540E\u91CD\u8BD5"}async function ro(e){if(!(Be||!Qe||Qe.demo)){Be=!0,jt.textContent=e==="jev_save"?"\u6B63\u5728\u9A8C\u8BC1 Key\u2026":e==="jev_test"?"\u6B63\u5728\u6D4B\u8BD5\u8FDE\u63A5\u2026":"\u6B63\u5728\u66F4\u65B0\u8BBE\u7F6E\u2026",jt.dataset.error="false",Ye.disabled=!0,dc.disabled=!0,document.querySelector("#settings-close").disabled=!0;for(let r of[If,pc,Xi,Yi,Tt])r.disabled=!0;try{let r=await mn("action",{action:e,...e==="jev_save"?{api_key:Ye.value}:{}});if(!r?.ok){jt.textContent=ew(r),jt.dataset.error="true";return}e.startsWith("jev_images")||(Ye.value=""),eo(r),jt.textContent=r.tested?`${e==="jev_save"?"\u5DF2\u4FDD\u5B58\u5E76\u542F\u7528":"\u8FDE\u63A5\u6B63\u5E38"} \xB7 ${r.latency_ms} ms`:e==="jev_images_on"?"\u5DF2\u5141\u8BB8\u53D1\u9001\u622A\u56FE":e==="jev_images_off"?"\u5DF2\u5173\u95ED\u622A\u56FE\u53D1\u9001":e==="jev_clear"?"\u672C\u673A Key \u5DF2\u79FB\u9664\uFF0CJev \u5DF2\u505C\u7528":"Jev \u5DF2\u505C\u7528"}catch{jt.textContent="\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A\u8BBE\u7F6E\u670D\u52A1\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55",jt.dataset.error="true"}finally{Be=!1,dc.disabled=!1,document.querySelector("#settings-close").disabled=!1,Qe&&eo(Qe)}}}dc.onclick=()=>{Be||(Qe=void 0,Ye.value="",Ye.disabled=!0,jt.textContent="",mc.showModal(),If.disabled=!0,pc.disabled=!0,Xi.hidden=!0,Yi.hidden=!0,Tt.disabled=!0,Tt.checked=!1,mn("action",{action:"jev_status"}).then(e=>{if(!e?.ok)throw new Error("settings_unavailable");eo(e)}).catch(()=>{document.querySelector("#jev-state").textContent="\u65E0\u6CD5\u8BFB\u53D6\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55"}))};document.querySelector("#jev-form").onsubmit=e=>{e.preventDefault(),ro("jev_save")};Tt.onchange=()=>{let e=Tt.checked;Qe&&(Tt.checked=!!Qe.images_enabled),ro(e?"jev_images_on":"jev_images_off")};pc.onclick=()=>void ro("jev_test");Xi.onclick=()=>void ro("jev_disable");Yi.onclick=()=>void ro("jev_clear");document.querySelector("#settings-close").onclick=()=>mc.close();mc.addEventListener("close",()=>{Ye.value=""});mc.addEventListener("cancel",e=>{Be&&e.preventDefault()});Ye.oninput=()=>{Qe&&eo(Qe)};function pr(){Le++,fr.removeAttribute("src"),Wi="",ln=0}function Hi(e,r=!1,i=!1){un??=performance.now();let o=performance.now()-un>=XS;if(!o&&r&&Wi){Te("buffering");return}o&&pr(),Te(o?"offline":"connecting",o?i?"\u672C\u5730\u9884\u89C8\u670D\u52A1\u672A\u54CD\u5E94":"\u89C6\u9891\u6682\u4E0D\u53EF\u7528":e,o?i?"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u5931\u8D25\uFF0C\u8BF7\u8BA9 Agent \u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55":"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u4E5F\u53EF\u70B9\u51FB\u300C\u91CD\u8FDE\u300D":"\u6B63\u5728\u81EA\u52A8\u6062\u590D\uFF0C\u65E0\u9700\u624B\u52A8\u91CD\u8FDE")}function ny(){let e=Ne?.interaction_ready===!1?"buffering":"live";Te(e),e==="live"&&lc&&(lc=!1,Dt("\u5DF2\u91CD\u65B0\u8FDE\u63A5"))}function ay(e){if(!e?.ok)throw new Error("preview_unreachable");if(Ne=e,document.querySelector("#model").textContent=e.device?.model||"Android",uc!==e.stream_id&&(uc=e.stream_id,pr(),Ge=void 0),e.paused){pr(),Ge=void 0,un=void 0,Te("paused","\u8BF7\u5728\u624B\u673A\u4E0A\u63A5\u7BA1\u64CD\u4F5C",e.pause_reason==="device_locked"?"\u624B\u673A\u5DF2\u9501\u5B9A\uFF0C\u89E3\u9501\u540E\u81EA\u52A8\u6062\u590D":"\u8BA4\u8BC1\u5B8C\u6210\u540E\u70B9\u51FB\u4E0B\u65B9\u6309\u94AE\uFF0C\u6216\u7531 agent \u6062\u590D\u9884\u89C8");return}if(!e.connected){pr(),Te("offline","\u624B\u673A\u672A\u8FDE\u63A5","\u8BF7\u68C0\u67E5 USB \u6216\u65E0\u7EBF ADB \u8FDE\u63A5");return}if(e.error==="video_stream_ended"){Ge===void 0&&(Ge=e.seq,Le++),Hi("\u6B63\u5728\u6062\u590D\u89C6\u9891\u2026",!0);return}if(e.error==="preview_unsupported_device"){pr(),Te("unsupported","\u6B64\u624B\u673A\u4E0D\u652F\u6301\u5B9E\u65F6\u9884\u89C8","\u7CFB\u7EDF\u672A\u63D0\u4F9B screenrecord\uFF1B\u622A\u56FE\u3001\u8BFB\u5C4F\u548C\u64CD\u4F5C\u4ECD\u53EF\u6B63\u5E38\u4F7F\u7528");return}if(e.error){pr(),Te("offline","\u89C6\u9891\u8FDE\u63A5\u6682\u4E0D\u53EF\u7528",e.error==="preview_dependency_missing"?"\u8BF7\u5B89\u88C5 ffmpeg \u540E\u91CD\u8FDE":"\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u4E5F\u53EF\u70B9\u51FB\u300C\u91CD\u8FDE\u300D");return}if(Ge!==void 0&&e.seq<=Ge){Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026",!0);return}let r=e.frame;if(r&&r.seq>ln&&r.data&&r.width>0&&r.height>0){ln=r.seq;let i=++Le,o=`data:${r.mimeType};base64,${r.data}`,t=new Image;t.onload=()=>{Sf||wf||i!==Le||Ne?.paused||(Wi=o,fr.src=o,Qi.style.aspectRatio=`${r.width}/${r.height}`,Xe.style.setProperty("--screen-ratio",String(r.width/r.height)),Xe.dataset.orientation=r.width>r.height?"landscape":"portrait",Xe.dataset.frameSeq=String(ln),un=void 0,Ge=void 0,ny())},t.onerror=()=>Te("offline","\u753B\u9762\u89E3\u7801\u5931\u8D25","\u70B9\u51FB\u300C\u91CD\u8FDE\u300D\u91CD\u8BD5"),t.src=o}else e.frame_available&&Wi?(un=void 0,ny()):Wi?(Ge===void 0&&(Ge=e.seq,Le++),Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026",!0)):un!==void 0?Hi("\u6B63\u5728\u7B49\u5F85\u65B0\u753B\u9762\u2026"):Te("connecting","\u6B63\u5728\u8FDE\u63A5\u89C6\u9891\u2026","\u901A\u8FC7 ADB \u89C6\u9891\u901A\u9053\u4F20\u8F93")}var cc=()=>!Sf&&!wf&&document.visibilityState!=="hidden";function vr(e=150){dt&&clearTimeout(dt),cc()&&(dt=setTimeout(tw,e))}async function tw(){if(!cc()||zf)return;zf=!0;let e=Le;try{let r=await mn("frame",{after_seq:ln});cc()&&e===Le&&ay(r)}catch{cc()&&e===Le&&(pr(),Hi("\u89C6\u9891\u8FDE\u63A5\u6062\u590D\u4E2D\u2026",!1,!0))}finally{zf=!1,vr(Ne?.paused?500:Xe.dataset.state==="offline"?1e3:150)}}async function to(e,r={}){if(!(lt||Ne?.paused)){lt=!0,Ji.textContent="";for(let i of Object.values(hr))i.disabled=!0;e==="refresh"&&(lc=!0,Ge=ln,Le++,Dt("\u6B63\u5728\u91CD\u8FDE\u2026"));try{let i=await mn(e==="refresh"?"refresh":"action",{action:e,...r});if(!i?.ok)throw new Error(i?.error?.code||"action_failed");e==="refresh"&&ay(i)}catch(i){e==="refresh"&&(lc=!1,Dt(String(i).includes("device_busy")?"\u624B\u673A\u6B63\u5728\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":"\u91CD\u8FDE\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u8BA9 Agent \u91CD\u65B0\u6253\u5F00\u624B\u673A\u5C4F\u5E55"))}finally{lt=!1,Te(Xe.dataset.state||"connecting"),vr(50)}}}Bi.onclick=async()=>{if(!Bi.disabled){Bi.disabled=!0;try{if(!(await mn("action",{action:"resume"}))?.ok)throw new Error("resume_failed")}catch{Dt("\u6062\u590D\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u6216\u8BA9 Agent \u6062\u590D")}finally{Bi.disabled=!1,vr(0)}}};hr.refresh.onclick=()=>{if(Ne?.paused){Dt("\u63A5\u7BA1\u671F\u95F4\u4FDD\u6301\u6682\u505C");return}to("refresh")};hr.home.onclick=()=>void to("home");hr.back.onclick=()=>void to("back");hr.copy.onclick=()=>{if(lt||Ne?.paused||Xe.dataset.state!=="live"||!fr.naturalWidth)return;if(!navigator.clipboard?.write||typeof ClipboardItem>"u"){Dt("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u590D\u5236\u56FE\u7247");return}let e=document.createElement("canvas");e.width=fr.naturalWidth,e.height=fr.naturalHeight;let r=e.getContext("2d");if(!r)return;r.drawImage(fr,0,0);let i=new Promise((o,t)=>e.toBlob(n=>n?o(n):t(new Error("encode_failed")),"image/png"));lt=!0,Te(Xe.dataset.state||"live"),navigator.clipboard.write([new ClipboardItem({"image/png":i})]).then(()=>Dt("\u753B\u9762\u5DF2\u590D\u5236")).catch(()=>Dt("\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u5141\u8BB8\u5199\u5165\u526A\u8D34\u677F")).finally(()=>{lt=!1,Te(Xe.dataset.state||"live")})};var dn;function sy(e){if(Xe.dataset.state!=="live"||lt||!Ne?.viewport)return;let r=fr.getBoundingClientRect(),[i,o]=Ne.viewport;if(!(Math.abs(r.width/r.height-i/o)>.08))return[Math.max(0,Math.min(i-1,Math.round((e.clientX-r.left)/r.width*i))),Math.max(0,Math.min(o-1,Math.round((e.clientY-r.top)/r.height*o)))]}Qi.onpointerdown=e=>{let r=sy(e);!r||!Ne?.viewport||(dn={x:r[0],y:r[1],at:performance.now(),stream:uc,size:[...Ne.viewport]},Qi.setPointerCapture(e.pointerId),Ki.style.display="block",Ki.style.left=`${r[0]/dn.size[0]*100}%`,Ki.style.top=`${r[1]/dn.size[1]*100}%`)};Qi.onpointerup=e=>{Ki.style.display="none";let r=dn;dn=void 0;let i=sy(e);if(!r||!i||r.stream!==uc||r.size.join()!==Ne?.viewport?.join())return;let o=i[0]-r.x,t=i[1]-r.y;Math.hypot(o,t)<20?to("tap",{x:i[0],y:i[1]}):to("swipe",{direction:Math.abs(o)>Math.abs(t)?o>0?"right":"left":t>0?"down":"up"})};Qi.onpointercancel=()=>{dn=void 0,Ki.style.display="none"};document.addEventListener("visibilitychange",()=>{document.hidden?(Le++,dt&&clearTimeout(dt)):vr(0)});window.addEventListener("pagehide",()=>{Sf=!0,Le++,dt&&clearTimeout(dt),Gi&&clearTimeout(Gi)});gr&&(gr.ontoolresult=()=>{oy&&vr(0)},gr.onhostcontextchanged=e=>{let r=e.displayMode==="inline";wf=r,r?(Le++,dt&&clearTimeout(dt)):vr(0)});async function rw(){Te("connecting");try{if(gr){await gr.connect(void 0,{timeout:8e3});try{await gr.requestDisplayMode({mode:"fullscreen"},{timeout:3e3})}catch{}}oy=!0,vr(0),mn("action",{action:"jev_status"}).then(e=>{e?.ok&&eo(e)}).catch(()=>{})}catch{Te("offline","\u65E0\u6CD5\u8FDE\u63A5\u5BBF\u4E3B","\u8BF7\u91CD\u65B0\u6253\u5F00 Android \u624B\u673A\u5C4F\u5E55")}}rw();