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 @@ Standard stdio MCP

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 @@ 标准 stdio MCP

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(); diff --git a/src/android_use/hotswap/__init__.py b/src/android_use/hotswap/__init__.py new file mode 100644 index 0000000..22a489e --- /dev/null +++ b/src/android_use/hotswap/__init__.py @@ -0,0 +1,5 @@ +"""Hot swap edited code and resources into a running, debuggable Android app.""" + +from .engine import Fail, Tools, run_action + +__all__ = ["Fail", "Tools", "run_action"] diff --git a/src/android_use/hotswap/agent/agent.cpp b/src/android_use/hotswap/agent/agent.cpp new file mode 100644 index 0000000..ed67737 --- /dev/null +++ b/src/android_use/hotswap/agent/agent.cpp @@ -0,0 +1,581 @@ +// JVMTI hot swap agent. Runs inside a debuggable app via: +// am attach-agent = +// +// Plan file, one directive per line: +// refresh auto|recreate|none +// compose (auto: composable groups whose slots must be reset) +// helper (hotswap.agent.HotswapState, for rebuilding activities) +// class +// resources (replaces the app's resource table, Android 11+) +// statics (also copy that class's static field values) +// +// Each class is redefined in place when the app already has it (loading it first if +// needed) and defined in the app class loader when it is new. The verdict goes to +// logcat (tag "hotswap") and to ".result". +#include +#include +#include +#include +#include +#include +#include + +#include "jvmti.h" + +#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "hotswap", __VA_ARGS__) + +namespace { + +struct Entry { + std::string name, dex_path; + std::vector dex; + jclass klass = nullptr; +}; + +struct Extensions { + jvmtiExtensionFunction add_dex_file = nullptr; + jvmtiExtensionFunction structural_redefine = nullptr; + jvmtiExtensionFunction last_error = nullptr; +}; + +bool read_file(const std::string& path, std::vector* out) { + FILE* f = fopen(path.c_str(), "rb"); + if (!f) return false; + unsigned char buf[8192]; + size_t n; + while ((n = fread(buf, 1, sizeof buf, f)) > 0) out->insert(out->end(), buf, buf + n); + fclose(f); + return !out->empty(); +} + +jint report(const std::string& plan, bool ok, const std::string& text) { + std::string line = (ok ? "OK " : "FAIL ") + text; + LOG("%s", line.c_str()); + if (FILE* f = fopen((plan + ".result").c_str(), "w")) { + fputs(line.c_str(), f); + fputc('\n', f); + fclose(f); + } + return ok ? JNI_OK : JNI_ERR; +} + +std::string error_text(jvmtiEnv* jvmti, const Extensions& ext, jvmtiError err) { + char* name = nullptr; + jvmti->GetErrorName(err, &name); + std::string text = name ? name : std::to_string(err); + char* detail = nullptr; + if (ext.last_error && ext.last_error(jvmti, &detail) == JVMTI_ERROR_NONE && detail) { + text += ": "; + text += detail; + text = text.substr(0, text.find('\n')); // drop the Java stack trace + } + return text; +} + +Extensions find_extensions(jvmtiEnv* jvmti) { + Extensions ext; + jint count = 0; + jvmtiExtensionFunctionInfo* infos = nullptr; + if (jvmti->GetExtensionFunctions(&count, &infos) != JVMTI_ERROR_NONE) return ext; + for (jint i = 0; i < count; i++) { + std::string id = infos[i].id; + if (id == "com.android.art.classloader.add_to_dex_class_loader") + ext.add_dex_file = infos[i].func; + else if (id == "com.android.art.class.structurally_redefine_classes") + ext.structural_redefine = infos[i].func; + else if (id == "com.android.art.misc.get_last_error_message") + ext.last_error = infos[i].func; + } + return ext; +} + +bool on_main_thread(JNIEnv* env) { + jclass looper = env->FindClass("android/os/Looper"); + jobject mine = env->CallStaticObjectMethod( + looper, env->GetStaticMethodID(looper, "myLooper", "()Landroid/os/Looper;")); + jobject main = env->CallStaticObjectMethod( + looper, env->GetStaticMethodID(looper, "getMainLooper", "()Landroid/os/Looper;")); + return mine && env->IsSameObject(mine, main); +} + +// The app's own class loader: the main thread's context loader, else the loader of +// any loaded Activity subclass. +jobject app_class_loader(JNIEnv* env, jvmtiEnv* jvmti, jint count, jclass* classes) { + jclass thread = env->FindClass("java/lang/Thread"); + jobject current = env->CallStaticObjectMethod( + thread, env->GetStaticMethodID(thread, "currentThread", "()Ljava/lang/Thread;")); + jobject loader = env->CallObjectMethod( + current, env->GetMethodID(thread, "getContextClassLoader", "()Ljava/lang/ClassLoader;")); + if (env->ExceptionCheck()) env->ExceptionClear(); + if (loader && on_main_thread(env)) return loader; + jclass activity = env->FindClass("android/app/Activity"); + for (jint i = 0; i < count; i++) { + if (!env->IsAssignableFrom(classes[i], activity)) continue; + jobject found = nullptr; + if (jvmti->GetClassLoader(classes[i], &found) == JVMTI_ERROR_NONE && found) return found; + } + return loader; +} + +jclass load_class(JNIEnv* env, jobject loader, const std::string& name) { + jclass cl = env->FindClass("java/lang/ClassLoader"); + jmethodID load = env->GetMethodID(cl, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); + jobject found = env->CallObjectMethod(loader, load, env->NewStringUTF(name.c_str())); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + return nullptr; + } + return static_cast(found); +} + +jint JNICALL tag_instance(jlong, jlong, jlong* tag, jint, void* wanted) { + *tag = *static_cast(wanted); + return JVMTI_VISIT_OBJECTS; +} + +// Every Activity instance that is still alive, found by walking the heap. +std::vector live_activities(JNIEnv* env, jvmtiEnv* jvmti) { + std::vector result; + jint count = 0; + jclass* classes = nullptr; + if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE) return result; + jclass activity = env->FindClass("android/app/Activity"); + jlong tag = 0x686f7473776170; // "hotswap" + jvmtiHeapCallbacks callbacks; + memset(&callbacks, 0, sizeof callbacks); + callbacks.heap_iteration_callback = tag_instance; + // The class filter matches exact classes only, so walk each Activity subclass. + for (jint i = 0; i < count; i++) + if (env->IsAssignableFrom(classes[i], activity)) + jvmti->IterateThroughHeap(0, classes[i], &callbacks, &tag); + jint found = 0; + jobject* objects = nullptr; + if (jvmti->GetObjectsWithTags(1, &tag, &found, &objects, nullptr) != JVMTI_ERROR_NONE) + return result; + jmethodID finishing = env->GetMethodID(activity, "isFinishing", "()Z"); + jmethodID destroyed = env->GetMethodID(activity, "isDestroyed", "()Z"); + for (jint i = 0; i < found; i++) { + jvmti->SetTag(objects[i], 0); + if (env->CallBooleanMethod(objects[i], finishing)) continue; + if (env->CallBooleanMethod(objects[i], destroyed)) continue; + result.push_back(objects[i]); + } + return result; +} + +// Rebuild the activities so the UI is drawn by the new code. Activity fields are lost +// unless saved; statics, singletons and ViewModels survive. +int recreate_activities(JNIEnv* env, const std::vector& activities, jclass helper) { + jclass activity = env->FindClass("android/app/Activity"); + jmethodID recreate = env->GetMethodID(activity, "recreate", "()V"); + // The helper rebuilds the activity too, and afterwards puts back scroll offsets and + // other view state the platform loses. + jmethodID keeping = helper ? env->GetStaticMethodID(helper, "recreate", "(Landroid/app/Activity;)V") + : nullptr; + if (env->ExceptionCheck()) { + env->ExceptionClear(); + keeping = nullptr; + } + int done = 0; + for (jobject one : activities) { + if (keeping) env->CallStaticVoidMethod(helper, keeping, one); + else env->CallVoidMethod(one, recreate); + if (env->ExceptionCheck()) env->ExceptionClear(); + else done++; + } + return done; +} + +// True (with the exception cleared and described) when the last JNI call threw. +bool threw(JNIEnv* env, std::string* error) { + if (!env->ExceptionCheck()) return false; + jthrowable thrown = env->ExceptionOccurred(); + env->ExceptionClear(); + jclass object = env->FindClass("java/lang/Object"); + jstring text = static_cast(env->CallObjectMethod( + thrown, env->GetMethodID(object, "toString", "()Ljava/lang/String;"))); + if (env->ExceptionCheck()) env->ExceptionClear(); + const char* chars = text ? env->GetStringUTFChars(text, nullptr) : nullptr; + *error = chars ? chars : "exception"; + if (chars) env->ReleaseStringUTFChars(text, chars); + return true; +} + +// Redefining a class never reruns its static initializer, so fields such as the +// non-final resource IDs in R classes keep their old values. Initialize the new version +// in a throwaway class loader and copy its static fields onto the live class. +int copy_statics(JNIEnv* env, jobject app_loader, const std::vector& entries, + std::string* error) { + std::string path; + for (const Entry& e : entries) path += (path.empty() ? "" : ":") + e.dex_path; + jclass path_loader = env->FindClass("dalvik/system/PathClassLoader"); + jobject fresh_loader = env->NewObject( + path_loader, + env->GetMethodID(path_loader, "", "(Ljava/lang/String;Ljava/lang/ClassLoader;)V"), + env->NewStringUTF(path.c_str()), nullptr); + if (threw(env, error)) return -1; + jclass klass = env->FindClass("java/lang/Class"); + jmethodID for_name = env->GetStaticMethodID( + klass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"); + jmethodID fields_of = env->GetMethodID(klass, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"); + jmethodID field_of = env->GetMethodID( + klass, "getDeclaredField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;"); + jclass field = env->FindClass("java/lang/reflect/Field"); + jmethodID name_of = env->GetMethodID(field, "getName", "()Ljava/lang/String;"); + jmethodID modifiers = env->GetMethodID(field, "getModifiers", "()I"); + jmethodID accessible = env->GetMethodID(field, "setAccessible", "(Z)V"); + jmethodID get = env->GetMethodID(field, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); + jmethodID set = env->GetMethodID(field, "set", "(Ljava/lang/Object;Ljava/lang/Object;)V"); + int copied = 0; + for (const Entry& e : entries) { + jstring name = env->NewStringUTF(e.name.c_str()); + jobject fresh = env->CallStaticObjectMethod(klass, for_name, name, JNI_TRUE, fresh_loader); + if (threw(env, error)) return -1; + jobject live = env->CallStaticObjectMethod(klass, for_name, name, JNI_TRUE, app_loader); + if (threw(env, error)) return -1; + jobjectArray fields = static_cast(env->CallObjectMethod(fresh, fields_of)); + if (threw(env, error)) return -1; + jsize total = env->GetArrayLength(fields); + for (jsize i = 0; i < total; i++) { + jobject source = env->GetObjectArrayElement(fields, i); + jint flags = env->CallIntMethod(source, modifiers); + // Only static, non-final fields: final constants are compiled into callers. + if (!(flags & 0x0008) || (flags & 0x0010)) continue; + jobject target = env->CallObjectMethod(live, field_of, env->CallObjectMethod(source, name_of)); + std::string ignored; + if (threw(env, &ignored)) continue; + env->CallVoidMethod(source, accessible, JNI_TRUE); + env->CallVoidMethod(target, accessible, JNI_TRUE); + jobject value = env->CallObjectMethod(source, get, nullptr); + if (threw(env, &ignored)) continue; + env->CallVoidMethod(target, set, nullptr, value); + if (!threw(env, &ignored)) copied++; + env->DeleteLocalRef(source); + env->DeleteLocalRef(target); + env->DeleteLocalRef(value); + } + } + return copied; +} + +// Ask the Compose runtime to rerun the composable functions with these group keys. The +// compositions stay alive, so remembered state (text fields, scroll positions) survives. +// Uses the runtime's own hot reload entry point; returns -1 when the app has no Compose. +int invalidate_compose(JNIEnv* env, jobject app_loader, const std::vector& keys, + std::string* error) { + jclass reloader = load_class(env, app_loader, "androidx.compose.runtime.HotReloader"); + if (!reloader) return -1; + jclass klass = env->FindClass("java/lang/Class"); + jclass field = env->FindClass("java/lang/reflect/Field"); + jclass method = env->FindClass("java/lang/reflect/Method"); + jclass accessible = env->FindClass("java/lang/reflect/AccessibleObject"); + jmethodID set_accessible = env->GetMethodID(accessible, "setAccessible", "(Z)V"); + jobject companion_field = env->CallObjectMethod( + reloader, + env->GetMethodID(klass, "getDeclaredField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;"), + env->NewStringUTF("Companion")); + if (threw(env, error)) return -2; + env->CallVoidMethod(companion_field, set_accessible, JNI_TRUE); + jobject companion = env->CallObjectMethod( + companion_field, + env->GetMethodID(field, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"), nullptr); + if (threw(env, error)) return -2; + jobjectArray methods = static_cast(env->CallObjectMethod( + env->GetObjectClass(companion), + env->GetMethodID(klass, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"))); + if (threw(env, error)) return -2; + jmethodID name_of = env->GetMethodID(method, "getName", "()Ljava/lang/String;"); + jobject invalidate = nullptr; + for (jsize i = 0; i < env->GetArrayLength(methods) && !invalidate; i++) { + jobject one = env->GetObjectArrayElement(methods, i); + jstring name = static_cast(env->CallObjectMethod(one, name_of)); + const char* chars = env->GetStringUTFChars(name, nullptr); + // Declared internal in Kotlin, so the JVM name carries a module suffix. + if (!strncmp(chars, "invalidateGroupsWithKey", 23)) invalidate = one; + env->ReleaseStringUTFChars(name, chars); + } + if (!invalidate) { + *error = "this Compose runtime has no invalidateGroupsWithKey"; + return -2; + } + env->CallVoidMethod(invalidate, set_accessible, JNI_TRUE); + jmethodID invoke = env->GetMethodID( + method, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"); + jclass integer = env->FindClass("java/lang/Integer"); + jmethodID value_of = env->GetStaticMethodID(integer, "valueOf", "(I)Ljava/lang/Integer;"); + jclass object = env->FindClass("java/lang/Object"); + for (jint key : keys) { + jobjectArray arguments = env->NewObjectArray(1, object, + env->CallStaticObjectMethod(integer, value_of, key)); + env->CallObjectMethod(invalidate, invoke, companion, arguments); + if (threw(env, error)) return -2; + env->DeleteLocalRef(arguments); + } + return static_cast(keys.size()); +} + +jint JNICALL tag_composition(jlong, jlong, jlong* tag, jint, void* wanted) { + *tag = *static_cast(wanted); + return JVMTI_VISIT_OBJECTS; +} + +// Make every live composition rerun all of its composable functions. This is an +// ordinary recomposition, so everything remembered is kept. Returns -1 without Compose. +int recompose_everything(JNIEnv* env, jvmtiEnv* jvmti, jobject app_loader) { + jclass composition = load_class(env, app_loader, "androidx.compose.runtime.CompositionImpl"); + if (!composition) return -1; + jmethodID invalidate_all = env->GetMethodID(composition, "invalidateAll", "()V"); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + return -1; + } + jlong tag = 0x636f6d706f7365; // "compose" + jvmtiHeapCallbacks callbacks; + memset(&callbacks, 0, sizeof callbacks); + callbacks.heap_iteration_callback = tag_composition; + jvmti->IterateThroughHeap(0, composition, &callbacks, &tag); + jint found = 0; + jobject* objects = nullptr; + if (jvmti->GetObjectsWithTags(1, &tag, &found, &objects, nullptr) != JVMTI_ERROR_NONE) return -1; + for (jint i = 0; i < found; i++) { + jvmti->SetTag(objects[i], 0); + env->CallVoidMethod(objects[i], invalidate_all); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + return found; +} + +// An activity whose whole content is one Compose view (what setContent {} builds). +bool is_pure_compose(JNIEnv* env, jobject app_loader, jobject activity) { + jclass compose_view = load_class(env, app_loader, "androidx.compose.ui.platform.AbstractComposeView"); + if (!compose_view) return false; + jclass activity_class = env->FindClass("android/app/Activity"); + jobject content = env->CallObjectMethod( + activity, env->GetMethodID(activity_class, "findViewById", "(I)Landroid/view/View;"), + 0x01020002 /* android.R.id.content */); + jclass group = env->FindClass("android/view/ViewGroup"); + if (env->ExceptionCheck() || !content || !env->IsInstanceOf(content, group)) { + env->ExceptionClear(); + return false; + } + if (env->CallIntMethod(content, env->GetMethodID(group, "getChildCount", "()I")) != 1) + return false; + jobject child = env->CallObjectMethod( + content, env->GetMethodID(group, "getChildAt", "(I)Landroid/view/View;"), 0); + return child && env->IsInstanceOf(child, compose_view); +} + +jobject g_resources_loader = nullptr; // the loader installed by the previous swap + +// Put a freshly linked resource table in front of the app's own, through the public +// ResourcesLoader API. Contexts created later inherit the application's loaders, so +// rebuilt activities see the new resources too. +bool apply_resources(JNIEnv* env, const std::string& path, + const std::vector& activities, std::string* error) { + if (activities.empty()) { + *error = "no live activity to reach the application through"; + return false; + } + jclass file_class = env->FindClass("java/io/File"); + jobject file = env->NewObject( + file_class, env->GetMethodID(file_class, "", "(Ljava/lang/String;)V"), + env->NewStringUTF(path.c_str())); + jclass pfd_class = env->FindClass("android/os/ParcelFileDescriptor"); + jobject pfd = env->CallStaticObjectMethod( + pfd_class, + env->GetStaticMethodID(pfd_class, "open", "(Ljava/io/File;I)Landroid/os/ParcelFileDescriptor;"), + file, 0x10000000 /* MODE_READ_ONLY */); + if (threw(env, error)) return false; + jclass provider_class = env->FindClass("android/content/res/loader/ResourcesProvider"); + if (threw(env, error)) { + *error = "resource swap needs Android 11+"; + return false; + } + jobject provider = env->CallStaticObjectMethod( + provider_class, + env->GetStaticMethodID(provider_class, "loadFromApk", + "(Landroid/os/ParcelFileDescriptor;)Landroid/content/res/loader/ResourcesProvider;"), + pfd); + if (threw(env, error)) return false; + env->CallVoidMethod(pfd, env->GetMethodID(pfd_class, "close", "()V")); + if (env->ExceptionCheck()) env->ExceptionClear(); + jclass loader_class = env->FindClass("android/content/res/loader/ResourcesLoader"); + jobject loader = env->NewObject(loader_class, env->GetMethodID(loader_class, "", "()V")); + env->CallVoidMethod( + loader, + env->GetMethodID(loader_class, "addProvider", + "(Landroid/content/res/loader/ResourcesProvider;)V"), + provider); + if (threw(env, error)) return false; + + jclass context = env->FindClass("android/content/Context"); + jmethodID resources_of = env->GetMethodID(context, "getResources", "()Landroid/content/res/Resources;"); + jclass resources = env->FindClass("android/content/res/Resources"); + const char* signature = "([Landroid/content/res/loader/ResourcesLoader;)V"; + jmethodID add = env->GetMethodID(resources, "addLoaders", signature); + jmethodID remove = env->GetMethodID(resources, "removeLoaders", signature); + jclass activity = env->FindClass("android/app/Activity"); + jobject application = env->CallObjectMethod( + activities[0], env->GetMethodID(activity, "getApplication", "()Landroid/app/Application;")); + std::vector contexts = activities; + contexts.push_back(application); + jobjectArray fresh = env->NewObjectArray(1, loader_class, loader); + jobjectArray stale = + g_resources_loader ? env->NewObjectArray(1, loader_class, g_resources_loader) : nullptr; + for (jobject one : contexts) { + jobject target = env->CallObjectMethod(one, resources_of); + if (stale) env->CallVoidMethod(target, remove, stale); + env->CallVoidMethod(target, add, fresh); + if (threw(env, error)) return false; + } + if (g_resources_loader) env->DeleteGlobalRef(g_resources_loader); + g_resources_loader = env->NewGlobalRef(loader); + return true; +} + +} // namespace + +extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void*) { + std::string plan = options ? options : ""; + std::vector entries; + std::string refresh = "none"; + std::vector compose_keys; + std::string resources, helper_dex; + std::vector statics; + { + FILE* f = fopen(plan.c_str(), "r"); + if (!f) return report(plan, false, "cannot read plan " + plan); + char a[32], b[1024], c[1024]; + char line[2200]; + while (fgets(line, sizeof line, f)) { + int n = sscanf(line, "%31s %1023s %1023s", a, b, c); + if (n == 2 && !strcmp(a, "refresh")) refresh = b; + else if (n == 2 && !strcmp(a, "compose")) compose_keys.push_back(atoi(b)); + else if (n == 2 && !strcmp(a, "resources")) resources = b; + else if (n == 2 && !strcmp(a, "helper")) helper_dex = b; + else if (n == 3 && !strcmp(a, "class")) entries.push_back({b, c}); + else if (n == 3 && !strcmp(a, "statics")) statics.push_back({b, c}); + } + fclose(f); + } + if (entries.empty() && resources.empty()) return report(plan, false, "plan is empty"); + + jvmtiEnv* jvmti = nullptr; + JNIEnv* env = nullptr; + if (vm->GetEnv(reinterpret_cast(&jvmti), JVMTI_VERSION_1_2) != JNI_OK || + vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + return report(plan, false, "no JVMTI/JNI environment"); + jvmtiCapabilities caps; + memset(&caps, 0, sizeof caps); + caps.can_redefine_classes = 1; + caps.can_tag_objects = 1; + jvmtiError err = jvmti->AddCapabilities(&caps); + Extensions ext = find_extensions(jvmti); + if (err != JVMTI_ERROR_NONE) + return report(plan, false, "AddCapabilities " + error_text(jvmti, ext, err)); + + jint count = 0; + jclass* classes = nullptr; + jvmti->GetLoadedClasses(&count, &classes); + jobject loader = app_class_loader(env, jvmti, count, classes); + if (!loader) return report(plan, false, "app class loader not found"); + + for (Entry& e : entries) { + if (!read_file(e.dex_path, &e.dex)) return report(plan, false, "cannot read " + e.dex_path); + std::string signature = "L" + e.name + ";"; + for (char& ch : signature) if (ch == '.') ch = '/'; + for (jint i = 0; i < count && !e.klass; i++) { + char* sig = nullptr; + if (jvmti->GetClassSignature(classes[i], &sig, nullptr) != JVMTI_ERROR_NONE || !sig) + continue; + if (signature == sig) e.klass = classes[i]; + jvmti->Deallocate(reinterpret_cast(sig)); + } + // Not loaded yet: the app would otherwise load the stale copy from its APK later. + if (!e.klass) e.klass = load_class(env, loader, e.name); + } + + // New classes first, so redefined code can resolve them. + int added = 0; + for (Entry& e : entries) { + if (e.klass) continue; + if (!ext.add_dex_file) + return report(plan, false, "new class " + e.name + " needs a newer Android (no add-dex extension)"); + // By file, not from memory: Android 14+ refuses dex code from a writable source, + // so the host leaves these files read-only. + err = ext.add_dex_file(jvmti, loader, e.dex_path.c_str()); + if (err != JVMTI_ERROR_NONE) + return report(plan, false, "add " + e.name + " " + error_text(jvmti, ext, err)); + added++; + } + + std::vector defs; + for (Entry& e : entries) { + if (!e.klass) continue; + jvmtiClassDefinition def; + def.klass = e.klass; + def.class_byte_count = static_cast(e.dex.size()); + def.class_bytes = e.dex.data(); + defs.push_back(def); + } + bool structural = false; + if (!defs.empty()) { + // All classes go in one call: either every one is replaced or none is. + err = jvmti->RedefineClasses(static_cast(defs.size()), defs.data()); + if (err != JVMTI_ERROR_NONE && ext.structural_redefine) { + std::string first = error_text(jvmti, ext, err); + err = ext.structural_redefine(jvmti, static_cast(defs.size()), defs.data()); + structural = err == JVMTI_ERROR_NONE; + if (!structural) + return report(plan, false, "redefine " + first + " | structural " + + error_text(jvmti, ext, err)); + } else if (err != JVMTI_ERROR_NONE) { + return report(plan, false, "redefine " + error_text(jvmti, ext, err)); + } + } + + int copied = 0; + if (!statics.empty()) { + std::string error; + copied = copy_statics(env, loader, statics, &error); + if (copied < 0) return report(plan, false, "statics " + error); + } + + // Code is already swapped at this point; the UI steps need the main thread. + int recreated = 0, recomposed = 0; + bool helper_loaded = false; + if (refresh != "none" || !resources.empty()) { + if (!on_main_thread(env)) return report(plan, false, "agent was not attached on the main thread"); + std::vector activities = live_activities(env, jvmti); + std::string error; + if (!resources.empty() && !apply_resources(env, resources, activities, &error)) + return report(plan, false, "resources " + error); + jclass helper = load_class(env, loader, "hotswap.agent.HotswapState"); + if (!helper && !helper_dex.empty() && ext.add_dex_file && + ext.add_dex_file(jvmti, loader, helper_dex.c_str()) == JVMTI_ERROR_NONE) + helper = load_class(env, loader, "hotswap.agent.HotswapState"); + helper_loaded = helper != nullptr; + if (refresh == "auto") { + // Compose screens rerun their functions in place and keep all state. Other + // activities are rebuilt, with their view state saved and put back. + if (!compose_keys.empty() && invalidate_compose(env, loader, compose_keys, &error) == -2) + LOG("could not reset changed composables: %s", error.c_str()); + recomposed = recompose_everything(env, jvmti, loader); + std::vector rebuild; + for (jobject one : activities) + if (recomposed < 0 || !is_pure_compose(env, loader, one)) rebuild.push_back(one); + if (recomposed < 0) recomposed = 0; + recreated = recreate_activities(env, rebuild, helper); + } else if (refresh == "recreate") { + recreated = recreate_activities(env, activities, helper); + } + } + return report(plan, true, + "redefined=" + std::to_string(defs.size()) + " added=" + std::to_string(added) + + " structural=" + (structural ? "1" : "0") + + " statics=" + std::to_string(copied) + + " resources=" + (resources.empty() ? "0" : "1") + + " recomposed=" + std::to_string(recomposed) + + " helper=" + (helper_loaded ? "1" : "0") + + " recreated=" + std::to_string(recreated)); +} diff --git a/src/android_use/hotswap/daemon/HotswapDaemon.java b/src/android_use/hotswap/daemon/HotswapDaemon.java new file mode 100644 index 0000000..7bbf3b6 --- /dev/null +++ b/src/android_use/hotswap/daemon/HotswapDaemon.java @@ -0,0 +1,136 @@ +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.PrintStream; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; + +/** + * Keeps javac, the Kotlin compiler and d8 loaded in one JVM so a hot swap does not pay a + * JVM start per tool. Loopback only; every request must carry the token from the port + * file, which only this user can read. Exits after 20 idle minutes. + * + * Request: token, tool, argument count, arguments (strings: int length + UTF-8) + * Response: int exit code, int length, output bytes + */ +public class HotswapDaemon { + private static final Map kotlinLoaders = new HashMap<>(); + + public static void main(String[] args) throws Exception { + Path portFile = Paths.get(args[0]); + byte[] random = new byte[24]; + new SecureRandom().nextBytes(random); + StringBuilder token = new StringBuilder(); + for (byte b : random) token.append(String.format("%02x", b)); + try (ServerSocket server = new ServerSocket(0, 8, InetAddress.getLoopbackAddress())) { + server.setSoTimeout(20 * 60 * 1000); + Path temporary = Paths.get(args[0] + ".tmp"); + Files.deleteIfExists(temporary); + Files.createFile(temporary, PosixFilePermissions.asFileAttribute( + PosixFilePermissions.fromString("rw-------"))); + Files.write(temporary, (server.getLocalPort() + " " + token + "\n").getBytes()); + Files.move(temporary, portFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING); + while (true) { + try (Socket socket = server.accept()) { + serve(socket, token.toString()); + } catch (SocketTimeoutException idle) { + break; + } catch (Exception broken) { + // A bad client must not take the daemon down. + } + } + } finally { + Files.deleteIfExists(portFile); + } + } + + private static String read(DataInputStream in) throws Exception { + byte[] bytes = new byte[in.readInt()]; + in.readFully(bytes); + return new String(bytes, StandardCharsets.UTF_8); + } + + private static void serve(Socket socket, String token) throws Exception { + DataInputStream in = new DataInputStream(socket.getInputStream()); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + if (!read(in).equals(token)) return; + String tool = read(in); + String[] args = new String[in.readInt()]; + for (int i = 0; i < args.length; i++) args[i] = read(in); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + PrintStream capture = new PrintStream(buffer, true, "UTF-8"); + PrintStream oldOut = System.out, oldErr = System.err; + int code; + System.setOut(capture); + System.setErr(capture); + try { + code = run(tool, args, capture); + } catch (Throwable error) { + Throwable cause = error.getCause() != null ? error.getCause() : error; + capture.println(cause); + code = 1; + } finally { + System.setOut(oldOut); + System.setErr(oldErr); + } + byte[] output = buffer.toByteArray(); + out.writeInt(code); + out.writeInt(output.length); + out.write(output); + out.flush(); + } + + private static int run(String tool, String[] args, PrintStream capture) throws Exception { + switch (tool) { + case "ping": + return 0; + case "javac": + return javax.tools.ToolProvider.getSystemJavaCompiler().run(null, capture, capture, args); + case "d8": + com.android.tools.r8.D8.run(com.android.tools.r8.D8Command.parse( + args, com.android.tools.r8.origin.Origin.root()).build()); + return 0; + case "kotlinc": { + // args[0] is the compiler's own classpath; one cached loader per compiler. + ClassLoader loader = kotlinLoaders.get(args[0]); + if (loader == null) { + String[] entries = args[0].split(File.pathSeparator); + URL[] urls = new URL[entries.length]; + for (int i = 0; i < entries.length; i++) urls[i] = new File(entries[i]).toURI().toURL(); + loader = new URLClassLoader(urls, ClassLoader.getPlatformClassLoader()); + kotlinLoaders.put(args[0], loader); + } + String[] rest = java.util.Arrays.copyOfRange(args, 1, args.length); + Thread thread = Thread.currentThread(); + ClassLoader previous = thread.getContextClassLoader(); + thread.setContextClassLoader(loader); + try { + Class compiler = loader.loadClass("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"); + Method exec = compiler.getMethod("exec", PrintStream.class, String[].class); + Object result = exec.invoke(compiler.getDeclaredConstructor().newInstance(), capture, rest); + return (Integer) result.getClass().getMethod("getCode").invoke(result); + } finally { + thread.setContextClassLoader(previous); + } + } + default: + capture.println("unknown tool " + tool); + return 2; + } + } +} diff --git a/src/android_use/hotswap/engine.py b/src/android_use/hotswap/engine.py new file mode 100755 index 0000000..5cfb9f5 --- /dev/null +++ b/src/android_use/hotswap/engine.py @@ -0,0 +1,1021 @@ +"""Hot swap code into a running, debuggable Android app. + +Uses only the JDK, the Android SDK/NDK and (for Kotlin sources) a Kotlin compiler. +Standard library only, and nothing is printed outside main(): the MCP server calls +run_action() in process, where stdout belongs to the protocol. + + hotswap -p PROJECT status toolchain and project check; changes nothing + hotswap -p PROJECT build full build, install, launch + hotswap -p PROJECT swap push source edits into the running process + hotswap -p PROJECT watch swap on every save + hotswap -p GRADLE_ROOT gradle-setup [--module :app] [--variant Debug] + +A Gradle project needs no setup: its root (or a module directory below it) is +recognised and Gradle keeps doing the full builds, while its own compiler settings are +reused for the swaps. A plain project holds a hand-written hotswap.json (see +script/hotswap/app/hotswap.json). A swap compiles the edited files, +finds the classes whose bytes differ from what the process runs, and has a JVMTI agent +redefine them in place. Edited resources are relinked and loaded into the process the +same way. Whatever cannot be swapped (manifest, build files, hierarchy changes, a dead +process) falls back to a full build and reinstall. +""" + +import argparse +import hashlib +import json +import os +import re +import shutil +import socket +import struct +import subprocess +import sys +import time +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent # agent, helper and daemon sources live here +ABI_TRIPLES = { + "arm64-v8a": "aarch64-linux-android", + "armeabi-v7a": "armv7a-linux-androideabi", + "x86_64": "x86_64-linux-android", + "x86": "i686-linux-android", +} + + +class Fail(Exception): + def __init__(self, message, code="hotswap_failed"): + super().__init__(message) + self.code = code + + +def cache_dir(): + """Built agent, helper and daemon: outside the package, which may be read-only.""" + base = os.environ.get("ANDROID_USE_HOTSWAP_CACHE") + if not base: + state = os.environ.get("ANDROID_USE_STATE_DIR", "~/.local/share/android-use") + base = Path(state).expanduser() / "hotswap" + return Path(base) + + +def sdk_dir(): + for name in ("ANDROID_HOME", "ANDROID_SDK_ROOT"): + if os.environ.get(name): + return Path(os.environ[name]) + home = Path.home() + found = [p for p in (home / "Library/Android/sdk", home / "Android/Sdk") if p.is_dir()] + return found[0] if found else home / "Library/Android/sdk" + + +def jvmti_header(): + """The NDK has no jvmti.h; any JDK's copy will do.""" + if os.environ.get("JVMTI_H"): + return os.environ["JVMTI_H"] + homes = [os.environ.get("JAVA_HOME", ""), str(Path.home() / "Library/Java"), + "/Library/Java/JavaVirtualMachines", "/usr/lib/jvm"] + return next((str(p) for h in homes if h and Path(h).is_dir() + for p in Path(h).rglob("jvmti.h")), None) + + +def run(cmd, check=True, **kwargs): + kwargs.setdefault("timeout", 900) # e.g. adb waiting forever for an unplugged device + try: + done = subprocess.run([str(c) for c in cmd], capture_output=True, text=True, **kwargs) + except OSError as error: + raise Fail(f"cannot run {cmd[0]}: {error}", "toolchain_missing") from None + except subprocess.TimeoutExpired: + raise Fail(f"{Path(str(cmd[0])).name} timed out (device disconnected?)") from None + if check and done.returncode: + raise Fail(f"{Path(str(cmd[0])).name} failed:\n{(done.stdout + done.stderr).strip()}") + return done + + +def newest(directory): + def key(path): + return [int(n) for n in re.findall(r"\d+", path.name)] + + directory = Path(directory) + items = sorted((p for p in directory.iterdir() if p.is_dir()), key=key) if ( + directory.is_dir()) else [] + if not items: + raise Fail(f"nothing installed under {directory}", "toolchain_missing") + return items[-1] + + +class Daemon: + """Client of daemon/HotswapDaemon.java: the compilers, kept warm in one JVM.""" + + def __init__(self, d8_jar): + source = HERE / "daemon/HotswapDaemon.java" + digest = hashlib.sha1(source.read_bytes() + str(d8_jar).encode()).hexdigest()[:12] + self.dir = cache_dir() / "daemon" / digest + self.port_file = self.dir / "port" + if not (self.dir / "HotswapDaemon.class").exists(): + self.dir.mkdir(parents=True, exist_ok=True) + run(["javac", "-nowarn", "-cp", d8_jar, "-d", self.dir, source]) + try: + self.call("ping", []) + except (OSError, ValueError): + self.port_file.unlink(missing_ok=True) + with open(self.dir / "daemon.log", "ab") as log: + subprocess.Popen(["java", "-cp", f"{self.dir}{os.pathsep}{d8_jar}", "HotswapDaemon", + str(self.port_file)], stdin=subprocess.DEVNULL, stdout=log, + stderr=log, start_new_session=True) + deadline = time.time() + 15 + while not self.port_file.exists(): + if time.time() > deadline: + raise Fail("compiler daemon did not start") from None + time.sleep(0.05) + + def call(self, tool, args): + port, token = self.port_file.read_text().split() + with socket.create_connection(("127.0.0.1", int(port)), timeout=5) as link: + link.settimeout(600) + message = b"" + for text in (token, tool): + raw = text.encode() + message += struct.pack(">I", len(raw)) + raw + message += struct.pack(">I", len(args)) + for text in args: + raw = str(text).encode() + message += struct.pack(">I", len(raw)) + raw + link.sendall(message) + reply = b"" + while True: + chunk = link.recv(65536) + if not chunk: + break + reply += chunk + if len(reply) < 8: + raise ValueError("short reply from compiler daemon") + code, length = struct.unpack(">iI", reply[:8]) + return code, reply[8:8 + length].decode(errors="replace") + + +class Tools: + def __init__(self, serial, use_daemon=True): + self.sdk = sdk_dir() + self.build_tools = newest(self.sdk / "build-tools") + self.serial = serial or os.environ.get("ANDROID_SERIAL") + self.adb_path = os.environ.get("ANDROID_USE_ADB") or shutil.which("adb") or "adb" + self.use_daemon = use_daemon + self.daemon = None + self.touched = False # True once something was installed on or pushed to the device + + def invoke(self, tool, command, args): + """Run a compiler in the warm daemon, or as a fresh process when that fails.""" + if self.use_daemon: + try: + self.daemon = self.daemon or Daemon(self.build_tools / "lib/d8.jar") + code, output = self.daemon.call(tool, [str(a) for a in args]) + except (OSError, ValueError, Fail): + self.use_daemon = False + else: + if code: + raise Fail(f"{tool} failed:\n{output.strip()}", self.failure(tool)) + return + try: + run([*command, *(args[1:] if tool == "kotlinc" else args)]) + except Fail as error: + if error.code == "hotswap_failed": + error.code = self.failure(tool) + raise + + @staticmethod + def failure(tool): + return "compile_failed" if tool in ("javac", "kotlinc") else "hotswap_failed" + + def javac(self, args): + self.invoke("javac", ["javac"], args) + + def d8(self, args): + self.invoke("d8", [self.tool("d8")], args) + + def kotlin(self, cfg, args): + command = self.kotlinc(cfg) + if cfg.get("kotlin_compiler_classpath"): + compiler, extra = cfg["kotlin_compiler_classpath"], [] + else: + home = Path(command[-1]).resolve().parent.parent + compiler = sorted(str(p) for p in (home / "lib").glob("*.jar") if re.match( + r"kotlin-(compiler|stdlib|reflect|script-runtime)\.jar|kotlinx-coroutines-core|" + r"trove4j|annotations-", p.name)) + extra = ["-kotlin-home", str(home)] + self.invoke("kotlinc", command, [os.pathsep.join(compiler), *extra, *args]) + + def tool(self, name): + return self.build_tools / name + + def android_jar(self, cfg): + if cfg.get("boot"): + return Path(cfg["boot"][0]) + return newest(self.sdk / "platforms") / "android.jar" + + def kotlinc(self, cfg): + """Command prefix that runs the Kotlin JVM compiler.""" + if cfg.get("kotlin_compiler_classpath"): + return ["java", "-cp", os.pathsep.join(cfg["kotlin_compiler_classpath"]), + "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"] + found = os.environ.get("KOTLINC") or shutil.which("kotlinc") or ( + "/Applications/Android Studio.app/Contents/plugins/Kotlin/kotlinc/bin/kotlinc") + if not Path(found).exists(): + raise Fail("Kotlin sources need a compiler: set KOTLINC", "toolchain_missing") + # Android Studio ships its launcher script without the executable bit. + return [found] if os.access(found, os.X_OK) else ["bash", found] + + def kotlin_stdlib(self, cfg): + return Path(self.kotlinc(cfg)[-1]).resolve().parent.parent / "lib/kotlin-stdlib.jar" + + def adb(self, *args, check=True, **kwargs): + kwargs.setdefault("timeout", 180) + return run([self.adb_path, *(["-s", self.serial] if self.serial else []), *args], + check, **kwargs) + + def shell(self, command, check=True): + return self.adb("shell", command, check=check).stdout.strip() + + def helper(self, cfg): + """Build the in-app helper class as a dex; return (path, content hash).""" + sources = sorted((HERE / "helper").rglob("*.java")) + digest = hashlib.sha1(b"".join(p.read_bytes() for p in sources)).hexdigest()[:12] + out = cache_dir() / "helper" / digest + if not (out / "classes.dex").exists(): + (out / "classes").mkdir(parents=True, exist_ok=True) + android_jar = self.android_jar(cfg) + self.javac(["-nowarn", "-Xlint:-options", "-proc:none", "-source", "8", "-target", "8", + "-bootclasspath", android_jar, "-d", out / "classes", *sources]) + self.d8(["--lib", android_jar, "--min-api", "26", "--output", out, + *(out / "classes").rglob("*.class")]) + return out / "classes.dex", digest + + def agent(self): + """Build the agent for the device ABI; return (path, content hash).""" + abi = self.shell("getprop ro.product.cpu.abi") + source = HERE / "agent/agent.cpp" + if abi not in ABI_TRIPLES: + raise Fail(f"unsupported device ABI {abi!r}", "device_error") + version = hashlib.sha1(source.read_bytes()).hexdigest()[:12] + out = cache_dir() / "agent" / version / abi / "libhotswap.so" + if not out.exists(): + out.parent.mkdir(parents=True, exist_ok=True) + ndk = newest(self.sdk / "ndk") + cxx = newest(ndk / "toolchains/llvm/prebuilt") / "bin/clang++" + # Take jvmti.h from a JDK but keep the NDK's own jni.h. + header = jvmti_header() + if not header: + raise Fail("jvmti.h not found in any JDK; set JVMTI_H", "toolchain_missing") + shutil.copy(header, out.parent / "jvmti.h") + # Static libc++: the app process has no libc++_shared.so to resolve against. + run([cxx, f"--target={ABI_TRIPLES[abi]}26", "-std=c++17", "-shared", "-fPIC", "-O2", + "-static-libstdc++", "-I", out.parent, source, "-llog", "-o", out]) + return out, hashlib.sha256(out.read_bytes()).hexdigest()[:12] + + +# ---------------------------------------------------------------- class files + +def class_abi(data): + """Hash of what other classes can depend on: hierarchy and non-private members.""" + def u2(at): + return struct.unpack_from(">H", data, at)[0] + + count, pos, pool, index = u2(8), 10, {}, 1 + while index < count: + tag = data[pos] + if tag == 1: + length = u2(pos + 1) + pool[index] = data[pos + 3:pos + 3 + length] + pos += 3 + length + elif tag in (3, 4): + pool[index] = data[pos + 1:pos + 5] + pos += 5 + elif tag in (5, 6): + pool[index] = data[pos + 1:pos + 9] + pos += 9 + index += 1 + elif tag in (7, 8, 16, 19, 20): + pool[index] = u2(pos + 1) + pos += 3 + elif tag in (9, 10, 11, 12, 17, 18): + pos += 5 + elif tag == 15: + pos += 4 + else: + raise Fail(f"unknown constant pool tag {tag}") + index += 1 + + def name(at): + value = pool.get(at) + return pool.get(value, b"") if isinstance(value, int) else value + + shape = [u2(pos), name(u2(pos + 2)), name(u2(pos + 4))] + interfaces = u2(pos + 6) + shape.append(sorted(name(u2(pos + 8 + 2 * i)) for i in range(interfaces))) + pos += 8 + 2 * interfaces + for _ in range(2): # fields, then methods + members = [] + total = u2(pos) + pos += 2 + for _ in range(total): + flags, member, descriptor, attributes = (u2(pos + i) for i in (0, 2, 4, 6)) + pos += 8 + constant = None + for _ in range(attributes): + length = struct.unpack_from(">I", data, pos + 2)[0] + if pool.get(u2(pos)) == b"ConstantValue": # inlined into callers by javac + constant = name(u2(pos + 6)) + pos += 6 + length + if not flags & 0x0002: # private members are invisible to other classes + members.append((flags, pool[member], pool[descriptor], constant)) + shape.append(sorted(members, key=repr)) + return hashlib.sha1(repr(shape).encode()).hexdigest() + + +def compose_shape(data): + """(calls, keys) for one class file: every call it makes on the Compose Composer, in + order, and the group keys of its restartable composable functions. + + The calls decide where remembered values live. If an edit leaves them unchanged, + the function can simply run again over its existing state; if not, its groups + (the keys) have to be reset, or old values would be read back in the wrong places. + """ + def u2(at): + return struct.unpack_from(">H", data, at)[0] + + count, pos, index = u2(8), 10, 1 + utf, classes, pairs, methods, integers = {}, {}, {}, {}, {} + calls, keys = [], [] + while index < count: + tag = data[pos] + if tag == 1: + length = u2(pos + 1) + utf[index] = data[pos + 3:pos + 3 + length] + pos += 3 + length + elif tag == 3: + integers[index] = struct.unpack_from(">i", data, pos + 1)[0] + pos += 5 + elif tag == 4: + pos += 5 + elif tag in (5, 6): + pos += 9 + index += 1 + elif tag in (7, 8, 16, 19, 20): + if tag == 7: + classes[index] = u2(pos + 1) + pos += 3 + elif tag in (9, 10, 11, 12, 17, 18): + if tag == 11: + methods[index] = (u2(pos + 1), u2(pos + 3)) + elif tag == 12: + pairs[index] = u2(pos + 1) + pos += 5 + elif tag == 15: + pos += 4 + else: + return calls, keys + index += 1 + targets = {struct.pack(">H", i): utf.get(pairs.get(pair)) for i, (owner, pair) in methods.items() + if utf.get(classes.get(owner)) == b"androidx/compose/runtime/Composer"} + at = data.find(b"\xb9", pos) + while at != -1: # invokeinterface 0, maybe after ldc / ldc_w + name = targets.get(data[at + 1:at + 3]) + if name and data[at + 4] == 0: + constant = None + if data[at - 2] == 0x12 and data[at - 1] in integers: + constant = integers[data[at - 1]] + elif data[at - 3] == 0x13 and u2(at - 2) in integers: + constant = integers[u2(at - 2)] + calls.append((name, constant)) + if name == b"startRestartGroup" and constant is not None: + keys.append(constant) + at = data.find(b"\xb9", at + 1) + return calls, keys + + +def class_files(root): + root = Path(root) + return {str(p.relative_to(root))[:-6].replace(os.sep, "."): p for p in root.rglob("*.class")} + + +def digests(root): + return {n: hashlib.sha1(p.read_bytes()).hexdigest() for n, p in class_files(root).items()} + + +# -------------------------------------------------------------------- project + +class Project: + def __init__(self, directory, tools): + self.dir = Path(directory).resolve() + self.tools = tools + self.work = self.dir / "build/hotswap" + self.current = self.work / "current" # classes matching the sources + self.state_path = self.work / "state.json" + self.gradle_info = self.dir / "build/hotswap-gradle.json" + # Resource IDs of the installed build. Relinking must keep them: the new table is + # laid over the installed one, and an ID meaning two different resources lets + # the system pick the old entry whenever its locale or density matches better. + self.ids = self.dir / "build/hotswap-ids.txt" + self.load() + + def load(self): + self.config_path = self.dir / "hotswap.json" + if not self.config_path.exists(): + self.config_path = self.dir / AUTO_CONFIG # written by locate() for Gradle + try: + self.cfg = json.loads(self.config_path.read_text()) + except (OSError, ValueError): + raise Fail(f"{self.dir} has no usable hotswap.json and is not a Gradle project", + "project_invalid") from None + if self.cfg.get("type") == "gradle" and self.gradle_info.exists(): + self.cfg.update(json.loads(self.gradle_info.read_text())) + self.package = self.cfg.get("package") + self.min_api = str(self.cfg.get("min_api", 26)) + + def activity(self): + if self.cfg.get("activity"): + return f"{self.package}/{self.cfg['activity']}" + found = self.tools.shell(f"cmd package resolve-activity --brief {self.package}") + return found.splitlines()[-1] + + def path(self, value): + return (self.dir / value).resolve() + + def sources(self): + files = [] + for root in self.cfg["sources"]: + for suffix in ("*.java", "*.kt"): + files += [p for p in self.path(root).rglob(suffix)] + return sorted(set(files)) + + def other_inputs(self): + """Files that can only take effect through a reinstall.""" + files = [self.config_path] + manifests = self.cfg.get("manifests") or [self.cfg["manifest"]] + for name in [*manifests, *self.cfg.get("build_files", [])]: + if self.path(name).is_file(): + files.append(self.path(name)) + return files + + def res_inputs(self): + return [p for root in self.cfg.get("res", []) for p in self.path(root).rglob("*") + if p.is_file()] + + def snapshot(self): + stat = lambda p: [p.stat().st_mtime_ns, p.stat().st_size] # noqa: E731 + return {"sources": {str(p): stat(p) for p in self.sources()}, + "res": {str(p): stat(p) for p in self.res_inputs()}, + "other": {str(p): stat(p) for p in self.other_inputs()}} + + def state(self): + try: + return json.loads(self.state_path.read_text()) + except (OSError, ValueError): + return {} + + def save(self, state): + self.state_path.write_text(json.dumps(state)) + + def classpath(self): + """Libraries, plus (Gradle) classes Gradle generates that no source here produces.""" + entries = [*self.cfg.get("classpath", []), *self.cfg.get("classes_dirs", [])] + return [str(self.path(e)) for e in entries if self.path(e).exists()] + + def boot(self): + if self.cfg.get("boot"): + return self.cfg["boot"] + return [str(self.tools.android_jar(self.cfg)), str(self.tools.tool("core-lambda-stubs.jar"))] + + def compile(self, kotlin, java, out, extra_classpath=()): + """Compile the given files into `out`, resolving the rest from classes on disk.""" + out.mkdir(parents=True, exist_ok=True) + classpath = [str(out), *map(str, extra_classpath), *self.classpath()] + if kotlin: + self.tools.kotlin(self.cfg, [ + "-no-jdk", "-nowarn", *self.cfg.get("kotlinc_args", ["-jvm-target", "1.8"]), + "-cp", os.pathsep.join(classpath + self.boot()), "-d", out, + *kotlin, *java]) # Java files are only read here, for cross references + if java: + self.tools.javac([ + "-nowarn", "-Xlint:-options", "-proc:none", "-encoding", "UTF-8", + *self.cfg.get("javac_args", ["-source", "8", "-target", "8"]), + "-bootclasspath", os.pathsep.join(self.boot()), + "-cp", os.pathsep.join(classpath), "-d", out, *java]) + + # ------------------------------------------------------------ full build + + def build(self, reason=None): + started = time.time() + self.tools.touched = True + if self.cfg.get("type") == "gradle": + self.build_gradle() + else: + self.build_simple() + state = {"snapshot": self.snapshot(), "apk": digests(self.current), "pid": None, + "live": None, "res_dirty": False, "inline": self.inline_files(self.sources())} + self.save(state) + self.tools.shell(f"am start -n {self.activity()}") + result = {"result": "installed", "package": self.package, + "seconds": round(time.time() - started, 2)} + if reason: + result["reason"] = reason + return result + + def build_gradle(self): + cfg = self.cfg + variant = cfg["variant"] + self.gradle_info.parent.mkdir(parents=True, exist_ok=True) + env = dict(os.environ) + if self.tools.serial: + env["ANDROID_SERIAL"] = self.tools.serial + # One Gradle run installs the app and re-exports its compile settings, so the + # swaps always use the classpath and compiler flags of the build just installed. + run([*self.gradle(), f"-Dhotswap.out={self.gradle_info}", + f"{cfg['module']}:install{variant}", f"{cfg['module']}:hotswapInfo"], + cwd=self.dir, env=env) + self.load() + self.record_ids(self.linked_resources()) + shutil.rmtree(self.work, ignore_errors=True) + # Baseline = every source compiled by this tool, not Gradle's class files: later + # diffs then compare like with like and only real edits show up as changes. + sources = self.sources() + self.compile([p for p in sources if p.suffix == ".kt"], + [p for p in sources if p.suffix == ".java"], self.current) + self.extract_r_classes() + + def gradle(self): + cfg = self.cfg + return [*cfg["gradle"], "-q", "-I", HERE / "hotswap.init.gradle", + f"-Dhotswap.module={cfg['module']}", f"-Dhotswap.variant={cfg['variant']}"] + + def linked_resources(self): + """The resource package Gradle linked last.""" + linked = sorted((Path(self.cfg["module_dir"]) / "build/intermediates").rglob("*.ap_"), + key=lambda p: p.stat().st_mtime) + if not linked: + raise Fail("Gradle produced no linked resource package (*.ap_)") + return linked[-1] + + def record_ids(self, package): + """Write the resource IDs of a linked package in aapt2's --stable-ids format.""" + dump = run([self.tools.tool("aapt2"), "dump", "resources", package]).stdout + name = re.search(r"Package name=(\S+) id=7f", dump) + if not name: + raise Fail(f"no application resources in {package}") + entries = re.findall(r"resource (0x7f[0-9a-f]{6}) (\S+)", dump) + self.ids.write_text("".join(f"{name.group(1)}:{entry} = {number}\n" + for number, entry in entries)) + + def r_jars(self): + return [Path(p) for p in self.cfg.get("classpath", []) if Path(p).name == "R.jar"] + + def extract_r_classes(self): + """Gradle keeps R classes in R.jar, not in sources; track them like compiled ones.""" + for jar in self.r_jars(): + if jar.exists(): + with zipfile.ZipFile(jar) as archive: + archive.extractall(self.current) + + def build_simple(self): + tools, work = self.tools, self.work + libs_cache = self.dir / "build/hotswap-libs" + shutil.rmtree(work, ignore_errors=True) + (work / "gen").mkdir(parents=True) + android_jar = tools.android_jar(self.cfg) + self.link_resources(work / "unsigned.apk") + + sources = self.sources() + sorted((work / "gen").rglob("*.java")) + kotlin = [p for p in sources if p.suffix == ".kt"] + java = [p for p in sources if p.suffix == ".java"] + self.compile(kotlin, java, self.current) + + libs = [Path(p) for p in self.classpath()] + if kotlin: + libs.append(tools.kotlin_stdlib(self.cfg)) + dex_dirs = [] + for lib in libs: # library dex is cached: it only changes with the jar + target = libs_cache / hashlib.sha1(lib.read_bytes()).hexdigest()[:16] + if not target.exists(): + target.mkdir(parents=True) + run([tools.tool("d8"), "--lib", android_jar, "--min-api", self.min_api, + "--output", target, lib]) + dex_dirs.append(target) + (work / "dex").mkdir() + run([tools.tool("d8"), "--lib", android_jar, "--min-api", self.min_api, + *[a for lib in libs for a in ("--classpath", lib)], + "--output", work / "dex", *class_files(self.current).values()]) + with zipfile.ZipFile(work / "unsigned.apk", "a", zipfile.ZIP_DEFLATED) as apk: + dex_files = [p for d in [work / "dex", *dex_dirs] for p in sorted(d.glob("*.dex"))] + for index, dex in enumerate(dex_files): + apk.write(dex, "classes.dex" if index == 0 else f"classes{index + 1}.dex") + run([tools.tool("zipalign"), "-f", "4", work / "unsigned.apk", work / "aligned.apk"]) + keystore = self.dir / "build/debug.keystore" + if not keystore.exists(): + run(["keytool", "-genkeypair", "-keystore", keystore, "-storepass", "android", + "-keypass", "android", "-alias", "hotswap", "-keyalg", "RSA", "-keysize", "2048", + "-validity", "10000", "-dname", "CN=hotswap"]) + run([tools.tool("apksigner"), "sign", "--ks", keystore, "--ks-pass", "pass:android", + "--out", work / "app.apk", work / "aligned.apk"]) + tools.adb("install", "-r", "-t", work / "app.apk") + + def link_resources(self, out, keep_ids=False): + """Plain project: compile and link resources into `out`, regenerating R.java.""" + tools, work = self.tools, self.work + fresh = self.ids.with_suffix(".new") + link = [tools.tool("aapt2"), "link", "-o", out, "-I", tools.android_jar(self.cfg), + "--manifest", self.path(self.cfg["manifest"]), "--java", work / "gen", + "--auto-add-overlay", "--emit-ids", fresh] + if keep_ids and self.ids.exists(): + link += ["--stable-ids", self.ids] + for index, root in enumerate(self.cfg.get("res", [])): + if self.path(root).is_dir(): + run([tools.tool("aapt2"), "compile", "--dir", self.path(root), + "-o", work / f"res{index}.zip"]) + link.append(work / f"res{index}.zip") + run(link) + fresh.replace(self.ids) + + def relink_resources(self): + """Link the edited resources into work/resources.apk; True if the R classes changed.""" + out = self.work / "resources.apk" + if self.cfg.get("type") != "gradle": + generated = lambda: {p: p.read_bytes() for p in (self.work / "gen").rglob("*.java")} # noqa: E731 + before = generated() + self.link_resources(out, keep_ids=True) + return before != generated() + cfg = self.cfg + digest = lambda: [hashlib.sha1(p.read_bytes()).hexdigest() # noqa: E731 + for p in self.r_jars() if p.exists()] + before = digest() + run([*self.gradle(), f"-Dhotswap.stableIds={self.ids}", + f"{cfg['module']}:process{cfg['variant']}Resources"], cwd=self.dir) + linked = self.linked_resources() + self.record_ids(linked) # now also covers resources added by this edit + shutil.copy(linked, out) + if before == digest(): + return False + self.extract_r_classes() + return True + + # ------------------------------------------------------------------ swap + + @staticmethod + def inline_files(files): + """Kotlin files declaring inline functions: their bodies are copied into callers.""" + return [str(p) for p in files + if p.suffix == ".kt" and re.search(r"\binline\b", p.read_text(errors="ignore"))] + + def swap(self, refresh="auto"): + started = time.time() + state = self.state() + if not state.get("snapshot"): + return self.build("no previous build") + now, before = self.snapshot(), state["snapshot"] + if now["other"] != before["other"]: + return self.build("manifest or build configuration changed") + res_changed = now.get("res") != before.get("res") + if set(before["sources"]) - set(now["sources"]): + return self.build("a source file was deleted") + changed = [Path(p) for p, stamp in now["sources"].items() + if before["sources"].get(p) != stamp] + + pid = self.tools.shell(f"pidof {self.package}", check=False) + if not pid: + return self.build("the app is not running") + r_changed = False + if res_changed: + r_changed = self.relink_resources() + state["res_dirty"] = True + if changed or r_changed: + # New resource IDs are constants compiled into every class that uses R. + self.recompile(changed, state, r_changed) + if changed or res_changed: + state["snapshot"] = now + state["inline"] = sorted(set(state.get("inline", [])) | set(self.inline_files(changed))) + self.save(state) + + # A restarted process runs the installed APK again: earlier swaps are gone. + same_process = state.get("pid") == pid and state.get("live") + live = state["live"] if same_process else state["apk"] + latest = digests(self.current) + names = sorted(n for n, digest in latest.items() if live.get(n) != digest) + resources = self.work / "resources.apk" + if not (res_changed or (not same_process and state.get("res_dirty"))): + resources = None + if not names and not resources: + return {"result": "unchanged", "package": self.package} + files = class_files(self.current) + verdict = self.push([files[n] for n in names], refresh, resources) + if not verdict.startswith("OK"): + return self.build(f"swap refused ({verdict})") + state.update(pid=pid, live=latest) + self.save(state) + return {"result": "swapped", "package": self.package, "class_count": len(names), + "classes": names[:40], "resources": bool(resources), "verdict": verdict, + "applied": {k: int(v) for k, v in re.findall(r"(\w+)=(\d+)", verdict)}, + "seconds": round(time.time() - started, 2)} + + def pending(self): + """What the next swap would do, without doing it.""" + state = self.state() + if not state.get("snapshot"): + return {"built": False, "next_swap": "full build (no previous build)"} + now, before = self.snapshot(), state["snapshot"] + changed = sorted(p for kind in ("sources", "res") for p, stamp in now[kind].items() + if before.get(kind, {}).get(p) != stamp) + report = {"built": True, "changed_files": len(changed), "changed": changed[:20]} + if now["other"] != before["other"]: + report["next_swap"] = "full build (manifest or build configuration changed)" + elif set(before["sources"]) - set(now["sources"]): + report["next_swap"] = "full build (a source file was deleted)" + else: + report["next_swap"] = "swap in place" if changed else "nothing to do" + return report + + def recompile(self, changed, state, everything_first=False): + patch = self.work / "patch" + shutil.rmtree(patch, ignore_errors=True) + files = class_files(self.current) + before = {n: class_abi(p.read_bytes()) for n, p in files.items()} + everything = self.sources() + sorted((self.work / "gen").rglob("*.java")) + wide = everything_first or any( + str(p) in state.get("inline", []) for p in changed) or bool(self.inline_files(changed)) + for _ in ("narrow", "wide"): + chosen = everything if wide else changed + shutil.rmtree(patch, ignore_errors=True) + self.compile([p for p in chosen if p.suffix == ".kt"], + [p for p in chosen if p.suffix == ".java"], patch, [self.current]) + # A changed signature, constant or hierarchy can break classes that were not + # recompiled, so recompile everything once and let the byte diff pick. + abi_changed = any(before.get(n) != class_abi(p.read_bytes()) + for n, p in class_files(patch).items() if n in before) + if wide or not abi_changed: + break + wide = True + self.reset_keys = set() + for name, path in class_files(patch).items(): + new = path.read_bytes() + if b"androidx/compose/runtime/Composer" not in new or name not in files: + continue + old_calls, old_keys = compose_shape(files[name].read_bytes()) + new_calls, new_keys = compose_shape(new) + if old_calls != new_calls: + self.reset_keys.update(old_keys, new_keys) + shutil.copytree(patch, self.current, dirs_exist_ok=True) + + def push(self, classes, refresh, resources=None): + tools, work = self.tools, self.work + merged, stage = work / "swap-merged", work / "swap-stage" + for directory in (merged, stage): + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir(parents=True) + android_jar = tools.android_jar(self.cfg) + common = ["--lib", android_jar, "--min-api", self.min_api] + # Pass 1 desugars (lambdas become extra classes); pass 2 splits to one class per + # dex, which is the only form ART accepts for redefinition. + split = work / "swap-split" + shutil.rmtree(split, ignore_errors=True) + split.mkdir() + if classes: + tools.d8([*common, "--classpath", self.current, + *[a for jar in self.classpath() for a in ("--classpath", jar)], + "--output", merged, *classes]) + tools.d8([*common, "--no-desugaring", "--file-per-class", "--output", split, + *sorted(merged.glob("*.dex"))]) + + remote = f"/data/data/{self.package}/code_cache/hotswap" + plan = [f"refresh {refresh}"] + for index, dex in enumerate(sorted(split.rglob("*.dex"))): + name = str(dex.relative_to(split))[:-4].replace(os.sep, ".") + shutil.copy(dex, stage / f"{index}.dex") + plan.append(f"class {name} {remote}/{index}.dex") + # R classes hold resource IDs in static fields that redefinition leaves stale. + if re.search(r"(^|\.)R(\$\w+)?$", name): + plan.append(f"statics {name} {remote}/{index}.dex") + if resources: + shutil.copy(resources, stage / "resources.apk") + plan.append(f"resources {remote}/resources.apk") + if refresh == "auto": + plan += [f"compose {key}" for key in sorted(getattr(self, "reset_keys", ()))] + helper, helper_digest = tools.helper(self.cfg) + helper_remote = f"/data/data/{self.package}/code_cache/hotswap-helper-{helper_digest}.dex" + plan.append(f"helper {helper_remote}") + (stage / "plan.txt").write_text("\n".join(plan) + "\n") + + agent, digest = tools.agent() + tools.touched = True + package = self.package + base = "/data/local/tmp/hotswap" + staging = f"{base}/{package}-{int(time.time() * 1000)}" + pushed_agent = f"{base}/agent-{digest}.so" + pushed_helper = f"{base}/helper-{helper_digest}.dex" + # The agent stays mapped in the app after its first attach; overwriting it in + # place would corrupt the running code, so it is copied once per content hash. + agent_remote = f"/data/data/{package}/code_cache/hotswap-agent-{digest}.so" + tools.adb("push", stage, staging) + # One device round trip: install the agent if missing, copy the plan and dex + # files into the app (read-only: Android 14+ refuses code from a writable + # file), attach, and wait for the agent's verdict. + script = f""" +if ! run-as {package} ls {agent_remote} {helper_remote} >/dev/null 2>&1; then + [ -f {pushed_agent} ] && [ -f {pushed_helper} ] || {{ echo NEED_AGENT; exit; }} + chmod a+rx {base}; chmod a+r {pushed_agent} {pushed_helper} + run-as {package} sh -c '[ -f {agent_remote} ] || cp {pushed_agent} {agent_remote}; [ -f {helper_remote} ] || {{ cp {pushed_helper} {helper_remote} && chmod 444 {helper_remote}; }}' || {{ echo FAIL cannot install the agent; exit; }} +fi +chmod a+rx {base}; chmod -R a+rX {staging} +run-as {package} sh -c 'rm -rf {remote} && mkdir -p {remote} && cp {staging}/* {remote}/ && chmod 444 {remote}/*' || {{ echo FAIL cannot copy into the app; exit; }} +rm -rf {staging} +error=$(am attach-agent {package} {agent_remote}={remote}/plan.txt 2>&1) || {{ echo "FAIL attach: $error" | head -1; exit; }} +i=0 +while [ $i -lt 160 ]; do + run-as {package} cat {remote}/plan.txt.result 2>/dev/null && exit + sleep 0.05; i=$((i+1)) +done +echo "FAIL the agent did not report (not debuggable, or attach blocked?)" +""" + verdict = tools.shell(script, check=False) + if verdict == "NEED_AGENT": + tools.adb("push", agent, pushed_agent) + tools.adb("push", helper, pushed_helper) + verdict = tools.shell(script, check=False) + return verdict.splitlines()[0] if verdict else "FAIL no answer from the device" + +AUTO_CONFIG = "build/hotswap-config.json" + + +def locate(directory, module=None, variant=None, gradle=None): + """Project root for `directory`: the nearest hotswap.json, else the Gradle root. + + A Gradle root gets its settings in build/, not in the project's own files; pointing + at a module directory selects that module. + """ + directory = Path(directory).expanduser().resolve() + if not directory.is_dir(): + raise Fail(f"{directory} is not a directory", "project_invalid") + for root in (directory, *directory.parents): + if (root / "hotswap.json").is_file(): + return root + if any((root / name).is_file() for name in ("settings.gradle", "settings.gradle.kts")): + break + else: + raise Fail(f"{directory}: no hotswap.json and no Gradle settings file here or above", + "project_invalid") + path = root / AUTO_CONFIG + try: + saved = json.loads(path.read_text()) + except (OSError, ValueError): + saved = {} + inferred = ":" + ":".join(directory.relative_to(root).parts) if directory != root else None + wrapper = root / "gradlew" + launcher = gradle or (str(wrapper) if wrapper.exists() else shutil.which("gradle")) + if not launcher and not saved.get("gradle"): + raise Fail("no ./gradlew in the project and no gradle on PATH", "toolchain_missing") + variant = variant or saved.get("variant") or "Debug" + wanted = {"type": "gradle", "module": module or inferred or saved.get("module") or ":app", + "variant": variant[:1].upper() + variant[1:], + "gradle": [launcher] if gradle or not saved.get("gradle") else saved["gradle"]} + if wanted != saved: # a new module or variant: the changed file forces a full build + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(wanted, indent=2) + "\n") + return root + + +def toolchain(): + """Host tools a swap needs; nothing is built or started.""" + sdk = sdk_dir() + + def latest(sub): + try: + return newest(sdk / sub) + except Fail: + return None + + build_tools, platform, ndk = latest("build-tools"), latest("platforms"), latest("ndk") + agents = cache_dir() / "agent" + report = { + "sdk": str(sdk) if sdk.is_dir() else None, + "build_tools": build_tools.name if build_tools else None, + "platform": platform.name if platform else None, + "ndk": ndk.name if ndk else None, + "javac": shutil.which("javac"), + "java": shutil.which("java"), + "adb": os.environ.get("ANDROID_USE_ADB") or shutil.which("adb"), + "agent_built_for": sorted({p.parent.name for p in agents.rglob("libhotswap.so")}), + } + missing = [text for ok, text in ( + (report["sdk"], "Android SDK (set ANDROID_HOME)"), + (build_tools, "SDK build-tools (d8, aapt2)"), + (platform, "an SDK platform (android.jar)"), + (report["javac"] and report["java"], "a JDK on PATH (java, javac)"), + (report["adb"], "adb"), + ) if not ok] + if not report["agent_built_for"]: # only needed to compile the agent once per ABI + if not ndk: + missing.append("Android NDK (to build the agent once)") + if not jvmti_header(): + missing.append("jvmti.h from a JDK (set JAVA_HOME or JVMTI_H)") + report.update(missing=missing, ready=not missing) + return report + + +def run_action(action, project, serial=None, refresh="auto", module=None, variant=None, + gradle=None, use_daemon=True, tools=None): + """One call for agents: `status`, `swap` or `build`. Returns a dict, raises Fail. + + Pass a Tools instance to learn (tools.touched) whether the device was changed + before a failure. + """ + if action == "status": + report = {"action": "status", "toolchain": toolchain()} + root = locate(project, module, variant, gradle) + report["project"] = str(root) + if report["toolchain"]["build_tools"]: + target = Project(root, tools or Tools(serial, use_daemon)) + report.update(type=target.cfg.get("type", "plain"), package=target.package, + config=str(target.config_path), **target.pending()) + if target.package and report["toolchain"]["adb"]: + try: + pid = target.tools.shell(f"pidof {target.package}", check=False) + report["running"] = bool(pid) + except Fail as error: + report["device_error"] = str(error) + return report + root = locate(project, module, variant, gradle) + target = Project(root, tools or Tools(serial, use_daemon)) + result = target.build() if action == "build" else target.swap(refresh) + return {"action": action, "project": str(root), **result} + + +def describe(result): + """The dict from run_action as the lines the command line prints.""" + lines = [] + if result.get("reason"): + lines.append(f"reinstall: {result['reason']}") + if result["result"] == "installed": + lines.append(f"built, installed and launched {result['package']} " + f"in {result['seconds']:.1f}s") + elif result["result"] == "unchanged": + lines.append("nothing to swap") + else: + what = f"{result['class_count']} class(es)" + ( + " + resources" if result["resources"] else "") + lines.append(f"swapped {what} in {result['seconds']:.2f}s: {result['verdict']}") + return "\n".join(lines) + + +def main(default_project=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("-p", "--project", default=default_project, required=not default_project) + parser.add_argument("-s", "--serial") + parser.add_argument("--refresh", choices=["auto", "recreate", "none"], default="auto", + help="after a swap: auto = recompose Compose UI in place and rebuild " + "other activities with their saved view state (default); " + "recreate = rebuild every activity; none = leave the UI alone") + parser.add_argument("--no-daemon", action="store_true", + help="run each compiler as a fresh process instead of the warm daemon") + parser.add_argument("--module", help="Gradle module path (default :app)") + parser.add_argument("--variant", help="Gradle build variant (default Debug)") + parser.add_argument("--gradle", help="Gradle launcher (default ./gradlew)") + parser.add_argument("command", choices=["status", "build", "swap", "watch", "gradle-setup"]) + args = parser.parse_args() + + def act(action): + return run_action(action, args.project, args.serial, args.refresh, args.module, + args.variant, args.gradle, not args.no_daemon) + + try: + if args.command == "gradle-setup": + root = Path(args.project).resolve() + wrapper = root / "gradlew" + gradle = args.gradle or (str(wrapper) if wrapper.exists() else shutil.which("gradle")) + if not gradle: + raise Fail("no ./gradlew and no gradle on PATH: pass --gradle") + (root / "hotswap.json").write_text(json.dumps( + {"type": "gradle", "module": args.module or ":app", + "variant": args.variant or "Debug", "gradle": [gradle]}, indent=2) + "\n") + print(f"wrote {root / 'hotswap.json'}; next: build") + elif args.command == "status": + print(json.dumps(act("status"), indent=2)) + elif args.command in ("build", "swap"): + print(describe(act(args.command))) + else: + print("watching for saves; Ctrl-C to stop") + project = Project(locate(args.project, args.module, args.variant, args.gradle), + Tools(args.serial, not args.no_daemon)) + seen = None + while True: + snapshot = project.snapshot() + if snapshot != seen: + seen = snapshot + if snapshot != project.state().get("snapshot"): + try: + print(describe(project.swap(args.refresh)), flush=True) + except Fail as error: # e.g. a compile error: wait for the next save + print(error, flush=True) + time.sleep(0.3) + except Fail as error: + sys.exit(str(error)) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/src/android_use/hotswap/helper/hotswap/agent/HotswapState.java b/src/android_use/hotswap/helper/hotswap/agent/HotswapState.java new file mode 100644 index 0000000..96d0df9 --- /dev/null +++ b/src/android_use/hotswap/helper/hotswap/agent/HotswapState.java @@ -0,0 +1,153 @@ +package hotswap.agent; + +import android.app.Activity; +import android.app.Application; +import android.content.Context; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.WindowInsets; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import java.util.ArrayList; +import java.util.List; + +/** + * Loaded into the app by the hot swap agent. Rebuilds an activity and puts back the view + * state the platform does not restore by itself: scroll offsets (which restoring focus + * otherwise overrides), the text of input fields that have no ID, and an open keyboard. + */ +public final class HotswapState implements Application.ActivityLifecycleCallbacks { + private static final class Entry { + String path; + String type; + int scrollX, scrollY, selection; + CharSequence text; + } + + private final Application application; + private final String activityClass; + private final List entries = new ArrayList<>(); + private boolean keyboardShown; + private final Handler handler = new Handler(Looper.getMainLooper()); + + private HotswapState(Activity activity) { + application = activity.getApplication(); + activityClass = activity.getClass().getName(); + View root = activity.getWindow().getDecorView(); + capture(root, ""); + if (Build.VERSION.SDK_INT >= 30) { + WindowInsets insets = root.getRootWindowInsets(); + keyboardShown = insets != null && insets.isVisible(WindowInsets.Type.ime()); + } + } + + /** Called by the agent on the main thread in place of Activity.recreate(). */ + public static void recreate(Activity activity) { + final HotswapState state = new HotswapState(activity); + state.application.registerActivityLifecycleCallbacks(state); + // Never linger if the rebuilt activity does not come back. + state.handler.postDelayed(new Runnable() { + @Override + public void run() { + state.application.unregisterActivityLifecycleCallbacks(state); + } + }, 10000); + activity.recreate(); + } + + private void capture(View view, String path) { + boolean unsavedText = view instanceof EditText && view.getId() == View.NO_ID; + if (view.getScrollX() != 0 || view.getScrollY() != 0 || unsavedText) { + Entry entry = new Entry(); + entry.path = path; + entry.type = view.getClass().getName(); + entry.scrollX = view.getScrollX(); + entry.scrollY = view.getScrollY(); + if (unsavedText) { + entry.text = ((EditText) view).getText().toString(); + entry.selection = ((EditText) view).getSelectionEnd(); + } + entries.add(entry); + } + if (view instanceof ViewGroup) { + ViewGroup group = (ViewGroup) view; + for (int i = 0; i < group.getChildCount(); i++) capture(group.getChildAt(i), path + "/" + i); + } + } + + private void restore(View root, boolean withText) { + for (Entry entry : entries) { + View view = root; + for (String step : entry.path.split("/")) { + if (step.isEmpty()) continue; + int index = Integer.parseInt(step); + if (!(view instanceof ViewGroup) || index >= ((ViewGroup) view).getChildCount()) { + view = null; + break; + } + view = ((ViewGroup) view).getChildAt(index); + } + // Only when the same kind of view is still in the same place. + if (view == null || !view.getClass().getName().equals(entry.type)) continue; + if (withText && entry.text != null) { + EditText input = (EditText) view; + input.setText(entry.text); + input.setSelection(Math.min(Math.max(entry.selection, 0), input.length())); + } + view.scrollTo(entry.scrollX, entry.scrollY); + } + } + + @Override + public void onActivityResumed(final Activity activity) { + if (!activity.getClass().getName().equals(activityClass)) return; + application.unregisterActivityLifecycleCallbacks(this); + final View root = activity.getWindow().getDecorView(); + // After the first layout pass, when scroll ranges are known and focus has settled. + root.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + root.getViewTreeObserver().removeOnPreDrawListener(this); + restore(root, true); + View focused = activity.getCurrentFocus(); + if (keyboardShown && focused != null) { + ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE)) + .showSoftInput(focused, 0); + } + return true; + } + }); + // While the window settles the platform keeps moving scroll offsets: focus is + // scrolled into view, and a focused input field pulls its cursor back on screen + // just before drawing. Hold the saved offsets for every frame of that window. + final ViewTreeObserver.OnPreDrawListener hold = new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + restore(root, false); + return true; + } + }; + root.getViewTreeObserver().addOnPreDrawListener(hold); + handler.postDelayed(new Runnable() { + @Override + public void run() { + if (root.getViewTreeObserver().isAlive()) { + root.getViewTreeObserver().removeOnPreDrawListener(hold); + } + restore(root, false); + } + }, 1500); + } + + @Override public void onActivityCreated(Activity activity, Bundle state) {} + @Override public void onActivityStarted(Activity activity) {} + @Override public void onActivityPaused(Activity activity) {} + @Override public void onActivityStopped(Activity activity) {} + @Override public void onActivitySaveInstanceState(Activity activity, Bundle state) {} + @Override public void onActivityDestroyed(Activity activity) {} +} diff --git a/src/android_use/hotswap/hotswap.init.gradle b/src/android_use/hotswap/hotswap.init.gradle new file mode 100644 index 0000000..45a9067 --- /dev/null +++ b/src/android_use/hotswap/hotswap.init.gradle @@ -0,0 +1,69 @@ +// Init script used only by hotswap.py's own Gradle runs; the project's files are untouched. +// It exports what hotswap.py needs to compile one module's sources exactly the way +// Gradle does, and lets a resource relink keep the resource IDs of the installed build. +// -Dhotswap.module=:app -Dhotswap.variant=Debug -Dhotswap.out=/path/info.json +// -Dhotswap.stableIds=FILE link resources with the IDs listed in FILE +allprojects { project -> + if (project.path != System.getProperty("hotswap.module")) return + // Through the variant API, registered as soon as the Android plugin is applied. + project.plugins.withId("com.android.application") { + def stableIds = System.getProperty("hotswap.stableIds") + def components = project.extensions.getByName("androidComponents") + components.onVariants(components.selector().all()) { variant -> + if (stableIds) variant.androidResources.aaptAdditionalParameters.addAll( + ["--stable-ids", stableIds]) + } + } + project.afterEvaluate { + project.tasks.register("hotswapInfo") { + doLast { + def variant = System.getProperty("hotswap.variant") + def lower = variant.uncapitalize() + def android = project.extensions.getByName("android") + def javac = project.tasks.findByName("compile${variant}JavaWithJavac") + def kotlin = project.tasks.findByName("compile${variant}Kotlin") + def paths = { files -> files.collect { it.absolutePath } } + def info = [:] + def app = android.applicationVariants.find { it.name == lower } + info.package = app.applicationId + info.min_api = android.defaultConfig.minSdk + info.boot = paths(android.bootClasspath) + info.sources = [] + info.res = [] + info.manifests = [] + app.sourceSets.each { set -> + info.sources += paths(set.javaDirectories) + if (set.hasProperty("kotlinDirectories")) info.sources += paths(set.kotlinDirectories) + info.res += paths(set.resDirectories) + info.manifests << set.manifestFile.absolutePath + } + info.classpath = paths(javac.classpath.files) + info.classes_dirs = [javac.destinationDirectory.get().asFile.absolutePath] + info.javac_args = ["-source", javac.sourceCompatibility, "-target", javac.targetCompatibility] + if (kotlin != null) { + info.classes_dirs << kotlin.destinationDirectory.get().asFile.absolutePath + info.classpath = (paths(kotlin.libraries.files) + info.classpath).unique() + info.kotlin_compiler_classpath = paths( + project.configurations.getByName("kotlinCompilerClasspath").files) + def options = kotlin.compilerOptions + def args = ["-no-stdlib", "-no-reflect", + "-jvm-target", options.jvmTarget.get().target, + // internal members are name-mangled with the module name + "-module-name", options.moduleName.get()] + args += options.freeCompilerArgs.get() + kotlin.pluginClasspath.files.each { args << "-Xplugin=${it.absolutePath}".toString() } + kotlin.pluginOptions.get().each { config -> + config.allOptions().each { id, values -> + values.each { args << "-P" << "plugin:${id}:${it.key}=${it.value}".toString() } + } + } + info.kotlinc_args = args + } + info.module_dir = project.projectDir.absolutePath + info.build_files = [project.buildFile.absolutePath, project.rootProject.buildFile.absolutePath] + new File(System.getProperty("hotswap.out")).text = groovy.json.JsonOutput.prettyPrint( + groovy.json.JsonOutput.toJson(info)) + } + } + } +} diff --git a/src/android_use/models.py b/src/android_use/models.py index 24bcfe6..6414ea9 100644 --- a/src/android_use/models.py +++ b/src/android_use/models.py @@ -280,7 +280,17 @@ class BatchStep(StrictModel): args: dict = Field(default_factory=dict) +class HotSwapArgs(StrictModel): + project: Annotated[str, Field(min_length=1, max_length=1000)] + action: Literal["swap", "build", "status"] = "swap" + refresh: Literal["auto", "recreate", "none"] = "auto" + module: Annotated[str, Field(min_length=1, max_length=200)] | None = None + variant: Annotated[str, Field(min_length=1, max_length=100)] | None = None + observe: Observe = "none" + + ARG_MODELS = { + "hot_swap": HotSwapArgs, "read_fields": ReadFieldsArgs, "locate": LocateArgs, "execute_goal": ExecuteGoalArgs, diff --git a/src/android_use/runtime.py b/src/android_use/runtime.py index bb7ad11..769c084 100644 --- a/src/android_use/runtime.py +++ b/src/android_use/runtime.py @@ -244,6 +244,8 @@ def _call(self, op, **args): if any(step.get("visual") for _, step in args["steps"]): # A paid, screenshot-sending location is never queued behind other actions. raise ValueError("Visual taps are not allowed in batch") + if op == "hot_swap": + return self._hot_swap(**args) goal_config = session = None if op in {"execute_goal", "read_fields"}: from .jev import JevConfig @@ -356,6 +358,40 @@ def _error(self, exc): error["screenshot_unavailable"] = type(snapshot_error).__name__ return error + def _hot_swap(self, project, action, refresh, module, variant, observe): + # Compiling can take minutes on a first build and needs no UiAutomator, so the + # cross-process device lock is only taken for the optional observation. + from .hotswap import engine + + self._connect() + if action != "status": + self._check_paused() + tools = None + try: + tools = engine.Tools(self.serial) + result = engine.run_action( + action, project, refresh=refresh, module=module, variant=variant, tools=tools + ) + except engine.Fail as exc: + self.mutation_attempted = bool(tools and tools.touched) + # Compiler output names the caller's own sources; keep the tail, where errors are. + raise UseError(exc.code, str(exc)[-4000:]) from None + result = {"ok": True, **result} + if action == "status": + return result + result["verified"] = False + if observe != "none": + # The agent answers before the UI has redrawn; a fresh install also has to start. + time.sleep(0.5 if result["result"] == "swapped" else 2.0) + try: + with self._guard(): + self._usable() + result["observation"] = self._observe(observe) + except UseError as exc: + result["observation_error"] = exc.as_dict() + self._check_paused() + return result + def _guard(self): from contextlib import contextmanager diff --git a/src/android_use/server.py b/src/android_use/server.py index 7fd5cc1..fe0644e 100644 --- a/src/android_use/server.py +++ b/src/android_use/server.py @@ -141,6 +141,21 @@ def obj(properties=None): "and returns the next decision, completion or handoff. An unknown option ID keeps the token; " "any other outcome consumes it. Tokens expire after 5 idle minutes and need the same MCP " "server process. timeout_seconds counts device time only, not host thinking time.", + "hot_swap": "For developing an Android app whose source is on this computer: after editing " + "its code or resources, push the edits into the running debuggable app in about a second, " + "without reinstalling or restarting it. project is the absolute path of a Gradle root " + "or module directory (auto-detected; settings go to build/, project files stay untouched), " + "or of a directory with a hotswap.json. action=swap (default) compiles what changed and " + "redefines the classes in place; Compose recomposes with remembered state, View screens are " + "rebuilt with scroll position and input text kept. It falls back to a full build, install " + "and launch when needed (first call, app not running, manifest/build file change, refused " + "swap): result is swapped, installed or unchanged, with reason for a fallback. The first " + "call can take minutes (Gradle). action=build forces the full build; action=status reports " + "the host toolchain, pending edits and what the next swap would do, changing nothing. " + "A compile error returns compile_failed with compiler output and leaves the app as it was: " + "fix the source and call again. observe returns the screen after the swap in the same " + "call; verified=false: check the UI yourself. Needs a JDK and the Android SDK (NDK once " + "per device ABI). Debuggable builds only; module/variant default to :app/Debug.", "doctor": "Read local ADB device inventory and configuration. Does not start a phone service.", "setup": "First use: status/discover, start once if needed, then ready. configure selects a serial. " "start pushes a pinned JAR and reuses/starts UiAutomator without root or keyboard APK.", @@ -212,6 +227,8 @@ def create_server(runtime=None): "Actions accept wait_for={selector,state:visible|gone,timeout_seconds}; " "use scroll_until for bounded list search. An unmet condition never replays the action. " "Execute actions once; do not replay uncertain mutations. " + "When developing an Android app from local source, apply each edit with aua_hot_swap " + "(project path) instead of rebuilding and reinstalling; it keeps the app's UI state. " "Password/PIN/OTP authentication belongs to the user: pause, ask, await confirmation, " "resume and observe. Verify final business outcomes from actual device state.", ) diff --git a/tests/test_hotswap.py b/tests/test_hotswap.py new file mode 100644 index 0000000..4f046ee --- /dev/null +++ b/tests/test_hotswap.py @@ -0,0 +1,131 @@ +import json +from importlib.resources import files + +import pytest + +from android_use.hotswap import engine + + +@pytest.fixture +def gradle_root(tmp_path): + root = tmp_path / "shop" + (root / "app/src").mkdir(parents=True) + (root / "settings.gradle.kts").write_text("") + (root / "gradlew").write_text("") + return root + + +def config(root): + return json.loads((root / engine.AUTO_CONFIG).read_text()) + + +def test_gradle_root_needs_no_setup_and_keeps_project_files_untouched(gradle_root): + before = sorted(p.name for p in gradle_root.iterdir()) + assert engine.locate(gradle_root) == gradle_root + assert config(gradle_root) == { + "type": "gradle", + "module": ":app", + "variant": "Debug", + "gradle": [str(gradle_root / "gradlew")], + } + assert sorted(p.name for p in gradle_root.iterdir()) == sorted([*before, "build"]) + + +def test_module_directory_selects_that_module(gradle_root): + (gradle_root / "feature/pay").mkdir(parents=True) + assert engine.locate(gradle_root / "feature/pay") == gradle_root + assert config(gradle_root)["module"] == ":feature:pay" + + +def test_settings_are_kept_until_explicitly_changed(gradle_root): + engine.locate(gradle_root, module=":wear", variant="staging") + assert (config(gradle_root)["module"], config(gradle_root)["variant"]) == (":wear", "Staging") + stamp = (gradle_root / engine.AUTO_CONFIG).stat().st_mtime_ns + engine.locate(gradle_root) # Unchanged file: the next swap stays a swap. + assert (gradle_root / engine.AUTO_CONFIG).stat().st_mtime_ns == stamp + assert config(gradle_root)["module"] == ":wear" + engine.locate(gradle_root, variant="Debug") + assert config(gradle_root)["variant"] == "Debug" + + +def test_hand_written_config_wins(gradle_root): + (gradle_root / "hotswap.json").write_text("{}") + assert engine.locate(gradle_root / "app") == gradle_root + assert not (gradle_root / engine.AUTO_CONFIG).exists() + + +def test_unknown_project_is_reported(tmp_path): + for target in (tmp_path, tmp_path / "missing"): + with pytest.raises(engine.Fail) as failure: + engine.locate(target) + assert failure.value.code == "project_invalid" + + +def test_command_line_text(): + swapped = {"result": "swapped", "class_count": 2, "resources": True, "seconds": 0.5, + "verdict": "OK redefined=2"} + assert engine.describe(swapped) == "swapped 2 class(es) + resources in 0.50s: OK redefined=2" + installed = {"result": "installed", "package": "a.b", "seconds": 3, "reason": "why"} + assert engine.describe(installed).splitlines()[0] == "reinstall: why" + assert engine.describe({"result": "unchanged"}) == "nothing to swap" + + +def test_sources_built_on_the_host_ship_with_the_package(): + package = files("android_use.hotswap") + for name in ( + "agent/agent.cpp", + "daemon/HotswapDaemon.java", + "helper/hotswap/agent/HotswapState.java", + "hotswap.init.gradle", + ): + assert package.joinpath(name).is_file() + + +class FakeTools: + touched = False + + def __init__(self, serial): + self.serial = serial + + +def test_runtime_passes_arguments_and_respects_takeover(rig, monkeypatch): + runtime, backend = rig + calls = [] + + def run_action(action, project, **options): + calls.append((action, project, options["refresh"], options["tools"].serial)) + if action == "status": + return {"action": "status", "toolchain": {"ready": True}} + return {"action": action, "result": "swapped", "package": "demo.app"} + + monkeypatch.setattr(engine, "Tools", FakeTools) + monkeypatch.setattr(engine, "run_action", run_action) + monkeypatch.setattr("android_use.runtime.time.sleep", lambda seconds: None) + result = runtime.call("hot_swap", project="/work/app", observe="tree") + assert result["result"] == "swapped" and result["verified"] is False + assert result["observation"]["tree"]["total_nodes"] == 6 + assert calls == [("swap", "/work/app", "auto", runtime.serial)] + assert backend.actions == [] + + assert runtime.call("pause")["paused"] + assert runtime.call("hot_swap", project="/work/app")["error"]["code"] == "user_takeover" + assert runtime.call("hot_swap", project="/work/app", action="status")["ok"] + assert [c[0] for c in calls] == ["swap", "status"] + assert runtime.call("hot_swap", project="")["error"]["code"] == "invalid_arguments" + + +@pytest.mark.parametrize("touched", [False, True]) +def test_runtime_reports_failures_without_replay(rig, monkeypatch, touched): + runtime, _ = rig + + def run_action(action, project, **options): + options["tools"].touched = touched + raise engine.Fail("javac failed:\nMain.java:3: error", "compile_failed") + + monkeypatch.setattr(engine, "Tools", FakeTools) + monkeypatch.setattr(engine, "run_action", run_action) + result = runtime.call("hot_swap", project="/work/app") + assert result["error"]["code"] == "compile_failed" + assert "Main.java:3" in result["error"]["message"] + assert result["error"]["uncertain"] is touched + assert result["action_attempted"] is touched and result["replay_action"] is False diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 6feb3a3..9f92ab8 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -29,7 +29,11 @@ async def exercise(): async with ClientSession(read, write) as session: await session.initialize() tools = (await session.list_tools()).tools - assert len(tools) == 26 + assert len(tools) == 27 + swap = next(t for t in tools if t.name == "aua_hot_swap") + assert swap.inputSchema["required"] == ["project"] + assert swap.inputSchema["properties"]["action"]["default"] == "swap" + assert not swap.annotations.readOnlyHint assert "aua_read_fields" in {t.name for t in tools} assert next( t for t in tools if t.name == "aua_read_fields" diff --git a/ui/package-lock.json b/ui/package-lock.json index c358b0c..250cda7 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -1,12 +1,12 @@ { "name": "android-use-screen", - "version": "0.7.1", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "android-use-screen", - "version": "0.7.1", + "version": "0.8.0", "dependencies": { "@modelcontextprotocol/ext-apps": "1.7.5" }, diff --git a/ui/package.json b/ui/package.json index ce1b235..b4140c7 100644 --- a/ui/package.json +++ b/ui/package.json @@ -1,6 +1,6 @@ { "name": "android-use-screen", - "version": "0.7.1", + "version": "0.8.0", "private": true, "type": "module", "scripts": { diff --git a/ui/src/app.ts b/ui/src/app.ts index 0090583..5adc68d 100644 --- a/ui/src/app.ts +++ b/ui/src/app.ts @@ -18,7 +18,7 @@ const pointer=document.querySelector('#pointer')!; const resumeButton=document.querySelector('#resume')!; const buttons=Object.fromEntries(['refresh','back','home','copy'].map(id=>[id,document.getElementById(id) as HTMLButtonElement])); const standalone=window.__ANDROID_USE_STANDALONE__===true; -const app=standalone?undefined:new App({name:'Android Use Screen',version:'0.7.1'}, +const app=standalone?undefined:new App({name:'Android Use Screen',version:'0.8.0'}, {availableDisplayModes:['fullscreen']},{autoResize:false}); let preview:Preview|undefined,seq=0,stream='',disposed=false,inFlight=false,acting=false; let suspended=false,timer:ReturnType|undefined; diff --git a/uv.lock b/uv.lock index 2b5aac0..7e626ac 100644 --- a/uv.lock +++ b/uv.lock @@ -28,7 +28,7 @@ wheels = [ [[package]] name = "android-use" -version = "0.7.1" +version = "0.8.0" source = { editable = "." } dependencies = [ { name = "httpx" }, From 3d732c44f0bec4571755b6bc351eb12c04f82aa5 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:46:48 +0800 Subject: [PATCH 2/3] test: rewrite only this project's version in the upgrade fixture The fixture replaced every occurrence of the current version in uv.lock, which also rewrote a locked dependency that happens to share 0.8.0. --- tests/test_installation.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_installation.py b/tests/test_installation.py index 8ffb562..7a3a90c 100644 --- a/tests/test_installation.py +++ b/tests/test_installation.py @@ -331,7 +331,10 @@ def test_real_mcp_upgrade_and_fresh_host_after_deleted_sources(tmp_path, monkeyp for name in (".codex-plugin/plugin.json", "pyproject.toml", "uv.lock", "src/android_use/__init__.py"): path = source_root / name - path.write_text(path.read_text().replace(version, ver)) + # Only this project's own entry: a locked dependency may share the version. + old = f'name = "android-use"\nversion = "{version}"' if name == "uv.lock" else version + assert path.read_text().count(old) == 1 + path.write_text(path.read_text().replace(old, old.replace(version, ver))) root = tmp_path / "stable install with spaces" env_file = tmp_path / "environment with spaces.env" env_file.write_text("ANDROID_USE_UPGRADE_SENTINEL=private-fixture\n") From 087d303749cc6a189925abdab3a6b8b1f16e49dd Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:51:31 +0800 Subject: [PATCH 3/3] test: expect 27 tools in native runtime acceptance --- scripts/accept_runtime.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/accept_runtime.py b/scripts/accept_runtime.py index e432bba..1a4b1fb 100644 --- a/scripts/accept_runtime.py +++ b/scripts/accept_runtime.py @@ -45,7 +45,7 @@ async def connected(command, env): read, write, read_timeout_seconds=timedelta(seconds=30) ) as session: started = await session.initialize() - assert len((await session.list_tools()).tools) == 26 + assert len((await session.list_tools()).tools) == 27 resource = (await session.list_resources()).resources[0] content = (await session.read_resource(resource.uri)).contents[0].text assert "Android Use" in content and len(content) > 10000 @@ -90,7 +90,7 @@ async def exercise(archive, upgrade_archive): result, first = run( [exe, "--root", root, "install", "--archive", archive, "--sha256", digest(archive)], env ) - assert result.returncode == 0 and first["tool_count"] == 26, first + assert result.returncode == 0 and first["tool_count"] == 27, first config = first["mcp_config"] command = [config["command"], *config["args"]] assert await connected(command, env) == version @@ -128,7 +128,7 @@ async def exercise(archive, upgrade_archive): ) assert result.returncode == 0 and upgraded["previous"] == first["release"], upgraded assert upgraded["mcp_config"] == config - assert len((await active.list_tools()).tools) == 26 + assert len((await active.list_tools()).tools) == 27 assert await connected(command, env) == upgraded["version"] passed.append("upgrade_switches_new_sessions_without_interrupting_old_session") shutil.rmtree(unpacked) @@ -156,7 +156,7 @@ async def exercise(archive, upgrade_archive): result, rolled = run([*command[:-1], "rollback"], env) assert result.returncode == 0 and rolled["version"] == version, rolled assert await connected(command, env) == version - assert len((await active.list_tools()).tools) == 26 + assert len((await active.list_tools()).tools) == 27 assert json.loads((root / "update-policy.json").read_text())["paused"] passed.append("rollback_reprobes_previous_runtime_and_pauses_auto_update") assert preference.read_bytes() == preference_before