From 1c8398ce156f718e3df6ff2df7d22fd9ccd1b2ac Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 00:36:57 +0800 Subject: [PATCH 01/11] ci(android): run the emulator traffic matrix and upload its report Assisted-by: Codex:GPT-6 Assisted-by: Pi:gemini-4-neon --- .github/emulator/grant.py | 68 +++++++++++++++++++++++++++++++ .github/emulator/prepare.sh | 54 ++++++++++++++++++++++++ .github/workflows/ci.yml | 53 +++++++++++++++++++++--- README.md | 2 + justfile | 3 +- traffic-test/emulator/__main__.py | 15 ++++--- 6 files changed, 183 insertions(+), 12 deletions(-) create mode 100644 .github/emulator/grant.py create mode 100644 .github/emulator/prepare.sh diff --git a/.github/emulator/grant.py b/.github/emulator/grant.py new file mode 100644 index 0000000..4bfe084 --- /dev/null +++ b/.github/emulator/grant.py @@ -0,0 +1,68 @@ +"""Authorize only the installed debug app in the pinned KernelSU Manager on the CI AVD.""" + +import re +import subprocess +import time +import xml.etree.ElementTree as ET + +MANAGER = "me.weishu.kernelsu" +CLASH = "rs.clash.android.dev" + + +def shell(*args): + return subprocess.check_output(["adb", "shell", *args], text=True, timeout=30).strip() + + +def screen(): + path = "/data/local/tmp/ksu-profile.xml" + shell("uiautomator", "dump", path) + return ET.fromstring(shell("cat", path)) + + +def find(tree, text): + return next((n for n in tree.iter("node") if n.get("package") == MANAGER + and text in (n.get("text"), n.get("content-desc"))), None) + + +def tap(node): + x, y, right, bottom = map(int, re.findall(r"\d+", node.get("bounds"))) + shell("input", "tap", str((x + right) // 2), str((y + bottom) // 2)) + + +def grant(): + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + tree = screen() + if find(tree, "Working") is not None: + tap(find(tree, "Superuser")) + break + else: + raise RuntimeError("KernelSU Manager did not report a working kernel module") + + # The pinned manager's paged app list may omit its rows from the accessibility + # tree. Clash is the only installed third-party client on the fresh 1080x2400 AVD. + # Always verify the package on the profile screen before touching a grant. + while time.monotonic() < deadline: + tree = screen() + if find(tree, "App Profile") is not None: + if find(tree, CLASH) is None: + raise RuntimeError("Unexpected package on the KernelSU grant screen") + switches = tree.findall(f".//node[@package='{MANAGER}'][@checkable='true']") + if len(switches) != 1: + raise RuntimeError("Unexpected KernelSU profile controls") + if switches[0].get("checked") != "true": + tap(switches[0]) + break + row = find(tree, CLASH) + if row is not None: + tap(row) + else: + shell("input", "tap", "386", "640") + else: + raise RuntimeError("Clash profile did not open") + if shell("run-as", CLASH, "su", "-c", "'id -u'") != "0": + raise RuntimeError("Clash did not receive the KernelSU grant") + + +if __name__ == "__main__": + grant() diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh new file mode 100644 index 0000000..b8a4422 --- /dev/null +++ b/.github/emulator/prepare.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +# A fresh hosted VM owns this AVD and its adb server. +work="$RUNNER_TEMP/clash-ksu" +mkdir -p "$work" +cd "$work" +image="$ANDROID_HOME/system-images/android-35/google_apis_playstore/x86_64" +package='system-images;android-35;google_apis_playstore;x86_64' +sdkmanager "emulator" "$package" +# KernelSU's module is built for the kernel in revision 9 of this image. +echo "a204606cf2f458540c5437e9ba804b5012acf0a2916d00f099a03e1e553e697e $image/kernel-ranchu" | sha256sum -c - +echo "bb8cbb36481f2892c29929ed37bf51b904ddfdc796a76476364cd19aebea843b $image/ramdisk.img" | sha256sum -c - + +fetch() { + curl --fail --silent --show-error --location --retry 3 "$1" -o "$2" + echo "$3 $2" | sha256sum -c - +} +release=https://github.com/leemikepop/avd-kernelsu-x86_64/releases/download/kernelsu-v3.3.1 +fetch "$release/ksud-kernelsu-v3.3.1-x86_64-unknown-linux-musl" ksud 29b50f946a3cc40b04aef3dd587adad227fe0f70edf9c56b02c84479f0b0e954 +fetch "$release/a15-api35-6.6_kernelsu-v3.3.1_kernelsu.ko" kernelsu.ko 9cd4ab1591a6299a1a8c49714630bb00fc96c87ec896181791c8e0f989bf225a +fetch "$release/ksuinit-x86_64-kernelsu-v3.3.1" ksuinit 07df433255389dcf015dcec023aabee3d61df82055fa7eb4f66240f5d2c4a9c5 +fetch "https://github.com/tiann/KernelSU/releases/download/v3.3.1/KernelSU_v3.3.1_32680-release.apk" manager.apk b4a059ace71de2fa65cc7f12b1c58d55fc23ab25e057ee4230ce779742abe450 +chmod +x ksud +./ksud boot-patch -b "$image/ramdisk.img" --ramdisk --arch x86_64 -m kernelsu.ko -i ksuinit \ + --kmi android15-6.6 --allow-shell -o "$work" --out-name ramdisk.img +echo "CLASH_TEST_RAMDISK=$work/ramdisk.img" >> "$GITHUB_ENV" + +echo no | avdmanager create avd --name "$CLASH_TEST_AVD" --package "$package" --device pixel_6 +sudo setfacl -m "u:$(id -un):rw" /dev/kvm +export ANDROID_SERIAL=emulator-5554 +adb start-server +"$ANDROID_HOME/emulator/emulator" -avd "$CLASH_TEST_AVD" -ramdisk "$work/ramdisk.img" -port 5554 \ + -no-snapshot -no-audio -no-boot-anim -no-window -gpu swiftshader_indirect >boot.log 2>&1 & +pid=$! +shutdown() { + adb -s "$ANDROID_SERIAL" emu kill >/dev/null 2>&1 || kill "$pid" 2>/dev/null || true + wait "$pid" || true +} +trap shutdown EXIT +if ! timeout 240 bash -c 'adb wait-for-device && until [[ $(adb shell getprop sys.boot_completed | tr -d "\r") == 1 ]]; do sleep 1; done'; then + tail -n 25 boot.log + exit 1 +fi +adb install --abi x86_64 manager.apk +adb install --abi x86_64 "$GITHUB_WORKSPACE/app/build/outputs/apk/debug/app-debug.apk" +adb shell wm size 1080x2400 +adb shell wm density 420 +adb shell input keyevent KEYCODE_WAKEUP +adb shell wm dismiss-keyguard +adb shell svc power stayon true +adb shell am start -W -n me.weishu.kernelsu/.ui.MainActivity +python3 "$GITHUB_WORKSPACE/.github/emulator/grant.py" +adb shell sync diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37276ec..81bc2f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -120,10 +120,24 @@ jobs: echo "version=dev-$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT fi - - name: Build Debug APK - if: github.event_name == 'pull_request' + - name: Build emulator test packages + if: "!startsWith(github.ref, 'refs/tags/')" run: | - ./gradlew --build-cache app:assembleDebug + ./gradlew --build-cache :app:assembleDebug :app:packageKernelSuModule :traffic-test:assembleDebug :traffic-test:assembleDebugAndroidTest + + - name: Pass test packages to the emulator + if: "!startsWith(github.ref, 'refs/tags/')" + uses: actions/upload-artifact@v7 + with: + name: emulator-packages + path: | + app/build/outputs/apk/debug/app-debug.apk + build/kernelsu/clash-android-tproxy.zip + traffic-test/build/outputs/apk/debug/traffic-test-debug.apk + traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk + if-no-files-found: error + retention-days: 3 + compression-level: 0 - name: Build Release APKs if: github.event_name != 'pull_request' @@ -243,6 +257,33 @@ jobs: gh release edit "$TAG_NAME" --draft=false --prerelease --notes-file CHANGELOG.md fi - - - + emulator: + name: Android emulator traffic matrix + needs: build + if: "!startsWith(github.ref, 'refs/tags/')" + runs-on: ubuntu-24.04 + permissions: + contents: read + timeout-minutes: 40 + env: + CLASH_TEST_AVD: ClashKsu35 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@v8 + with: + name: emulator-packages + - uses: taiki-e/install-action@v2.90.11 + with: + tool: just,uv + - name: Prepare disposable API 35 KernelSU AVD + run: bash .github/emulator/prepare.sh + - name: Run all eight traffic combinations + run: just test-emulator --prebuilt + - name: Upload emulator JSON report + uses: actions/upload-artifact@v7 + with: + name: emulator-report-${{ github.sha }}-${{ github.run_attempt }} + path: build/emulator-tests/*/results.json + if-no-files-found: error diff --git a/README.md b/README.md index 96503cb..84433f3 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ Clash Android 是基于 clash-rs 的 Android 代理客户端,支持 Android 7. 运行需要项目的 Android 构建环境、`just`、`uv` 和一个 API 35 KernelSU 测试 AVD。AVD 需要支持 `adb shell su 0`,并预先向调试包 `rs.clash.android.dev` 授予 root,能通过 `10.0.2.2` 和 `fec0::2` 访问宿主机,并能解析和连接 `example.com:443`。默认使用 `ClashKsu35` 和 `~/.android/ksu-clash-api35/ramdisk-ksu.img`,可用 `CLASH_TEST_AVD`、`CLASH_TEST_RAMDISK` 指定匹配的 AVD 和 ramdisk。命令会在宿主机的两个回环地址上启动端口为 `39007` 的回显服务,并在结束后关闭服务和测试模拟器。 +GitHub Actions 在 PR 和主分支构建中将同一次构建的调试 APK 和模块交给独立的 Ubuntu runner。它创建一次性的 API 35 KernelSU AVD,执行 `just test-emulator --prebuilt`。八组测试全部通过后,可在该次运行的 Artifacts 中下载 `emulator-report--`,其中包含 `results.json`。 + 在已安装 `traffic-test` 调试 APK 和 androidTest APK 的设备上,也可以单独运行探针: ```sh diff --git a/justfile b/justfile index 6954022..d3ebae1 100644 --- a/justfile +++ b/justfile @@ -30,7 +30,8 @@ module: phone: ./gradlew -PphoneArm64=true :app:assembleDebug +[positional-arguments] [script("uv", "run", "--no-project", "python")] -test-emulator: +test-emulator *args: import runpy runpy.run_path("traffic-test/emulator", run_name="__main__") diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index 7419a20..f3ccc68 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -1,5 +1,6 @@ """Run the VPN/TPROXY traffic matrix on a disposable KernelSU emulator.""" +import argparse import ipaddress import itertools import json @@ -296,6 +297,9 @@ def check_settings(device, mode, ipv6, fake_ip): def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prebuilt", action="store_true", help="use test packages already built for this checkout") + args = parser.parse_args() sdk_path = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") properties = ROOT / "local.properties" if not sdk_path and properties.is_file(): @@ -320,11 +324,12 @@ def save(): env.pop("KEYSTORE_FILE", None) env.pop("ANDROID_SPLIT_ABI_ENABLE", None) try: - if not (ROOT / "core/src/main/java/uniffi/clash_android_ffi/clash_android_ffi.kt").is_file(): - subprocess.run(["just", "generate-bindings", "--locked"], cwd=ROOT, env=env, check=True) - subprocess.run([ROOT / ("gradlew.bat" if os.name == "nt" else "gradlew"), ":app:assembleDebug", - ":app:packageKernelSuModule", ":traffic-test:assembleDebug", ":traffic-test:assembleDebugAndroidTest"], - cwd=ROOT, env=env, check=True) + if not args.prebuilt: + if not (ROOT / "core/src/main/java/uniffi/clash_android_ffi/clash_android_ffi.kt").is_file(): + subprocess.run(["just", "generate-bindings", "--locked"], cwd=ROOT, env=env, check=True) + subprocess.run([ROOT / ("gradlew.bat" if os.name == "nt" else "gradlew"), ":app:assembleDebug", + ":app:packageKernelSuModule", ":traffic-test:assembleDebug", ":traffic-test:assembleDebugAndroidTest"], + cwd=ROOT, env=env, check=True) with ExitStack() as stack: logs = {family: stack.enter_context(echo_server(directory, family, address)) for family, address in [("v4", "127.0.0.1"), ("v6", "::1")]} From de6d96167f0ad7eddd69f0d1499bf156edad0496 Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 00:50:05 +0800 Subject: [PATCH 02/11] ci(android): persist the local sccache directory with Actions cache Assisted-by: Codex:GPT-6 --- .github/workflows/ci.yml | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81bc2f6..e612b8a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,6 @@ defaults: env: RUSTC_BOOTSTRAP: "1" - SCCACHE_GHA_ENABLED: "true" AWS_LC_SYS_PREBUILT_NASM: "1" concurrency: @@ -27,6 +26,10 @@ concurrency: jobs: build: runs-on: ubuntu-latest + env: + RUSTC_WRAPPER: sccache + SCCACHE_DIR: /tmp/sccache + SCCACHE_CACHE_SIZE: 2G steps: - name: Checkout code @@ -74,12 +77,18 @@ jobs: echo "ANDROID_NDK_ROOT=$ndk" >> "$GITHUB_ENV" echo "ANDROID_NDK=$ndk" >> "$GITHUB_ENV" - - name: Setup sccache-cache - uses: mozilla-actions/sccache-action@v0.0.11 - - uses: taiki-e/install-action@v2.90.11 with: - tool: cargo-ndk,just + tool: cargo-ndk,just,sccache + + - name: Cache the local sccache directory + uses: actions/cache@v6.1.0 + with: + path: ${{ env.SCCACHE_DIR }} + key: android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}-${{ hashFiles('uniffi/Cargo.lock', 'kernelsu/Cargo.lock') }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}-${{ hashFiles('uniffi/Cargo.lock', 'kernelsu/Cargo.lock') }}- + android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}- - name: Build Rust workspaces with a shared Cargo target directory run: echo "CARGO_BUILD_TARGET_DIR=$RUNNER_TEMP/cargo-target" >> "$GITHUB_ENV" @@ -99,8 +108,6 @@ jobs: - name: Generate Rust bindings if: steps.bindings.outputs.cache-hit != 'true' - env: - RUSTC_WRAPPER: sccache run: just generate-bindings --locked - name: Decode Keystore @@ -161,6 +168,9 @@ jobs: bash .github/verify-native-symbols.sh release ./gradlew :app:uploadCrashlyticsSymbolFileRelease + - name: Show local compiler cache statistics + run: sccache --show-stats + - name: Archive matching native symbols and R8 mapping if: github.event_name != 'pull_request' uses: actions/upload-artifact@v7 From f0cb82b41b9c4923a2ac3b2fc001b73e134b11a8 Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 01:34:35 +0800 Subject: [PATCH 03/11] fix(ci): locate Android command-line tools on the runner Assisted-by: Codex:GPT-6 --- .github/emulator/prepare.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh index b8a4422..c484ba7 100644 --- a/.github/emulator/prepare.sh +++ b/.github/emulator/prepare.sh @@ -7,6 +7,7 @@ mkdir -p "$work" cd "$work" image="$ANDROID_HOME/system-images/android-35/google_apis_playstore/x86_64" package='system-images;android-35;google_apis_playstore;x86_64' +export PATH="$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH" sdkmanager "emulator" "$package" # KernelSU's module is built for the kernel in revision 9 of this image. echo "a204606cf2f458540c5437e9ba804b5012acf0a2916d00f099a03e1e553e697e $image/kernel-ranchu" | sha256sum -c - From 4af42390bcac32bea50f874fce236c073c106ad8 Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 01:44:52 +0800 Subject: [PATCH 04/11] fix(ci): share the AVD location and KVM permissions across boots Assisted-by: Codex:GPT-6 --- .github/emulator/prepare.sh | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh index c484ba7..9e7476b 100644 --- a/.github/emulator/prepare.sh +++ b/.github/emulator/prepare.sh @@ -3,7 +3,9 @@ set -euo pipefail # A fresh hosted VM owns this AVD and its adb server. work="$RUNNER_TEMP/clash-ksu" -mkdir -p "$work" +export ANDROID_AVD_HOME="$work/avd" +mkdir -p "$ANDROID_AVD_HOME" +echo "ANDROID_AVD_HOME=$ANDROID_AVD_HOME" >> "$GITHUB_ENV" cd "$work" image="$ANDROID_HOME/system-images/android-35/google_apis_playstore/x86_64" package='system-images;android-35;google_apis_playstore;x86_64' @@ -28,7 +30,14 @@ chmod +x ksud echo "CLASH_TEST_RAMDISK=$work/ramdisk.img" >> "$GITHUB_ENV" echo no | avdmanager create avd --name "$CLASH_TEST_AVD" --package "$package" --device pixel_6 -sudo setfacl -m "u:$(id -un):rw" /dev/kvm +"$ANDROID_HOME/emulator/emulator" -list-avds | grep -Fx "$CLASH_TEST_AVD" +# The kernel can recreate /dev/kvm between the seed boot and the probe boot. +printf 'KERNEL=="kvm", OWNER="%s", GROUP="kvm", MODE="0660", OPTIONS+="static_node=kvm"\n' "$(id -un)" \ + | sudo tee /etc/udev/rules.d/99-clash-emulator-kvm.rules >/dev/null +sudo udevadm control --reload-rules +sudo udevadm trigger --name-match=kvm +sudo udevadm settle +test -r /dev/kvm && test -w /dev/kvm export ANDROID_SERIAL=emulator-5554 adb start-server "$ANDROID_HOME/emulator/emulator" -avd "$CLASH_TEST_AVD" -ramdisk "$work/ramdisk.img" -port 5554 \ From 1a32e91e709acc6d45b9a9f84f1a5bad9c1bdf9f Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 01:47:19 +0800 Subject: [PATCH 05/11] ci(android): enable actor-restricted Upterm on emulator debug reruns Assisted-by: Codex:GPT-6 --- .github/workflows/ci.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e612b8a..e6545de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -287,6 +287,14 @@ jobs: - uses: taiki-e/install-action@v2.90.11 with: tool: just,uv + - name: Open Upterm for a debug re-run + if: github.run_attempt != '1' && runner.debug == '1' + uses: owenthereal/action-upterm@6c2d60e09009f59cb4c45c88767c78701f14d121 # v2.8.1 + with: + limit-access-to-actor: true + detached: true + wait-timeout-minutes: 15 + upterm-version: v0.41.1 - name: Prepare disposable API 35 KernelSU AVD run: bash .github/emulator/prepare.sh - name: Run all eight traffic combinations From 27230615927223f8d50adde5f9ed9a69dd021d6c Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 01:51:58 +0800 Subject: [PATCH 06/11] docs(ci): explain how to connect to an emulator debug run Assisted-by: Codex:GPT-6 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 84433f3..f1753e3 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Clash Android 是基于 clash-rs 的 Android 代理客户端,支持 Android 7. GitHub Actions 在 PR 和主分支构建中将同一次构建的调试 APK 和模块交给独立的 Ubuntu runner。它创建一次性的 API 35 KernelSU AVD,执行 `just test-emulator --prebuilt`。八组测试全部通过后,可在该次运行的 Artifacts 中下载 `emulator-report--`,其中包含 `results.json`。 +要在 runner 上交互排查,用 `gh run rerun --job --debug` 重跑模拟器作业。从 `Open Upterm for a debug re-run` 步骤复制 SSH 命令,使用 GitHub 账号已登记公钥对应的私钥连接。普通步骤结束后,Upterm 最多等待 15 分钟供调试者接入。 + 在已安装 `traffic-test` 调试 APK 和 androidTest APK 的设备上,也可以单独运行探针: ```sh From 4543d8444bb8d8c09c887473430559744bd5f995 Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 01:58:27 +0800 Subject: [PATCH 07/11] fix(ci): grant KernelSU access during the emulator test boot Assisted-by: Codex:GPT-6 --- .github/emulator/prepare.sh | 26 +--------- traffic-test/emulator/__main__.py | 51 ++++++++++++++----- .../emulator/ksu_manager.py | 37 ++++++-------- 3 files changed, 54 insertions(+), 60 deletions(-) rename .github/emulator/grant.py => traffic-test/emulator/ksu_manager.py (74%) diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh index 9e7476b..ade6cb6 100644 --- a/.github/emulator/prepare.sh +++ b/.github/emulator/prepare.sh @@ -28,37 +28,13 @@ chmod +x ksud ./ksud boot-patch -b "$image/ramdisk.img" --ramdisk --arch x86_64 -m kernelsu.ko -i ksuinit \ --kmi android15-6.6 --allow-shell -o "$work" --out-name ramdisk.img echo "CLASH_TEST_RAMDISK=$work/ramdisk.img" >> "$GITHUB_ENV" +echo "CLASH_TEST_KSU_MANAGER=$work/manager.apk" >> "$GITHUB_ENV" echo no | avdmanager create avd --name "$CLASH_TEST_AVD" --package "$package" --device pixel_6 "$ANDROID_HOME/emulator/emulator" -list-avds | grep -Fx "$CLASH_TEST_AVD" -# The kernel can recreate /dev/kvm between the seed boot and the probe boot. printf 'KERNEL=="kvm", OWNER="%s", GROUP="kvm", MODE="0660", OPTIONS+="static_node=kvm"\n' "$(id -un)" \ | sudo tee /etc/udev/rules.d/99-clash-emulator-kvm.rules >/dev/null sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm sudo udevadm settle test -r /dev/kvm && test -w /dev/kvm -export ANDROID_SERIAL=emulator-5554 -adb start-server -"$ANDROID_HOME/emulator/emulator" -avd "$CLASH_TEST_AVD" -ramdisk "$work/ramdisk.img" -port 5554 \ - -no-snapshot -no-audio -no-boot-anim -no-window -gpu swiftshader_indirect >boot.log 2>&1 & -pid=$! -shutdown() { - adb -s "$ANDROID_SERIAL" emu kill >/dev/null 2>&1 || kill "$pid" 2>/dev/null || true - wait "$pid" || true -} -trap shutdown EXIT -if ! timeout 240 bash -c 'adb wait-for-device && until [[ $(adb shell getprop sys.boot_completed | tr -d "\r") == 1 ]]; do sleep 1; done'; then - tail -n 25 boot.log - exit 1 -fi -adb install --abi x86_64 manager.apk -adb install --abi x86_64 "$GITHUB_WORKSPACE/app/build/outputs/apk/debug/app-debug.apk" -adb shell wm size 1080x2400 -adb shell wm density 420 -adb shell input keyevent KEYCODE_WAKEUP -adb shell wm dismiss-keyguard -adb shell svc power stayon true -adb shell am start -W -n me.weishu.kernelsu/.ui.MainActivity -python3 "$GITHUB_WORKSPACE/.github/emulator/grant.py" -adb shell sync diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index f3ccc68..cddbfc9 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -17,6 +17,7 @@ from contextlib import ExitStack, contextmanager from clash_ui import ClashUi +from ksu_manager import authorize ROOT = Path(__file__).resolve().parents[2] CLASH = "rs.clash.android.dev" @@ -77,6 +78,17 @@ def shell(self, *args, **kwargs): def root(self, *args): return self.shell("su", "0", *args) + def install(self, apk, *options): + for attempt in range(2): + try: + self.adb("install", "-r", *options, apk, timeout=120) + return + except RuntimeError as error: + # adbd may restart during a streamed install on the first boot. + if attempt or "INSTALL_" in str(error): + raise + self.adb("wait-for-device", timeout=120) + @contextmanager def emulator(sdk, directory): @@ -111,17 +123,27 @@ def connect(): with connection.makefile("rb") as stream: port = int(stream.read(16).strip()) device = Device(adb, f"emulator-{port}") - device.adb("wait-for-device", timeout=120) - wait_for(lambda: device.shell("getprop", "sys.boot_completed") == "1", "Android boot", 180) + def booted(): + if process.poll() is not None: + raise RuntimeError(f"Emulator exited during boot; see {log.name}") + # adbd can disconnect and reconnect during the first boot of a new AVD. + probe = subprocess.run([*device.command, "shell", "getprop", "sys.boot_completed"], + capture_output=True, timeout=30) + return probe.returncode == 0 and probe.stdout.strip() == b"1" + + wait_for(booted, "Android boot", 240) if device.adb("emu", "avd", "name").splitlines()[0] != name: raise RuntimeError("Unexpected AVD name") try: yield device except Exception: - (directory / "logcat.txt").write_text( - device.shell("logcat", "-d", "-t", "4000", "-s", "AndroidRuntime:E", "TestRunner:E", "ClashTproxy:E", "clash:E"), - encoding="utf-8", - ) + try: + (directory / "logcat.txt").write_text( + device.shell("logcat", "-d", "-t", "4000", "-s", "AndroidRuntime:E", "TestRunner:E", "ClashTproxy:E", "clash:E"), + encoding="utf-8", + ) + except (RuntimeError, subprocess.TimeoutExpired) as diagnostic: + print(f"Could not collect logcat: {diagnostic}", file=sys.stderr) raise finally: if device is not None: @@ -154,15 +176,21 @@ def ready(): def prepare(device): abi = device.shell("getprop", "ro.product.cpu.abi") - device.adb("install", "-r", "--abi", abi, ROOT / "app/build/outputs/apk/debug/app-debug.apk") - device.adb("install", "-r", ROOT / "traffic-test/build/outputs/apk/debug/traffic-test-debug.apk") - device.adb("install", "-r", ROOT / "traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk") + device.install(ROOT / "app/build/outputs/apk/debug/app-debug.apk", "--abi", abi) # Only the read-only AVD overlay is changed. Preserve the pre-authorized app UID. device.shell("pm", "clear", CLASH) device.shell("pm", "grant", CLASH, "android.permission.POST_NOTIFICATIONS") device.shell("cmd", "locale", "set-app-locales", CLASH, "--locales", "en-US") + device.shell("input", "keyevent", "KEYCODE_WAKEUP") + device.shell("wm", "dismiss-keyguard") + device.shell("svc", "power", "stayon", "true") + manager = os.environ.get("CLASH_TEST_KSU_MANAGER") + if manager: + authorize(device, manager, CLASH, abi) if device.shell("run-as", CLASH, "su", "-c", "id -u") != "0": - raise RuntimeError(f"KernelSU must grant {CLASH} root in the base AVD") + raise RuntimeError(f"KernelSU must grant {CLASH} root in the test AVD") + device.install(ROOT / "traffic-test/build/outputs/apk/debug/traffic-test-debug.apk") + device.install(ROOT / "traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk") module = "/data/local/tmp/clash-test-module.zip" device.adb("push", ROOT / "build/kernelsu/clash-android-tproxy.zip", module) device.root("/data/adb/ksud", "module", "install", module) @@ -176,9 +204,6 @@ def prepare(device): f'{private}/files/matrix.yaml')]: device.shell("run-as", CLASH, "mkdir", "-p", path.split("/")[0]) device.shell("run-as", CLASH, "sh", "-c", f"cat > {path}", input=contents.encode()) - device.shell("input", "keyevent", "KEYCODE_WAKEUP") - device.shell("wm", "dismiss-keyguard") - device.shell("svc", "power", "stayon", "true") device.shell("am", "start", "-W", "-n", f"{CLASH}/rs.clash.android.MainActivity") diff --git a/.github/emulator/grant.py b/traffic-test/emulator/ksu_manager.py similarity index 74% rename from .github/emulator/grant.py rename to traffic-test/emulator/ksu_manager.py index 4bfe084..d88dfaf 100644 --- a/.github/emulator/grant.py +++ b/traffic-test/emulator/ksu_manager.py @@ -1,19 +1,13 @@ """Authorize only the installed debug app in the pinned KernelSU Manager on the CI AVD.""" import re -import subprocess import time import xml.etree.ElementTree as ET MANAGER = "me.weishu.kernelsu" -CLASH = "rs.clash.android.dev" -def shell(*args): - return subprocess.check_output(["adb", "shell", *args], text=True, timeout=30).strip() - - -def screen(): +def screen(shell): path = "/data/local/tmp/ksu-profile.xml" shell("uiautomator", "dump", path) return ET.fromstring(shell("cat", path)) @@ -24,17 +18,22 @@ def find(tree, text): and text in (n.get("text"), n.get("content-desc"))), None) -def tap(node): +def tap(shell, node): x, y, right, bottom = map(int, re.findall(r"\d+", node.get("bounds"))) shell("input", "tap", str((x + right) // 2), str((y + bottom) // 2)) -def grant(): +def authorize(device, apk, package, abi): + shell = device.shell + device.install(apk, "--abi", abi) + shell("wm", "size", "1080x2400") + shell("wm", "density", "420") + shell("am", "start", "-W", "-n", f"{MANAGER}/.ui.MainActivity") deadline = time.monotonic() + 90 while time.monotonic() < deadline: - tree = screen() + tree = screen(shell) if find(tree, "Working") is not None: - tap(find(tree, "Superuser")) + tap(shell, find(tree, "Superuser")) break else: raise RuntimeError("KernelSU Manager did not report a working kernel module") @@ -43,26 +42,20 @@ def grant(): # tree. Clash is the only installed third-party client on the fresh 1080x2400 AVD. # Always verify the package on the profile screen before touching a grant. while time.monotonic() < deadline: - tree = screen() + tree = screen(shell) if find(tree, "App Profile") is not None: - if find(tree, CLASH) is None: + if find(tree, package) is None: raise RuntimeError("Unexpected package on the KernelSU grant screen") switches = tree.findall(f".//node[@package='{MANAGER}'][@checkable='true']") if len(switches) != 1: raise RuntimeError("Unexpected KernelSU profile controls") if switches[0].get("checked") != "true": - tap(switches[0]) + tap(shell, switches[0]) break - row = find(tree, CLASH) + row = find(tree, package) if row is not None: - tap(row) + tap(shell, row) else: shell("input", "tap", "386", "640") else: raise RuntimeError("Clash profile did not open") - if shell("run-as", CLASH, "su", "-c", "'id -u'") != "0": - raise RuntimeError("Clash did not receive the KernelSU grant") - - -if __name__ == "__main__": - grant() From 53c74e95504e3012144e0e07043915c7c737f16a Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 02:05:39 +0800 Subject: [PATCH 08/11] fix(test): report Android resolver errors in probe JSON Assisted-by: Codex:GPT-6 --- .../androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt b/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt index ab0658c..b9ce3ee 100644 --- a/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt +++ b/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt @@ -1,5 +1,6 @@ package rs.clash.traffictest +import android.net.DnsResolver import android.os.Bundle import android.os.SystemClock import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -56,6 +57,8 @@ class TrafficProbeTest { result.put("error", context.resources.getResourceEntryName(e.messageRes)).put("detail", context.getString(e.messageRes, *e.args)) } catch (e: java.io.IOException) { result.put("error", e.javaClass.simpleName).put("detail", e.message) + } catch (e: DnsResolver.DnsException) { + result.put("error", e.javaClass.simpleName).put("detail", e.message).put("code", e.code) } return result.put("elapsedMs", SystemClock.elapsedRealtime() - start) } From 9810d1b677aff409a69f08971145af46aea6d62f Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 02:05:39 +0800 Subject: [PATCH 09/11] fix(ci): pass the runner's upstream DNS to the Android emulator Assisted-by: Codex:GPT-6 --- .github/emulator/prepare.sh | 8 ++++++++ traffic-test/emulator/__main__.py | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh index ade6cb6..c6ecdd4 100644 --- a/.github/emulator/prepare.sh +++ b/.github/emulator/prepare.sh @@ -30,6 +30,14 @@ chmod +x ksud echo "CLASH_TEST_RAMDISK=$work/ramdisk.img" >> "$GITHUB_ENV" echo "CLASH_TEST_KSU_MANAGER=$work/manager.apk" >> "$GITHUB_ENV" +# Use the runner's upstream DNS instead of passing systemd-resolved's loopback stub to the guest. +if [[ -r /run/systemd/resolve/resolv.conf ]]; then + dns=$(awk '$1 == "nameserver" && $2 !~ /^127\./ && $2 != "::1" { print $2; exit }' /run/systemd/resolve/resolv.conf) + if [[ -n "$dns" ]]; then + echo "CLASH_TEST_DNS_SERVER=$dns" >> "$GITHUB_ENV" + fi +fi + echo no | avdmanager create avd --name "$CLASH_TEST_AVD" --package "$package" --device pixel_6 "$ANDROID_HOME/emulator/emulator" -list-avds | grep -Fx "$CLASH_TEST_AVD" printf 'KERNEL=="kvm", OWNER="%s", GROUP="kvm", MODE="0660", OPTIONS+="static_node=kvm"\n' "$(id -un)" \ diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index cddbfc9..ffab7d8 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -104,9 +104,11 @@ def emulator(sdk, directory): console.listen(1) console.settimeout(1) report = f"tcp:{console.getsockname()[1]},max=60" + dns_server = os.environ.get("CLASH_TEST_DNS_SERVER") + dns_args = ["-dns-server", dns_server] if dns_server else [] process = subprocess.Popen([sdk / "emulator" / ("emulator" + binary), "-avd", name, "-ramdisk", ramdisk.resolve(), "-read-only", "-no-snapshot", - "-no-window", "-no-audio", "-no-boot-anim", "-report-console", report], + "-no-window", "-no-audio", "-no-boot-anim", "-report-console", report, *dns_args], stdin=subprocess.DEVNULL, stdout=log, stderr=log) device = None try: From 2424525a25aa168d67525a7191768b8356781435 Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 11:43:21 +0800 Subject: [PATCH 10/11] fix(test): wait for app networking before the initial emulator baseline Assisted-by: Codex:GPT-6 --- traffic-test/emulator/__main__.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index ffab7d8..c88f93e 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -312,7 +312,26 @@ def measure(device, case, logs): def baseline(device, logs, report, name): case = report[name] = dict(mode="off", ipv6=True, fakeIp=False) case["network"] = wait_network(device, "off") - measure(device, case, logs) + # A fresh AVD can reach sys.boot_completed before Android routes app traffic. + # Wait only for the initial unproxied probe. Every matrix case and the final + # restoration check must pass on their first measurement. + deadline = time.monotonic() + 120 + while True: + try: + measure(device, case, logs) + return + except AssertionError: + if name != "before" or time.monotonic() >= deadline: + raise + results = case["probes"] + transient = {"ConnectException", "NoRouteToHostException", "SocketException", + "PortUnreachableException", "DnsException", "timeout"} + checks = [results[family][protocol] for family in ("v4", "v6") for protocol in ("tcp", "udp")] + checks.append(results["dns"]) + if not any(check.get("error") in transient for check in checks): + raise + print("Waiting for the initial unproxied network", flush=True) + time.sleep(2) def check_settings(device, mode, ipv6, fake_ip): From f6ec3bceb6f6512048787601af7bf131acdca89a Mon Sep 17 00:00:00 2001 From: iHsin Date: Sat, 5 Dec 2026 11:59:29 +0800 Subject: [PATCH 11/11] fix(test): tolerate transient Android network state read failures Assisted-by: Codex:GPT-6 --- traffic-test/emulator/__main__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index c88f93e..5678956 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -228,9 +228,14 @@ def network(device): def wait_network(device, mode, ipv6=False): vpn, tproxy = mode == "vpn", mode == "tproxy" wanted = dict(tun=vpn, tun4=vpn, tun6=vpn and ipv6, v4=tproxy, v6=tproxy and ipv6, block6=tproxy and not ipv6) - last = {} + last = None def ready(): - last.update(network(device)) + nonlocal last + try: + last = network(device) + except (RuntimeError, subprocess.TimeoutExpired) as error: + last = str(error) + return None return last if last == wanted else None try: return wait_for(ready, f"{mode} network")