diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5bc277b..45685cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -81,7 +81,7 @@ adb devices Enable USB debugging on a physical device and authorize your computer, or start an emulator first. You can also select `app` and the target device in Android Studio and run it there. -The debug APK is generated at `app/build/outputs/apk/debug/app-debug.apk`. Its package name is `com.powercess.mbrain.debug`, so it can coexist with the release app. Local development does not require release signing materials. If installation fails because of a signature mismatch, first check the source of the installed test package. Uninstalling it will erase its app data. +The debug APK is generated at `app/build/outputs/apk/debug/app-debug.apk`. Its fixed package name is `com.powercess.mbrain.dev`, and its launcher label is `MBrain 开发版`, so it can coexist with the release app. Keep this identity across versions; do not override it with version numbers or temporary task names. Local development does not require release signing materials. Reuse your local debug keystore so updates retain the same signing identity. If installation fails because of a signature mismatch, first check the source of the installed test package. Uninstalling it will erase its app data. After opening the app, start the gateway from the home screen and open the connection address and credentials section to get the actual address and token. Basic device information does not require Root. Prepare Root or Shizuku and grant MBrain access separately only when testing capabilities that require elevated permissions. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index c8bd12e..27c2427 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -10,17 +10,20 @@ android { compileSdk = libs.versions.compileSdk.get().toInt() defaultConfig { applicationId = "com.powercess.mbrain" + manifestPlaceholders["appLabel"] = "MBrain" minSdk = libs.versions.minSdk.get().toInt() targetSdk = libs.versions.targetSdk.get().toInt() - versionCode = 4 - versionName = "0.2.0" + versionCode = 5 + versionName = "0.3.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildFeatures { compose = true; buildConfig = true } buildTypes { getByName("debug") { - applicationIdSuffix = ".debug" - versionNameSuffix = "-debug" + // Stable development identity across versions; never use per-release suffixes. + applicationIdSuffix = ".dev" + versionNameSuffix = "-dev" + manifestPlaceholders["appLabel"] = "MBrain 开发版" } } compileOptions { diff --git a/app/src/androidTest/java/com/powercess/mbrain/control/ClipboardDeviceSmoke.java b/app/src/androidTest/java/com/powercess/mbrain/control/ClipboardDeviceSmoke.java new file mode 100644 index 0000000..354feb1 --- /dev/null +++ b/app/src/androidTest/java/com/powercess/mbrain/control/ClipboardDeviceSmoke.java @@ -0,0 +1,48 @@ +package com.powercess.mbrain.control; + +import android.content.ClipData; +import android.os.IBinder; +import java.lang.reflect.Method; +import org.json.JSONObject; + +/** Keeps the original ClipData exclusively in device RAM. Never serializes or prints it. */ +public final class ClipboardDeviceSmoke { + public static void run() throws Exception { + if (android.os.Looper.getMainLooper() == null) android.os.Looper.prepareMainLooper(); + IBinder binder = (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "clipboard"); + Object service = Class.forName("android.content.IClipboard$Stub").getMethod("asInterface", IBinder.class).invoke(null, binder); + int user = (Integer) Class.forName("android.app.ActivityManager").getMethod("getCurrentUser").invoke(null); + Method getter = method("getPrimaryClip"), setter = method("setPrimaryClip"), clear = method("clearPrimaryClip"); + ClipData original = (ClipData) getter.invoke(service, arguments(getter, user, null)); + // Invoke production code locally: only pass/fail ever crosses ADB. + Method operation = PhoneControlMain.class.getDeclaredMethod("clipboard", String.class, JSONObject.class); + operation.setAccessible(true); + PhoneControlMain helper = new PhoneControlMain(); + String expected = "MBrain 中文😀 clipboard QA"; + try { + operation.invoke(helper, "clipboard_set", new JSONObject().put("value", expected)); + JSONObject reply = (JSONObject) operation.invoke(helper, "clipboard_get", new JSONObject()); + if (!expected.equals(reply.optString("text"))) throw new IllegalStateException("Clipboard roundtrip mismatch"); + System.out.println("PASS clipboard Unicode roundtrip (device-local)"); + } finally { + if (original != null) setter.invoke(service, arguments(setter, user, original)); + else clear.invoke(service, arguments(clear, user, null)); + } + } + private static Method method(String name) throws Exception { + for (Method method : Class.forName("android.content.IClipboard").getMethods()) if (method.getName().equals(name)) return method; + throw new NoSuchMethodException(name); + } + private static Object[] arguments(Method method, int user, ClipData clip) { + Object[] result = new Object[method.getParameterCount()]; + int strings = 0, ints = 0; + for (int i = 0; i < result.length; i++) { + Class type = method.getParameterTypes()[i]; + if (type == String.class) result[i] = strings++ == 0 ? "com.android.shell" : null; + else if (type == int.class) result[i] = ints++ == 0 ? user : 0; + else if (type == ClipData.class) result[i] = clip; + else throw new IllegalStateException("Unknown clipboard signature"); + } + return result; + } +} diff --git a/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilityGatewayTest.kt b/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilityGatewayTest.kt new file mode 100644 index 0000000..8618f5f --- /dev/null +++ b/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilityGatewayTest.kt @@ -0,0 +1,89 @@ +package com.powercess.mbrain.control + +import android.content.Intent +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.powercess.mbrain.MainActivity +import com.powercess.mbrain.gateway.GatewayRuntime +import com.powercess.mbrain.gateway.MBrainService +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL + +/** Opt-in real Shizuku + authenticated MCP test. Credentials never leave the device. */ +@RunWith(AndroidJUnit4::class) +class CapabilityGatewayTest { + @Test fun shizukuToolsAreCallableThroughAuthenticatedGateway() { + assumeTrue("Enable with -e capabilityGateway true after granting test app Shizuku", + InstrumentationRegistry.getArguments().getString("capabilityGateway") == "true") + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + require(context.packageName == "com.powercess.mbrain.dev") + val activity = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + try { + await { GatewayRuntime.status.value.shizukuReady } + assertTrue("Enable Shizuku in the test app first", GatewayRuntime.config.value.shizukuEnabled) + instrumentation.runOnMainSync { context.startForegroundService(Intent(context, MBrainService::class.java)) } + await { GatewayRuntime.status.value.running && GatewayRuntime.status.value.tools.any { it.name == "shizuku_ui_dump" } } + val status = GatewayRuntime.status.value + var session: String? = null + var id = 0 + fun rpc(method: String, params: JsonObject): JsonObject { + val connection = URL(status.endpoint).openConnection() as HttpURLConnection + try { + connection.requestMethod = "POST" + connection.doOutput = true + connection.connectTimeout = 5000 + connection.readTimeout = 30000 + connection.setRequestProperty("Authorization", "Bearer ${status.token}") + connection.setRequestProperty("Content-Type", "application/json") + connection.setRequestProperty("Accept", "application/json, text/event-stream") + session?.let { connection.setRequestProperty("Mcp-Session-Id", it) } + val body = buildJsonObject { put("jsonrpc", "2.0"); put("id", ++id); put("method", method); put("params", params) } + connection.outputStream.use { it.write(body.toString().toByteArray()) } + assertEquals("HTTP status for $method", 200, connection.responseCode) + connection.getHeaderField("Mcp-Session-Id")?.let { session = it } + val response = Json.parseToJsonElement(connection.inputStream.bufferedReader().use { it.readText() }).jsonObject + assertFalse("RPC error for $method", response.containsKey("error")) + return response.getValue("result").jsonObject + } finally { connection.disconnect() } + } + rpc("initialize", buildJsonObject { + put("protocolVersion", "2024-11-05"); put("capabilities", buildJsonObject {}) + put("clientInfo", buildJsonObject { put("name", "capability-device-test"); put("version", "1") }) + }) + val names = rpc("tools/list", buildJsonObject {}).getValue("tools").jsonArray.map { it.jsonObject.getValue("name").jsonPrimitive.content } + val required = listOf("ui_dump", "ui_click", "ui_long_click", "ui_set_text", "ui_swipe", "ui_navigate", "ui_wait", "clipboard_get", "clipboard_set", + "logs_query", "appops_get", "appops_set", "proc_list", "app_resource_usage", "net_status", "net_diagnose") + required.forEach { assertTrue("Missing tool $it", "shizuku_$it" in names) } + fun call(name: String, params: JsonObject = buildJsonObject {}) { + val result = rpc("tools/call", buildJsonObject { put("name", "shizuku_$name"); put("arguments", params) }) + assertNotEquals("Tool failed: $name", true, result["isError"]?.jsonPrimitive?.booleanOrNull) + assertTrue("Missing tool content: $name", result.getValue("content").jsonArray.isNotEmpty()) + } + call("ui_dump", buildJsonObject { put("limit", 5) }) + call("ui_wait", buildJsonObject { put("text", "MBrain"); put("package", context.packageName); put("timeout_ms", 2000) }) + call("logs_query", buildJsonObject { put("tag", "MBrainSmoke"); put("lines", 5) }) + call("appops_get", buildJsonObject { put("package", context.packageName); put("op", "VIBRATE") }) + call("proc_list", buildJsonObject { put("package", context.packageName) }) + call("app_resource_usage", buildJsonObject { put("package", context.packageName) }) + call("net_status") + call("net_diagnose", buildJsonObject { put("host", "localhost"); put("port", status.port!!) }) + call("ui_click", buildJsonObject { put("text", "能力"); put("package", context.packageName) }) + call("ui_wait", buildJsonObject { put("text", "手机能力"); put("timeout_ms", 2000) }) + } finally { + instrumentation.runOnMainSync { context.stopService(Intent(context, MBrainService::class.java)); activity.finish() } + } + } + private fun await(condition: () -> Boolean) { + val deadline = android.os.SystemClock.uptimeMillis() + 10000 + while (!condition()) { + check(android.os.SystemClock.uptimeMillis() < deadline) { "Gateway/Shizuku did not become ready" } + Thread.sleep(100) + } + } +} diff --git a/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilitySmokeMain.kt b/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilitySmokeMain.kt new file mode 100644 index 0000000..911c449 --- /dev/null +++ b/app/src/androidTest/kotlin/com/powercess/mbrain/control/CapabilitySmokeMain.kt @@ -0,0 +1,57 @@ +package com.powercess.mbrain.control + +import com.powercess.mbrain.shell.DiagnosticTools +import io.droidmcp.shell.ShellBackend +import io.droidmcp.shell.ShellResult +import kotlinx.coroutines.runBlocking + +/** Device-only smoke entry point. Run via app_process with app + test APKs on CLASSPATH. */ +object CapabilitySmokeMain { + @JvmStatic fun main(args: Array) = runBlocking { + try { + require(args.size == 2) { "Usage: APK_PATH TEST_PACKAGE" } + val shell = object : ShellBackend { + override val name = "device-shell" + override fun isAvailable() = true + override suspend fun exec(command: String, args: List): ShellResult { + val process = ProcessBuilder(listOf(command) + args).start() + var stderr = "" + val reader = Thread { stderr = process.errorStream.bufferedReader().use { it.readText() } }.apply { start() } + val stdout = process.inputStream.use { it.readBytes() } + val exit = process.waitFor() + reader.join() + return ShellResult(exit, stdout, stderr) + } + } + val diagnostic = DiagnosticTools.all(shell).associateBy { it.name } + suspend fun checkCall(name: String, params: Map = emptyMap()) { + val result = diagnostic.getValue(name).execute(params) + check(result.isSuccess) { "$name: ${result.errorMessage}" } + println("PASS $name") + } + checkCall("logs_query", mapOf("lines" to 5, "tag" to "MBrainSmoke")) + checkCall("appops_get", mapOf("package" to args[1], "op" to "VIBRATE")) + // Dedicated test package only; preserve the original mode on-device. + val before = shell.exec("cmd", listOf("appops", "get", args[1], "VIBRATE")).stdout + val mode = Regex("VIBRATE: (allow|ignore|deny|default|foreground)").find(before)?.groupValues?.get(1) ?: "default" + try { checkCall("appops_set", mapOf("package" to args[1], "op" to "VIBRATE", "mode" to "ignore")) } + finally { shell.exec("cmd", listOf("appops", "set", args[1], "VIBRATE", mode)) } + checkCall("proc_list", mapOf("package" to args[1])) + checkCall("app_resource_usage", mapOf("package" to args[1])) + checkCall("net_status") + val network = PhoneTools.all(shell, args[0]).first { it.name == "net_diagnose" } + val result = network.execute(mapOf("host" to "localhost", "port" to 1)) + check(result.isSuccess) + check((result.data!!["dns"] as Map<*, *>)["ok"] == true) + check((result.data!!["tcp"] as Map<*, *>)["ok"] == false) + println("PASS net_diagnose DNS success and TCP failure") + ClipboardDeviceSmoke.run() + println("CAPABILITY_SMOKE_OK") + System.exit(0) + } catch (failure: Throwable) { + // Do not print tool payloads: logs and clipboard can contain private data. + System.err.println("CAPABILITY_SMOKE_FAILED: ${failure.javaClass.simpleName}: ${failure.message}") + System.exit(1) + } + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3b74617..e2ee40e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@ - connectionType = Class.forName("android.app.IUiAutomationConnection"); + Object connection = Class.forName("android.app.UiAutomationConnection").getConstructor().newInstance(); + automation = UiAutomation.class.getConstructor(Looper.class, connectionType) + .newInstance(callbacks.getLooper(), connection); + UiAutomation.class.getMethod("connect", int.class).invoke(automation, + UiAutomation.FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES); + AccessibilityServiceInfo info = automation.getServiceInfo(); + info.flags |= AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS + | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS; + automation.setServiceInfo(info); + } + + private JSONObject control(String operation, JSONObject params) throws Exception { + connect(); + switch (operation) { + case "ui_dump": return dump(params); + case "ui_wait": return waitFor(params); + case "ui_click": case "ui_long_click": case "ui_set_text": return nodeAction(operation, params); + case "ui_swipe": return swipe(params); + case "ui_navigate": { + String action = params.getString("action"); + int code; + switch (action) { + case "back": code = AccessibilityService.GLOBAL_ACTION_BACK; break; + case "home": code = AccessibilityService.GLOBAL_ACTION_HOME; break; + case "recents": code = AccessibilityService.GLOBAL_ACTION_RECENTS; break; + case "notifications": code = AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS; break; + case "quick_settings": code = AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS; break; + default: throw new IllegalArgumentException("Unknown navigation action"); + } + if (!automation.performGlobalAction(code)) throw new IllegalStateException("Navigation rejected"); + return new JSONObject().put("performed", true).put("action", action); + } + default: throw new IllegalArgumentException("Unknown operation: " + operation); + } + } + + private static final class Node { + final AccessibilityNodeInfo info; + final int parent; + Node(AccessibilityNodeInfo info, int parent) { this.info = info; this.parent = parent; } + } + + private static final class UiUnavailable extends IllegalStateException { + UiUnavailable() { super("ui_unavailable: No active window; unlock the device and retry"); } + } + + private List snapshot() { + AccessibilityNodeInfo root = automation.getRootInActiveWindow(); + // Connection registration can finish before the active window is published. + long deadline = SystemClock.uptimeMillis() + 1000; + while (root == null && SystemClock.uptimeMillis() < deadline) { + SystemClock.sleep(100); + root = automation.getRootInActiveWindow(); + } + if (root == null) throw new UiUnavailable(); + List nodes = new ArrayList<>(); + nodes.add(new Node(root, -1)); + for (int i = 0; i < nodes.size() && nodes.size() < MAX_NODES; i++) { + AccessibilityNodeInfo node = nodes.get(i).info; + for (int child = 0; child < node.getChildCount() && nodes.size() < MAX_NODES; child++) { + AccessibilityNodeInfo next = node.getChild(child); + if (next != null) nodes.add(new Node(next, i)); + } + } + return nodes; + } + + private static void recycle(List nodes) { + for (Node node : nodes) node.info.recycle(); + } + + private JSONObject describe(Node item, int index) throws Exception { + AccessibilityNodeInfo node = item.info; + Rect bounds = new Rect(); node.getBoundsInScreen(bounds); + return new JSONObject().put("index", index).put("parent", item.parent) + .put("text", node.isPassword() ? "" : bounded(node.getText())) + .put("description", bounded(node.getContentDescription())) + .put("resource_id", value(node.getViewIdResourceName())) + .put("class", value(node.getClassName())).put("package", value(node.getPackageName())) + .put("bounds", new JSONArray(new int[]{bounds.left, bounds.top, bounds.right, bounds.bottom})) + .put("clickable", node.isClickable()).put("long_clickable", node.isLongClickable()) + .put("editable", node.isEditable()).put("scrollable", node.isScrollable()) + .put("enabled", node.isEnabled()).put("visible", node.isVisibleToUser()) + .put("focused", node.isFocused()).put("password", node.isPassword()); + } + + private JSONObject dump(JSONObject params) throws Exception { + List nodes = snapshot(); + try { + int limit = integer(params, "limit", 50, 1, 60); + int offset = integer(params, "offset", 0, 0, MAX_NODES - 1); + JSONArray result = new JSONArray(); + int end = Math.min(nodes.size(), offset + limit); + for (int i = offset; i < end; i++) result.put(describe(nodes.get(i), i)); + return new JSONObject().put("nodes", result).put("count", nodes.size()) + .put("next_offset", end < nodes.size() ? end : JSONObject.NULL) + .put("truncated", nodes.size() == MAX_NODES) + .put("note", "Indices describe this snapshot only. Select actions by text/resource_id/description."); + } finally { recycle(nodes); } + } + + private List matches(List nodes, JSONObject params) throws Exception { + if (!params.has("text") && !params.has("resource_id") && !params.has("description")) + throw new IllegalArgumentException("Supply text, resource_id or description selector"); + List result = new ArrayList<>(); + for (int i = 0; i < nodes.size(); i++) { + AccessibilityNodeInfo node = nodes.get(i).info; + if (!node.isVisibleToUser()) continue; + if (params.has("text") && (node.isPassword() || !match(value(node.getText()), params.getString("text"), params.optBoolean("contains", false)))) continue; + if (params.has("resource_id") && !value(node.getViewIdResourceName()).equals(params.getString("resource_id"))) continue; + if (params.has("description") && !match(value(node.getContentDescription()), params.getString("description"), params.optBoolean("contains", false))) continue; + if (params.has("package") && !value(node.getPackageName()).equals(params.getString("package"))) continue; + result.add(i); + } + return result; + } + + private static boolean match(String actual, String expected, boolean contains) { + return contains ? actual.contains(expected) : actual.equals(expected); + } + + private JSONObject nodeAction(String operation, JSONObject params) throws Exception { + if (params.has("x") || params.has("y")) { + if (operation.equals("ui_set_text")) throw new IllegalArgumentException("Text input requires a node selector"); + for (String key : new String[]{"text", "resource_id", "description", "package", "index", "contains"}) { + if (params.has(key)) throw new IllegalArgumentException("Use coordinates OR a selector"); + } + int x = integer(params, "x", -1, 0, 20000), y = integer(params, "y", -1, 0, 20000); + gesture(x, y, x, y, operation.equals("ui_long_click") ? 800 : 70); + return new JSONObject().put("performed", true); + } + List nodes = snapshot(); + try { + List found = matches(nodes, params); + if (found.isEmpty()) throw new IllegalStateException("node_not_found"); + if (found.size() > 1 && !params.has("index")) throw new IllegalArgumentException("ambiguous_selector: " + found.size() + " matches; supply zero-based index"); + int index = integer(params, "index", 0, 0, found.size() - 1); + int position = found.get(index); + AccessibilityNodeInfo target = nodes.get(position).info; + int action = operation.equals("ui_set_text") ? AccessibilityNodeInfo.ACTION_SET_TEXT + : operation.equals("ui_long_click") ? AccessibilityNodeInfo.ACTION_LONG_CLICK : AccessibilityNodeInfo.ACTION_CLICK; + while (position >= 0 && !(operation.equals("ui_set_text") ? target.isEditable() + : operation.equals("ui_long_click") ? target.isLongClickable() : target.isClickable())) { + position = nodes.get(position).parent; + if (position >= 0) target = nodes.get(position).info; + } + if (position < 0) throw new IllegalStateException("No actionable ancestor for " + operation); + if (!target.isEnabled()) throw new IllegalStateException("Target is disabled"); + Bundle args = new Bundle(); + if (operation.equals("ui_set_text")) { + String content = params.getString("value"); + if (content.length() > 16000) throw new IllegalArgumentException("Text exceeds 16000 characters"); + args.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, content); + } + if (!target.performAction(action, args)) throw new IllegalStateException("action_rejected: Refresh ui_dump and retry with another selector"); + return new JSONObject().put("performed", true).put("matched_count", found.size()); + } finally { recycle(nodes); } + } + + private JSONObject waitFor(JSONObject params) throws Exception { + int timeout = integer(params, "timeout_ms", 5000, 0, 15000); + String state = params.optString("state", "present"); + if (!state.equals("present") && !state.equals("absent")) throw new IllegalArgumentException("state must be present or absent"); + long start = SystemClock.uptimeMillis(); + do { + List nodes = null; + try { + nodes = snapshot(); + List found = matches(nodes, params); + if (state.equals("absent") == found.isEmpty()) { + JSONObject result = new JSONObject().put("matched", true).put("state", state) + .put("elapsed_ms", SystemClock.uptimeMillis() - start); + if (!found.isEmpty()) result.put("node", describe(nodes.get(found.get(0)), found.get(0))); + return result; + } + } catch (UiUnavailable unavailable) { + // During activity transitions there may briefly be no root. This is not + // evidence of an absent selector; continue until a real tree or timeout. + } finally { if (nodes != null) recycle(nodes); } + if (SystemClock.uptimeMillis() - start >= timeout) break; + SystemClock.sleep(Math.min(250, timeout - (SystemClock.uptimeMillis() - start))); + } while (true); + throw new IllegalStateException("wait_timeout: condition not met after " + timeout + "ms"); + } + + private JSONObject swipe(JSONObject params) throws Exception { + gesture(integer(params, "x1", -1, 0, 20000), integer(params, "y1", -1, 0, 20000), + integer(params, "x2", -1, 0, 20000), integer(params, "y2", -1, 0, 20000), + integer(params, "duration_ms", 350, 50, 3000)); + return new JSONObject().put("performed", true); + } + + private void gesture(int x1, int y1, int x2, int y2, int duration) throws Exception { + // Default display only; use current real display dimensions (including system bars). + Object manager = Class.forName("android.hardware.display.DisplayManagerGlobal").getMethod("getInstance").invoke(null); + android.view.Display display = (android.view.Display) manager.getClass().getMethod("getRealDisplay", int.class).invoke(manager, 0); + android.graphics.Point size = new android.graphics.Point(); display.getRealSize(size); + if (x1 >= size.x || x2 >= size.x || y1 >= size.y || y2 >= size.y) throw new IllegalArgumentException("Coordinates outside " + size.x + "x" + size.y); + long down = SystemClock.uptimeMillis(); + inject(down, MotionEvent.ACTION_DOWN, x1, y1); + boolean completed = false; + try { + int steps = Math.max(1, duration / 16); + for (int step = 1; step <= steps; step++) { + long delay = down + (long) duration * step / steps - SystemClock.uptimeMillis(); + if (delay > 0) SystemClock.sleep(delay); + float fraction = (float) step / steps; + if (x1 != x2 || y1 != y2) inject(down, MotionEvent.ACTION_MOVE, x1 + (x2 - x1) * fraction, y1 + (y2 - y1) * fraction); + } + inject(down, MotionEvent.ACTION_UP, x2, y2); + completed = true; + } finally { + if (!completed) inject(down, MotionEvent.ACTION_CANCEL, x2, y2); + } + } + + private void inject(long down, int action, float x, float y) { + MotionEvent event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action, x, y, 0); + event.setSource(InputDevice.SOURCE_TOUCHSCREEN); + try { if (!automation.injectInputEvent(event, true)) throw new IllegalStateException("Input injection rejected"); } + finally { event.recycle(); } + } + + private JSONObject clipboard(String operation, JSONObject params) throws Exception { + if (!operation.equals("clipboard_get") && !operation.equals("clipboard_set")) throw new IllegalArgumentException("Unknown clipboard operation"); + IBinder binder = (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, "clipboard"); + Object service = Class.forName("android.content.IClipboard$Stub").getMethod("asInterface", IBinder.class).invoke(null, binder); + String methodName = operation.equals("clipboard_get") ? "getPrimaryClip" : "setPrimaryClip"; + Method selected = null; + for (Method method : Class.forName("android.content.IClipboard").getMethods()) { + if (method.getName().equals(methodName)) { selected = method; break; } + } + if (selected == null) throw new UnsupportedOperationException("Clipboard interface unavailable"); + int user = (Integer) Class.forName("android.app.ActivityManager").getMethod("getCurrentUser").invoke(null); + Object[] args = new Object[selected.getParameterCount()]; + int strings = 0, ints = 0; + for (int i = 0; i < args.length; i++) { + Class type = selected.getParameterTypes()[i]; + if (type == String.class) args[i] = strings++ == 0 ? "com.android.shell" : null; + else if (type == int.class) args[i] = ints++ == 0 ? user : 0; + else if (type == ClipData.class) { + String text = params.getString("value"); + if (text.length() > 16000) throw new IllegalArgumentException("Clipboard exceeds 16000 characters"); + args[i] = ClipData.newPlainText("MBrain", text); + } else throw new UnsupportedOperationException("Unsupported clipboard signature"); + } + Object result = selected.invoke(service, args); + if (operation.equals("clipboard_set")) return new JSONObject().put("written", true); + ClipData clip = (ClipData) result; + if (clip == null) return new JSONObject().put("available", false).put("text", JSONObject.NULL) + .put("note", "Clipboard is empty or access was denied by the system"); + CharSequence text = clip.getItemCount() > 0 ? clip.getItemAt(0).getText() : null; + if (text == null) return new JSONObject().put("available", true).put("text", JSONObject.NULL).put("item_count", clip.getItemCount()); + String content = text.toString(); + return new JSONObject().put("available", true).put("text", content.substring(0, Math.min(16000, content.length()))) + .put("truncated", content.length() > 16000).put("item_count", clip.getItemCount()); + } + + private static String value(CharSequence value) { return value == null ? "" : value.toString(); } + private JSONObject network(JSONObject params) throws Exception { + String host = params.getString("host"); + if (host.length() > 253 || !host.matches("[A-Za-z0-9:.%-]+") || host.startsWith("-")) + throw new IllegalArgumentException("Invalid host; supply a hostname or IP without scheme/path"); + int port = integer(params, "port", 443, 1, 65535); + java.util.concurrent.ExecutorService worker = java.util.concurrent.Executors.newSingleThreadExecutor(); + JSONObject result = new JSONObject().put("host", host).put("port", port); + long start = SystemClock.uptimeMillis(); + try { + java.util.concurrent.Future lookup = worker.submit(() -> java.net.InetAddress.getAllByName(host)); + java.net.InetAddress[] addresses; + try { addresses = lookup.get(4, java.util.concurrent.TimeUnit.SECONDS); } + catch (Exception error) { + lookup.cancel(true); + return result.put("dns", new JSONObject().put("ok", false).put("error", error.toString())) + .put("tcp", new JSONObject().put("attempted", false)); + } + JSONArray resolved = new JSONArray(); + for (java.net.InetAddress address : addresses) resolved.put(address.getHostAddress()); + result.put("dns", new JSONObject().put("ok", true).put("addresses", resolved) + .put("elapsed_ms", SystemClock.uptimeMillis() - start)); + JSONArray attempts = new JSONArray(); + boolean connected = false; + for (int i = 0; i < Math.min(3, addresses.length); i++) { + long tcpStart = SystemClock.uptimeMillis(); + JSONObject attempt = new JSONObject().put("address", addresses[i].getHostAddress()); + try (java.net.Socket socket = new java.net.Socket()) { + socket.connect(new java.net.InetSocketAddress(addresses[i], port), 2000); + attempt.put("ok", true); connected = true; + } catch (Exception error) { attempt.put("ok", false).put("error", error.toString()); } + attempt.put("elapsed_ms", SystemClock.uptimeMillis() - tcpStart); + attempts.put(attempt); + if (connected) break; + } + return result.put("tcp", new JSONObject().put("attempted", true).put("ok", connected).put("attempts", attempts)); + } finally { worker.shutdownNow(); } + } + + private static String bounded(CharSequence value) { String text = value(value); return text.substring(0, Math.min(200, text.length())); } + private static int integer(JSONObject params, String key, int fallback, int min, int max) throws Exception { + Object raw = params.has(key) ? params.get(key) : fallback; + if (!(raw instanceof Number)) throw new IllegalArgumentException(key + " must be an integer"); + double number = ((Number) raw).doubleValue(); + if (!Double.isFinite(number) || number != Math.rint(number) || number < min || number > max) + throw new IllegalArgumentException(key + " must be between " + min + " and " + max); + return (int) number; + } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/control/PhoneTools.kt b/app/src/main/kotlin/com/powercess/mbrain/control/PhoneTools.kt new file mode 100644 index 0000000..fc271f8 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/control/PhoneTools.kt @@ -0,0 +1,97 @@ +package com.powercess.mbrain.control + +import io.droidmcp.core.* +import io.droidmcp.shell.ShellBackend +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.json.* + +/** One UI automation connection at a time, shared by both privileged backends. */ +object PhoneTools { + private val session = Mutex() + fun all(shell: ShellBackend, apkPath: String): List = operations.map { (name, spec) -> + object : McpTool { + override val name = name + override val description = spec.description + override val parameters = spec.parameters + override val annotations = ToolAnnotations(readOnlyHint = spec.readOnly, destructiveHint = !spec.readOnly, openWorldHint = name == "net_diagnose") + override suspend fun execute(params: Map): ToolResult = try { + val unknown = params.keys - parameters.map { it.name }.toSet() + require(unknown.isEmpty()) { "Unknown arguments: ${unknown.joinToString()}" } + parameters.forEach { parameter -> + val value = params[parameter.name] + require(value != null || !parameter.required) { "${parameter.name} is required" } + if (value != null) require(when (parameter.type) { + ParameterType.STRING -> value is String + ParameterType.BOOLEAN -> value is Boolean + ParameterType.INTEGER -> value is Number && value.toDouble().isFinite() && value.toDouble() == value.toLong().toDouble() + else -> false + }) { "Invalid ${parameter.name}" } + } + params.values.filterIsInstance().forEach { require(it.length <= 16000 && '\u0000' !in it) { "Text too long or contains NUL" } } + session.withLock { + val response = shell.exec("/system/bin/env", listOf("CLASSPATH=$apkPath", "/system/bin/app_process", + "/system/bin", "com.powercess.mbrain.control.PhoneControlMain", name, buildJsonObject { + params.forEach { (key, value) -> put(key, when (value) { + is Boolean -> JsonPrimitive(value) + is Number -> JsonPrimitive(value) + else -> JsonPrimitive(value.toString()) + }) } + }.toString())) + if (!response.isSuccess) ToolResult.error("phone_control_failed", response.stderr.take(2000)) + else decodePhoneReply(response.stdout) + } + } catch (cancel: CancellationException) { throw cancel } + catch (error: Exception) { ToolResult.error("phone_control_failed", error.message) } + } + } + + private data class Spec(val description: String, val parameters: List, val readOnly: Boolean = false) + private fun string(name: String, description: String, required: Boolean = false) = ToolParameter(name, description, ParameterType.STRING, required) + private fun number(name: String, description: String, required: Boolean = false) = ToolParameter(name, description, ParameterType.INTEGER, required) + private val selector = listOf( + string("text", "Exact node text; at least one of text/resource_id/description required"), + string("resource_id", "Full Android view resource ID"), + string("description", "Accessibility content description"), + string("package", "Restrict selector to this package"), + ToolParameter("contains", "Substring match for text/description; default false", ParameterType.BOOLEAN), + ) + private val actionSelector = selector + number("index", "Zero-based occurrence among matches; required when ambiguous (NOT dump node index)") + private val coordinates = listOf(number("x", "Default-display pixel X; use coordinates OR selector"), number("y", "Default-display pixel Y")) + private val operations = linkedMapOf( + "ui_dump" to Spec("Read the active window's node tree, text, bounds and actions. Paginated live snapshot; default display. Requires Root/Shizuku, no accessibility service setup.", + listOf(number("offset", "Node offset, default 0"), number("limit", "Page size 1..60, default 50")), true), + "ui_click" to Spec("Click a visible node (or nearest clickable ancestor), or pixel coordinates. Ambiguous selectors fail unless index supplied.", actionSelector + coordinates), + "ui_long_click" to Spec("Long-click a visible node (or actionable ancestor), or hold coordinates for 800ms.", actionSelector + coordinates), + "ui_set_text" to Spec("Replace an editable node's text with Unicode, including Chinese and emoji. Empty value clears it; does not submit. Use ui_wait/dump to verify.", + actionSelector + string("value", "Replacement text, up to 16000 characters", true)), + "ui_swipe" to Spec("Swipe between default-display pixel coordinates. Coordinates follow current screen rotation.", + listOf(number("x1", "Start X", true), number("y1", "Start Y", true), number("x2", "End X", true), number("y2", "End Y", true), number("duration_ms", "50..3000; default 350"))), + "ui_navigate" to Spec("Perform Android navigation: back, home, recents, notifications or quick_settings.", + listOf(string("action", "back | home | recents | notifications | quick_settings", true))), + "ui_wait" to Spec("Wait for a visible node to appear or disappear; polls a fresh tree every 250ms. Timeout is an error, not success.", + selector + listOf(string("state", "present (default) or absent"), number("timeout_ms", "0..15000, default 5000")), true), + "clipboard_get" to Spec("Read first clipboard text item for the current Android user. Returns available=false when empty or system-denied; non-text content is not dereferenced.", emptyList(), true), + "clipboard_set" to Spec("Replace clipboard text for the current Android user, including Chinese and emoji.", listOf(string("value", "Text, up to 16000 characters", true))), + "net_diagnose" to Spec("Diagnose DNS resolution and TCP connectivity from the selected Root/Shizuku backend. Returns per-stage status; DNS/TCP failure is a diagnostic result. No HTTP request is sent.", + listOf(string("host", "Hostname or IP without scheme/path", true), number("port", "TCP port 1..65535; default 443")), true), + ) +} + +internal fun decodePhoneReply(output: String): ToolResult { + val envelope = output.lineSequence().lastOrNull { it.startsWith("MBRAIN_RESULT:") } + ?: return ToolResult.error("phone_control_protocol", "Helper returned no result") + return try { + val reply = Json.parseToJsonElement(envelope.removePrefix("MBRAIN_RESULT:")).jsonObject + if (reply["ok"]?.jsonPrimitive?.booleanOrNull != true) ToolResult.error("phone_control_failed", reply["error"]?.jsonPrimitive?.content) + else ToolResult.success(reply.getValue("data").jsonObject.mapValues { jsonValue(it.value) }) + } catch (_: Exception) { ToolResult.error("phone_control_protocol", "Invalid helper result") } +} + +private fun jsonValue(value: JsonElement): Any? = when (value) { + JsonNull -> null + is JsonObject -> value.mapValues { jsonValue(it.value) } + is JsonArray -> value.map(::jsonValue) + is JsonPrimitive -> if (value.isString) value.content else value.booleanOrNull ?: value.longOrNull ?: value.doubleOrNull ?: value.content +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt b/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt index 7a6a48f..e57efda 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt @@ -4,6 +4,7 @@ import android.content.Context import com.powercess.mbrain.data.* import com.powercess.mbrain.mcp.* import com.powercess.mbrain.shell.* +import com.powercess.mbrain.control.PhoneTools import com.powercess.mbrain.remote.SecretStore import io.droidmcp.apps.AppsTools import io.droidmcp.core.* @@ -217,6 +218,8 @@ object GatewayRuntime { add(ShellCommandTool(backend, prefix)) addAll(ShellTools.all(context, backend).filterNot { it.name == "run_shell" }.map { NamedTool(it, prefix) }) addAll(FileOperationTool.all(backend, prefix)) + addAll(PhoneTools.all(backend, context.applicationInfo.sourceDir).map { NamedTool(it, prefix) }) + addAll(DiagnosticTools.all(backend).map { NamedTool(it, prefix) }) } } } diff --git a/app/src/main/kotlin/com/powercess/mbrain/shell/DiagnosticTools.kt b/app/src/main/kotlin/com/powercess/mbrain/shell/DiagnosticTools.kt new file mode 100644 index 0000000..616c7e2 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/shell/DiagnosticTools.kt @@ -0,0 +1,125 @@ +package com.powercess.mbrain.shell + +import io.droidmcp.core.* +import io.droidmcp.shell.ShellBackend +import kotlinx.coroutines.CancellationException + +/** Bounded diagnostic commands; caller values are argv, never shell fragments. */ +object DiagnosticTools { + fun all(shell: ShellBackend): List = listOf( + command("logs_query", "Read a bounded logcat snapshot (not a stream). Filters combine; time is MM-DD HH:MM:SS.mmm. Buffer/UID support varies by Android version.", listOf( + integer("lines", "Maximum lines 1..300; default 100"), integer("pid", "Process ID"), integer("uid", "Android UID"), + string("tag", "Exact log tag; default all"), string("level", "V/D/I/W/E/F; default I"), + string("since", "MM-DD HH:MM:SS.mmm; optional"), string("buffer", "main/system/crash/events/all; default main"), + )) { p -> + val args = mutableListOf("-d", "-v", "threadtime", + "-b", p.choice("buffer", "main", setOf("main", "system", "crash", "events", "all"))) + if (p.containsKey("pid")) args += "--pid=${p.int("pid", 0, 1, Int.MAX_VALUE)}" + if (p.containsKey("uid")) args += "--uid=${p.int("uid", 0, 0, Int.MAX_VALUE)}" + if (p.containsKey("since")) { + val since = p.text("since") + require(Regex("\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}").matches(since)) { "Invalid since format" } + args += listOf("-T", since, "-m", p.int("lines", 100, 1, 300).toString()) + } else args += listOf("-t", p.int("lines", 100, 1, 300).toString()) + val tag = if (p.containsKey("tag")) p.text("tag").also { require(Regex("[A-Za-z0-9_.-]{1,120}").matches(it)) { "Invalid tag" } } else "*" + args += "$tag:${p.choice("level", "I", setOf("V", "D", "I", "W", "E", "F"))}" + if (tag != "*") args += "*:S" + run(shell, "logcat", args, p.int("lines", 100, 1, 300)) + }, + command("appops_get", "Read AppOps modes for an application and optional operation.", packageParams + string("op", "Optional operation name")) { p -> + run(shell, "cmd", listOf("appops", "get", "--user", p.user(), p.pkg()) + p.optionalOp()) + }, + command("appops_set", "Set one AppOp mode, then return the observed mode. default resets this operation to platform policy.", packageParams + listOf( + string("op", "Operation, e.g. CAMERA or android:camera", true), string("mode", "allow/ignore/deny/default/foreground", true)), false) { p -> + val op = p.op() + val result = run(shell, "cmd", listOf("appops", "set", "--user", p.user(), p.pkg(), op, + p.choice("mode", null, setOf("allow", "ignore", "deny", "default", "foreground")))) + if (!result.isSuccess) result else { + val observed = run(shell, "cmd", listOf("appops", "get", "--user", p.user(), p.pkg(), op)) + if (observed.isSuccess) ToolResult.success(mapOf("applied" to true, "observed" to observed.data)) + else ToolResult.error("appops_verification_failed", "Set completed; readback failed: ${observed.errorMessage}") + } + }, + command("proc_list", "List processes with PID, UID, RSS and command. RSS is KiB. Optional package matches main and colon-suffixed processes.", + listOf(string("package", "Optional exact package"), integer("limit", "1..300, default 100"))) { p -> + val response = shell.exec("ps", listOf("-A", "-o", "PID,UID,RSS,NAME")) + if (!response.isSuccess) failure(response.exitCode, response.stderr) else { + val packageName = if (p.containsKey("package")) p.pkg() else null + val lines = response.stdout.lineSequence().drop(1).filter { it.isNotBlank() }.toList() + val processes = lines.mapNotNull { line -> + val parts = line.trim().split(Regex("\\s+"), limit = 4) + if (parts.size != 4 || parts[0].toLongOrNull() == null) null else mapOf( + "pid" to parts[0].toLong(), "uid" to parts[1], "rss_kib" to parts[2].toLongOrNull(), "name" to parts[3]) + }.filter { row -> packageName == null || row["name"] == packageName || row["name"].toString().startsWith("$packageName:") } + val limit = p.int("limit", 100, 1, 300) + ToolResult.success(mapOf("processes" to processes.take(limit), "total" to processes.size, "truncated" to (processes.size > limit))) + } + }, + command("app_resource_usage", "Read application memory and system CPU snapshot. CPU uses dumpsys' reported sampling interval, not an instantaneous percent.", + listOf(string("package", "Application package", true))) { p -> + val pkg = p.pkg() + val memory = run(shell, "dumpsys", listOf("meminfo", pkg)) + if (!memory.isSuccess) memory else { + val cpu = shell.exec("dumpsys", listOf("cpuinfo")) + if (!cpu.isSuccess) failure(cpu.exitCode, cpu.stderr) else { + val cpuLines = cpu.stdout.lineSequence().filter { it.contains(pkg) || it.startsWith("CPU usage") || it.contains("TOTAL:") }.toList() + ToolResult.success(mapOf("package" to pkg, "memory" to memory.data, "cpu" to cpuLines)) + } + } + }, + command("net_status", "Read IP addresses, IPv4/IPv6 routes, Wi-Fi status and global HTTP proxy. Each section reports its own exit code.", emptyList()) { + val sections = linkedMapOf() + listOf(Triple("addresses", "ip", listOf("addr", "show")), + Triple("routes_ipv4", "ip", listOf("route", "show")), Triple("routes_ipv6", "ip", listOf("-6", "route", "show")), + Triple("wifi", "cmd", listOf("wifi", "status")), Triple("http_proxy", "settings", listOf("get", "global", "http_proxy"))) + .forEach { (name, executable, args) -> + val result = shell.exec(executable, args) + sections[name] = mapOf("exit_code" to result.exitCode, "output" to result.stdout.take(12000), "stderr" to result.stderr.take(2000)) + } + ToolResult.success(sections) + }, + ) + + private val packageParams = listOf(string("package", "Application package", true), integer("user", "Android user ID; defaults to current user")) + private fun string(name: String, description: String, required: Boolean = false) = ToolParameter(name, description, ParameterType.STRING, required) + private fun integer(name: String, description: String) = ToolParameter(name, description, ParameterType.INTEGER) + private fun command(name: String, description: String, parameters: List, readOnly: Boolean = true, + openWorld: Boolean = false, execute: suspend (Map) -> ToolResult): McpTool = object : McpTool { + override val name = name + override val description = description + override val parameters = parameters + override val annotations = ToolAnnotations(readOnlyHint = readOnly, destructiveHint = !readOnly, openWorldHint = openWorld) + override suspend fun execute(params: Map): ToolResult = try { + require((params.keys - parameters.map { it.name }.toSet()).isEmpty()) { "Unknown argument" } + execute.invoke(params) + } catch (cancel: CancellationException) { throw cancel } + catch (error: Exception) { ToolResult.error("diagnostic_failed", error.message) } + } + private suspend fun run(shell: ShellBackend, executable: String, args: List, maxLines: Int = 400): ToolResult { + val result = shell.exec(executable, args) + if (!result.isSuccess) return failure(result.exitCode, result.stderr.ifBlank { result.stdout }) + // Some Android cmd handlers report errors on stderr while exiting zero. + if (result.stderr.lineSequence().any { it.startsWith("Error:") || it.startsWith("Exception") }) return ToolResult.error(result.stderr.take(2000)) + val lines = result.stdout.lines() + val text = lines.takeLast(maxLines).joinToString("\n") + return ToolResult.success(mapOf("output" to text.take(48000), "truncated" to (lines.size > maxLines || text.length > 48000), + "exit_code" to result.exitCode, "stderr" to result.stderr.take(2000))) + } + private fun failure(code: Int, error: String) = ToolResult.error("command_failed", "exit=$code: ${error.take(2000)}") + private fun Map.text(key: String): String = (this[key] as? String)?.also { + require(it.isNotBlank() && '\u0000' !in it) { "$key must not be blank or contain NUL" } + } ?: error("$key is required") + private fun Map.pkg() = text("package").also { require(Regex("[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)+").matches(it)) { "Invalid package" } } + private fun Map.op() = text("op").also { require(Regex("[A-Za-z][A-Za-z0-9_:]{0,100}").matches(it)) { "Invalid operation" } } + private fun Map.optionalOp() = if (containsKey("op")) listOf(op()) else emptyList() + private fun Map.user() = if (containsKey("user")) int("user", 0, 0, 100000).toString() else "current" + private fun Map.choice(key: String, default: String?, choices: Set): String = + (if (containsKey(key)) text(key) else default ?: error("$key is required")).also { require(it in choices) { "Invalid $key" } } + private fun Map.int(key: String, default: Int, min: Int, max: Int): Int { + if (!containsKey(key)) return default + val value = this[key] as? Number ?: error("$key must be an integer") + val number = value.toDouble() + require(number.isFinite() && number == value.toLong().toDouble() && number >= min && number <= max) { "$key must be $min..$max" } + return value.toInt() + } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt index a2fe863..4b6af0d 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt @@ -19,6 +19,12 @@ private val toolLabels = mapOf( "list_installed_apps" to "应用列表", "get_app_info" to "应用详情", "launch_app" to "启动应用", "exec" to "执行命令", "file_list" to "浏览目录", "file_read" to "读取文件", "file_write" to "写入文件", "file_mkdir" to "创建目录", "file_copy" to "复制文件", "file_move" to "移动文件", "file_delete" to "删除文件", + "ui_dump" to "读取控件树", "ui_click" to "点击控件", "ui_long_click" to "长按控件", + "ui_set_text" to "输入文本", "ui_swipe" to "滑动屏幕", "ui_navigate" to "系统导航", "ui_wait" to "等待控件", + "clipboard_get" to "读取剪贴板", "clipboard_set" to "写入剪贴板", + "logs_query" to "查询日志", "appops_get" to "查询 AppOps", "appops_set" to "修改 AppOps", + "proc_list" to "进程列表", "app_resource_usage" to "应用资源占用", + "net_status" to "网络状态", "net_diagnose" to "网络诊断", ) internal fun toolTitle(name: String): String = toolLabels[name.removePrefix("root_").removePrefix("shizuku_")] ?: name diff --git a/app/src/test/kotlin/com/powercess/mbrain/control/PhoneToolsTest.kt b/app/src/test/kotlin/com/powercess/mbrain/control/PhoneToolsTest.kt new file mode 100644 index 0000000..e19df84 --- /dev/null +++ b/app/src/test/kotlin/com/powercess/mbrain/control/PhoneToolsTest.kt @@ -0,0 +1,56 @@ +package com.powercess.mbrain.control + +import io.droidmcp.shell.ShellBackend +import io.droidmcp.shell.ShellResult +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Test + +class PhoneToolsTest { + private class Shell : ShellBackend { + override val name = "fake" + override fun isAvailable() = true + val calls = mutableListOf>>() + override suspend fun exec(command: String, args: List): ShellResult { + calls += command to args + return ShellResult.ofText(0, "MBRAIN_RESULT:{\"ok\":true,\"data\":{\"performed\":true}}", "") + } + } + @Test fun `unicode and shell syntax are delivered as literal JSON argv`() = runTest { + val shell = Shell() + val tool = PhoneTools.all(shell, "/data/app/a b/base.apk").first { it.name == "ui_set_text" } + val text = "中文😀\n'\"; $(touch /sdcard/injected)" + assertTrue(tool.execute(mapOf("resource_id" to "app:id/input", "value" to text)).isSuccess) + val (command, args) = shell.calls.single() + assertEquals("/system/bin/env", command) + assertEquals("CLASSPATH=/data/app/a b/base.apk", args.first()) + assertEquals(text, Json.parseToJsonElement(args.last()).jsonObject["value"]!!.jsonPrimitive.content) + assertFalse(args.contains("-c")) + } + @Test fun `bad required types fractional numbers and unknown args never reach backend`() = runTest { + val shell = Shell() + val tools = PhoneTools.all(shell, "/base.apk").associateBy { it.name } + assertFalse(tools.getValue("ui_set_text").execute(mapOf("text" to "field")).isSuccess) + assertFalse(tools.getValue("clipboard_set").execute(mapOf("value" to 12)).isSuccess) + assertFalse(tools.getValue("ui_click").execute(mapOf("x" to 1.5, "y" to 2)).isSuccess) + assertFalse(tools.getValue("ui_navigate").execute(mapOf("action" to "back", "acton" to "home")).isSuccess) + assertFalse(tools.getValue("clipboard_set").execute(mapOf("value" to "x\u0000y")).isSuccess) + assertTrue(shell.calls.isEmpty()) + } + @Test fun `helper failures and malformed output never become successful calls`() { + assertFalse(decodePhoneReply("VM startup failed").isSuccess) + assertFalse(decodePhoneReply("MBRAIN_RESULT:garbage").isSuccess) + val result = decodePhoneReply("log line\nMBRAIN_RESULT:{\"ok\":false,\"error\":\"wait_timeout\"}") + assertFalse(result.isSuccess) + assertTrue(result.errorMessage!!.contains("wait_timeout")) + } + @Test fun `nested node results and explicit null survive decoding`() { + val result = decodePhoneReply("MBRAIN_RESULT:{\"ok\":true,\"data\":{\"nodes\":[{\"text\":\"中文\",\"bounds\":[1,2,3,4]}],\"next_offset\":null,\"truncated\":false}}") + assertTrue(result.isSuccess) + val data = result.data!! + assertNull(data["next_offset"]) + assertEquals(false, data["truncated"]) + assertEquals("中文", ((data["nodes"] as List<*>).single() as Map<*, *>)["text"]) + } +} diff --git a/app/src/test/kotlin/com/powercess/mbrain/shell/DiagnosticToolsTest.kt b/app/src/test/kotlin/com/powercess/mbrain/shell/DiagnosticToolsTest.kt new file mode 100644 index 0000000..70b978d --- /dev/null +++ b/app/src/test/kotlin/com/powercess/mbrain/shell/DiagnosticToolsTest.kt @@ -0,0 +1,67 @@ +package com.powercess.mbrain.shell + +import io.droidmcp.shell.ShellBackend +import io.droidmcp.shell.ShellResult +import kotlinx.coroutines.test.runTest +import org.junit.Assert.* +import org.junit.Test + +class DiagnosticToolsTest { + private class Shell : ShellBackend { + override val name = "fake" + override fun isAvailable() = true + val calls = mutableListOf>>() + var reply = ShellResult.ofText(0, "ok", "") + override suspend fun exec(command: String, args: List): ShellResult { + calls += command to args + return reply + } + fun tool(name: String) = DiagnosticTools.all(this).first { it.name == name } + } + @Test fun `log queries are finite and combine validated filters`() = runTest { + val shell = Shell() + val result = shell.tool("logs_query").execute(mapOf("pid" to 42L, "uid" to 10000L, "tag" to "App", "lines" to 12, "level" to "E")) + assertTrue(result.isSuccess) + val args = shell.calls.single().second + assertTrue(args.containsAll(listOf("-d", "-t", "12", "--pid=42", "--uid=10000", "App:E", "*:S"))) + } + @Test fun `invalid command arguments cannot reach shell`() = runTest { + val shell = Shell() + assertFalse(shell.tool("logs_query").execute(mapOf("tag" to "x; id")).isSuccess) + assertFalse(shell.tool("logs_query").execute(mapOf("lines" to 0)).isSuccess) + assertFalse(shell.tool("logs_query").execute(mapOf("pid" to 1.5)).isSuccess) + assertFalse(shell.tool("appops_set").execute(mapOf("package" to "a.b;id", "op" to "CAMERA", "mode" to "allow")).isSuccess) + assertFalse(shell.tool("appops_set").execute(mapOf("package" to "a.b", "op" to "CAMERA", "mode" to "typo")).isSuccess) + assertTrue(shell.calls.isEmpty()) + } + @Test fun `timestamp queries retain a maximum record count`() = runTest { + val shell = Shell() + assertTrue(shell.tool("logs_query").execute(mapOf("since" to "09-24 12:30:00.000", "lines" to 7)).isSuccess) + val args = shell.calls.single().second + assertTrue(args.containsAll(listOf("-d", "-T", "09-24 12:30:00.000", "-m", "7"))) + assertFalse(args.contains("-t")) + } + @Test fun `AppOps writes specify user and read back same operation`() = runTest { + val shell = Shell() + assertTrue(shell.tool("appops_set").execute(mapOf("package" to "a.b", "op" to "CAMERA", "mode" to "default", "user" to 10)).isSuccess) + assertEquals(listOf("appops", "set", "--user", "10", "a.b", "CAMERA", "default"), shell.calls[0].second) + assertEquals(listOf("appops", "get", "--user", "10", "a.b", "CAMERA"), shell.calls[1].second) + } + @Test fun `shell failures are surfaced and AppOps write does not continue`() = runTest { + val shell = Shell() + shell.reply = ShellResult.ofText(1, "", "denied") + assertFalse(shell.tool("appops_set").execute(mapOf("package" to "a.b", "op" to "CAMERA", "mode" to "allow")).isSuccess) + assertEquals(1, shell.calls.size) + shell.reply = ShellResult.ofText(0, "", "Error: unknown operation") + assertFalse(shell.tool("appops_get").execute(mapOf("package" to "a.b")).isSuccess) + } + @Test fun `process filtering excludes similar package names and reports truncation`() = runTest { + val shell = Shell() + shell.reply = ShellResult.ofText(0, "PID UID RSS NAME\n1 10000 42 a.b\n2 10000 21 a.b:remote\n3 10001 11 a.bc\n", "") + val result = shell.tool("proc_list").execute(mapOf("package" to "a.b", "limit" to 1)) + val data = result.data!! + assertEquals(2, data["total"]) + assertEquals(true, data["truncated"]) + assertEquals(42L, ((data["processes"] as List<*>).single() as Map<*, *>)["rss_kib"]) + } +} diff --git a/docs/capability-packs.md b/docs/capability-packs.md new file mode 100644 index 0000000..ce6cb4b --- /dev/null +++ b/docs/capability-packs.md @@ -0,0 +1,82 @@ +# 手机操作与应用诊断 + +启用 Root 或 Shizuku 后,在工具目录中选择对应来源。下表省略 `root_` / `shizuku_` 前缀,例如完整名称为 `shizuku_ui_dump`。工具不需要单独启用无障碍服务,也不依赖 AutoX.js。 + +## 手机操作 + +| 工具 | 参数与用途 | +| --- | --- | +| `ui_dump` | `offset`、`limit`;读取当前窗口,默认每页 50 个节点,最多 60 个;总遍历上限 600 个 | +| `ui_click` | 按选择器点击节点或可点击的父节点;也可传 `x`、`y` | +| `ui_long_click` | 按选择器长按;坐标长按保持 800ms | +| `ui_set_text` | 选择输入框或它的标签,`value` 为替换内容;支持中文、emoji、换行,空字符串清空 | +| `ui_swipe` | `x1`、`y1`、`x2`、`y2`,`duration_ms` 为 50–3000,默认 350 | +| `ui_navigate` | `action`:`back`、`home`、`recents`、`notifications`、`quick_settings` | +| `ui_wait` | 选择器 + `state=present/absent`,默认等待出现,`timeout_ms` 默认 5000、最多 15000 | +| `clipboard_get` | 读取第一项文本;返回可用性、文本、项数与截断状态,不读取 URI 指向的文件 | +| `clipboard_set` | `value`:写入最多 16000 字符的文本 | + +选择器至少提供 `text`、`resource_id`、`description` 之一,多个字段同时提供表示同时满足。可用 `package` 限定目标应用。`text` 和 `description` 默认精确匹配,`contains=true` 改为包含匹配。动作遇到多个匹配时返回错误,使用 `index` 指定匹配结果中的第几个(从 0 开始);它不是 `ui_dump` 的节点索引。坐标与选择器不能混用。 + +`ui_dump` 的索引和父索引用于描述当次快照,翻页期间页面应保持稳定;不缓存节点供后续动作复用。单个文字/描述最多返回 200 字符,密码文字不返回。文本写入最多 16000 字符。动作返回 `performed=true` 表示系统接受了动作,业务是否完成应继续用 `ui_wait`、`ui_dump` 或截图验证。 + +例如: + +```json +{"name":"shizuku_ui_set_text","arguments":{"text":"服务名称","package":"com.powercess.mbrain","value":"中文输入 😀"}} +``` + +```json +{"name":"shizuku_ui_wait","arguments":{"text":"保存成功","timeout_ms":5000}} +``` + +## 应用诊断 + +| 工具 | 参数与用途 | +| --- | --- | +| `logs_query` | `lines`(1–300,默认 100)、`pid`、`uid`、`tag`、`level`(默认 I)、`buffer`(默认 main)、`since` | +| `appops_get` | `package`、可选 `op` 和 `user` | +| `appops_set` | `package`、`op`、`mode`(allow/ignore/deny/default/foreground)、可选 `user`;设置后读回 | +| `proc_list` | 可选 `package` 和 `limit`;返回 PID、UID、RSS KiB、进程名,包括包名的冒号子进程 | +| `app_resource_usage` | `package`;返回内存报告,以及系统 CPU 报告中的采样区间、目标应用和总量 | +| `net_status` | 返回 IP、IPv4/IPv6 路由、Wi-Fi 与全局 HTTP 代理,各项带退出码 | +| `net_diagnose` | `host`、`port`(默认 443);DNS 最多等待 4 秒,最多尝试 3 个地址、每次 TCP 最多 2 秒 | + +日志未传 `since` 时取最近若干条;传入 `MM-DD HH:MM:SS.mmm` 后,从该时间开始最多取 `lines` 条。日志是快照,不持续监听。输出超出执行器预算会明确报错,应缩小查询范围。普通诊断文本返回截断标记。 + +AppOps 默认针对当前 Android 用户;`default` 恢复该项的平台默认策略。网络诊断只进行域名解析与 TCP 握手,不发送 HTTP 请求;DNS/TCP 失败作为诊断结果返回,不能仅凭 MCP 调用成功判断网络畅通。连通性反映所选执行身份,并不等同于目标应用的网络权限或 VPN 路由。 + +## 执行方式 + +固定 Java 辅助入口打包在 APK 中,经现有高权限执行器启动 `app_process`,只接受上述固定操作和 JSON 参数,不接受任意代码。UI 操作在两个后端之间串行执行;连接时保留已有无障碍服务,完成后断开。沿用现有命令超时、输出上限与能力关闭行为。 + +## 验证 + +应用单元测试覆盖参数边界、字面量 Unicode 参数传递、辅助进程错误、结果解码、日志过滤、AppOps 读回及进程匹配。 + +构建 Debug APK 和 AndroidTest APK,安装独立测试包后运行: + +```powershell +./gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest :app:lintDebug +./scripts/smoke-capabilities.ps1 -Package com.powercess.mbrain.dev +``` + +脚本仅允许测试包名,会重新启动该测试应用,操作未保存的服务表单,不清除数据。诊断测试只返回通过/失败;剪贴板原始对象在设备内存中保存、恢复,不传回主机。测试前让设备保持解锁。使用固定开发包名和同一本地签名覆盖安装,不卸载已有应用。 + +真实 Shizuku → MCP 链路另由 `CapabilityGatewayTest` 验证。在测试应用中启用并授权 Shizuku,安装对应 AndroidTest APK,然后执行: + +```powershell +adb shell am instrument -w -e class com.powercess.mbrain.control.CapabilityGatewayTest -e capabilityGateway true com.powercess.mbrain.dev.test/androidx.test.runner.AndroidJUnitRunner +``` + +常规开发测试统一使用固定的开发包名。测试在设备内获取自己的网关凭据、初始化 MCP、检查全部 16 项工具并执行读操作及测试应用内的点击;Token 不离开设备。结束后停止测试网关。 + +### 2026-09-24 验证记录 + +- Debug 与 AndroidTest APK 构建通过;应用模块 41 项 JVM 测试通过,lint 为 0 错误、33 警告。已有 HTTP 本机测试曾出现一次 socket 超时,复跑通过。构建复用了未修改的四 ABI frpc 产物。 +- Android 15 / API 35 已连接设备:`smoke-capabilities.ps1` 通过,覆盖控件树、选择器点击、中文与 emoji 输入、长按、滑动、返回/桌面/最近任务、出现/消失等待与超时、设备内剪贴板保存/恢复,以及全部诊断工具。 +- `CapabilityGatewayTest` 通过:真实 Shizuku → 托管执行器 → 辅助进程 / 系统命令 → MCP 返回链路可用,16 项新增工具均出现在网关目录。 +- 中文工具名和搜索界面验证通过。测试使用独立 `controlqa` 包,保留原有应用数据;结束时测试网关已停止。 +- 尚未覆盖其他 Android 版本、其他 ROM、直接 Root 后端与多显示器;当前 UI 操作仅支持默认显示器。 + +固定开发包名后的提交前复验:`com.powercess.mbrain.dev` / “MBrain 开发版”安装成功,手机操作与诊断脚本、设备内 Shizuku/MCP 测试再次通过。Debug、AndroidTest、Release 构建、各模块 JVM 测试、Debug/Release lint 及四 ABI 打包检查通过;常规开发不再使用临时包名覆盖脚本。 diff --git a/docs/development.md b/docs/development.md index 75424a4..3f8607e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -51,7 +51,9 @@ GitHub Actions 在 push、PR 和手动触发时使用 Ubuntu 24.04、JDK 17、An 通用 APK 覆盖 `arm64-v8a`、`armeabi-v7a`、`x86_64` 和 `x86`,最低 Android 9.0。CI 检查 APK 中每个原生库是否同时包含四种 ABI;当前原生库来自 AndroidX 依赖。无需按 CPU 下载不同文件。该检查验证打包完整性,不代表四种架构都已进行运行测试。设备上的外部 MCP 程序需要另行匹配设备架构。 -自动构建使用临时 Debug 签名和 `com.powercess.mbrain.debug` 包名,仅用于测试,可与正式版并存。不同运行的 Debug 签名可能不同,不能保证覆盖安装同名测试包。正式版固定使用 `com.powercess.mbrain` 和正式签名。早期临时版本曾使用正式包名与 Debug 签名,无法直接覆盖为正式版;卸载会清除配置,操作前需保存需要保留的连接设置。 +本地开发与普通 Debug 构建固定使用 `com.powercess.mbrain.dev`,桌面显示“MBrain 开发版”,版本号显示为 `版本号-dev`。包名不随版本号或开发任务改变,不再通过临时 init 脚本改成 `controlqa` 等名称。后续本地构建使用同一份 Debug keystore,并以 `adb install -r` 覆盖更新,保留配置。 + +CI 使用临时 Debug 签名,签名可能与本地不同,不能保证覆盖安装同名开发包。正式版固定使用 `com.powercess.mbrain` 和正式签名。已有旧测试包不会自动迁移或卸载;签名冲突时应先确认安装来源,不通过不断更换包名解决。卸载会清除配置。 验证首次克隆时,在新目录克隆后设置标准 `JAVA_HOME`、`ANDROID_HOME` 和全新的 `GRADLE_USER_HOME`,运行 `./gradlew :app:assembleDebug testDebugUnitTest :app:lintDebug --no-build-cache --max-workers=1 --no-parallel --no-watch-fs`。Windows 使用 `gradlew.bat`。不复制旧目录的 `local.properties`、`.local-tools`、`.gradle` 或 `build`。 @@ -70,6 +72,8 @@ KernelSU 等管理器可能对未授权应用隐藏 `su`,需在管理器中单 ## 当前工具 +0.3.0 新增手机操作包与应用诊断包,完整参数和设备测试见[能力包说明](capability-packs.md)。两组工具随 Root / Shizuku 来源启用,不需要额外安装自动化引擎。 + | 来源 | 工具 | |---|---| | 设备(始终启用) | `get_device_info`、`get_battery_info`、`get_connectivity`、`get_storage_info` | diff --git a/docs/releases/0.3.0.md b/docs/releases/0.3.0.md new file mode 100644 index 0000000..fa198c8 --- /dev/null +++ b/docs/releases/0.3.0.md @@ -0,0 +1,27 @@ +# MBrain 0.3.0 + +本版本增加手机操作包和应用诊断包。启用 Root 或 Shizuku 后,工具会随对应来源出现在工具目录中;无需配置外部自动化应用。 + +## 手机操作包 + +- 控件树:读取当前窗口的文字、描述、资源 ID、坐标、父子关系和可操作状态,支持分页。 +- 点击与长按:按文字、资源 ID、描述定位,也支持坐标操作;多个匹配需明确选择。 +- 中文输入:替换输入框内容,支持中文、emoji 和多行文本,可通过输入框标签定位。 +- 滑动与导航:滑动、返回、桌面、最近任务、通知栏和快捷设置。 +- 等待:等待控件出现或消失,超时明确返回错误。 +- 剪贴板:读取和写入文本。 + +## 应用诊断包 + +- 日志:按进程、UID、标签、级别、缓冲区和起始时间查询。 +- AppOps:读取、修改单项操作模式,并返回修改后的查询结果。 +- 进程与资源:进程列表、RSS、应用内存报告和 CPU 采样报告。 +- 网络:IP、路由、Wi-Fi、代理状态,以及 DNS 解析和 TCP 连通性诊断。 + +## 使用范围 + +新增 16 个工具,每个已启用的高权限来源分别注册 `root_` 或 `shizuku_` 前缀。工具目录提供对应中文名称。现有工具和配置保持兼容。 + +开发版固定使用 `com.powercess.mbrain.dev`,桌面名称为“MBrain 开发版”;包名不随版本变化,后续使用相同本地签名覆盖更新。正式版仍使用 `com.powercess.mbrain`。 + +手机操作针对当前活动窗口和默认显示器,设备需要处于可交互状态。自绘控件、受保护页面可能不提供完整控件树。剪贴板、系统命令及隐藏接口受 Android 版本和厂商系统影响,不可用时返回明确错误,不自动切换执行身份。 diff --git a/scripts/smoke-capabilities.ps1 b/scripts/smoke-capabilities.ps1 new file mode 100644 index 0000000..e156b83 --- /dev/null +++ b/scripts/smoke-capabilities.ps1 @@ -0,0 +1,73 @@ +param( + [string]$Package = 'com.powercess.mbrain.dev', + [string]$Serial = '', + [string]$TestApk = "$PSScriptRoot/../app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk" +) +$ErrorActionPreference = 'Stop' +if ($Package -ne 'com.powercess.mbrain.dev') { + throw 'Only the fixed development package com.powercess.mbrain.dev may be tested.' +} +$deviceArgs = if ($Serial) { @('-s', $Serial) } else { @() } +function Invoke-Adb([string[]]$Arguments) { + $output = & adb @deviceArgs @Arguments + if ($LASTEXITCODE -ne 0) { throw "ADB failed ($LASTEXITCODE): $($Arguments[0])" } + return $output +} +function Quote-Shell([string]$Value) { "'" + $Value.Replace("'", "'" + [char]34 + "'" + [char]34 + "'") + "'" } +$apkPath = ([string](Invoke-Adb @('shell', 'pm', 'path', $Package))).Replace('package:', '').Trim() +if (!$apkPath.StartsWith('/data/app/')) { throw 'Install the test app first.' } +$helper = "CLASSPATH=$(Quote-Shell $apkPath) timeout 30 app_process /system/bin com.powercess.mbrain.control.PhoneControlMain" +function Invoke-Phone([string]$Operation, [hashtable]$Arguments = @{}) { + # Restrict selectors to the test app; global navigation and coordinates are explicit below. + if ($Arguments.ContainsKey('text')) { $Arguments['package'] = $Package } + $json = ConvertTo-Json -InputObject $Arguments -Compress -EscapeHandling EscapeNonAscii + $output = Invoke-Adb @('shell', "$helper $Operation $(Quote-Shell $json)") + $line = $output | Where-Object { $_.StartsWith('MBRAIN_RESULT:') } | Select-Object -Last 1 + if (!$line) { throw 'No helper response' } + $reply = $line.Substring(14) | ConvertFrom-Json + if (!$reply.ok) { throw "$Operation failed: $($reply.error)" } + return $reply.data +} +Invoke-Adb @('push', (Resolve-Path $TestApk).Path, '/data/local/tmp/mbrain-control-tests.apk') | Out-Null +try { + Invoke-Adb @('shell', 'am', 'force-stop', $Package) | Out-Null + Invoke-Adb @('shell', 'am', 'start', '-W', '-n', "$Package/com.powercess.mbrain.MainActivity") | Out-Null + $classpath = Quote-Shell "${apkPath}:/data/local/tmp/mbrain-control-tests.apk" + $result = Invoke-Adb @('shell', "CLASSPATH=$classpath timeout 60 app_process /system/bin com.powercess.mbrain.control.CapabilitySmokeMain $(Quote-Shell $apkPath) $Package") + if ($result -notcontains 'CAPABILITY_SMOKE_OK') { throw 'Device diagnostics failed' } + $result + $tree = Invoke-Phone ui_dump + if ($tree.count -le 0) { throw 'Empty UI tree' } + 'PASS ui_dump' + Invoke-Phone ui_click @{text='MCP'} | Out-Null + Invoke-Phone ui_wait @{text='添加服务'; timeout_ms=5000} | Out-Null + Invoke-Phone ui_click @{text='添加服务'} | Out-Null + Invoke-Phone ui_wait @{text='HTTP 服务'; timeout_ms=5000} | Out-Null + Invoke-Phone ui_click @{text='HTTP 服务'} | Out-Null + Invoke-Phone ui_set_text @{text='服务名称';value='MBrain 中文😀输入验证'} | Out-Null + Invoke-Phone ui_wait @{text='MBrain 中文😀输入验证'; timeout_ms=5000} | Out-Null + 'PASS Chinese + emoji input and present wait' + Invoke-Phone ui_long_click @{text='MBrain 中文😀输入验证'} | Out-Null + 'PASS node long click' + Invoke-Phone ui_navigate @{action='back'} | Out-Null + # Derive swipe coordinates from the current root, so the script works at different resolutions. + $bounds = (Invoke-Phone ui_dump).nodes[0].bounds + $x = [int](($bounds[0] + $bounds[2]) / 2) + $y1 = [int]($bounds[1] + ($bounds[3] - $bounds[1]) * 0.65) + $y2 = [int]($bounds[1] + ($bounds[3] - $bounds[1]) * 0.4) + Invoke-Phone ui_swipe @{x1=$x;y1=$y1;x2=$x;y2=$y2;duration_ms=250} | Out-Null + 'PASS swipe' + Invoke-Phone ui_wait @{text='MBrain nonexistent control';state='absent';timeout_ms=0} | Out-Null + try { Invoke-Phone ui_wait @{text='MBrain nonexistent control';timeout_ms=100} | Out-Null; throw 'Expected timeout' } + catch { if (!$_.ToString().Contains('wait_timeout')) { throw } } + 'PASS absent wait and timeout error' + Invoke-Phone ui_navigate @{action='home'} | Out-Null + Invoke-Phone ui_navigate @{action='recents'} | Out-Null + Invoke-Phone ui_navigate @{action='back'} | Out-Null + 'PASS home, recents and back' +} finally { + Invoke-Adb @('shell', 'rm', '-f', '/data/local/tmp/mbrain-control-tests.apk') | Out-Null + # Discard the unsaved test form, leaving installed app data intact. + Invoke-Adb @('shell', 'am', 'force-stop', $Package) | Out-Null + Invoke-Adb @('shell', 'am', 'start', '-W', '-n', "$Package/com.powercess.mbrain.MainActivity") | Out-Null +} diff --git a/scripts/smoke-frpc.py b/scripts/smoke-frpc.py index cd1fd91..654df27 100644 --- a/scripts/smoke-frpc.py +++ b/scripts/smoke-frpc.py @@ -22,7 +22,7 @@ def free_port(): def run(args): root = Path(__file__).resolve().parents[1] - if args.package in {"com.powercess.mbrain", "com.powercess.mbrain.debug"}: + if args.package in {"com.powercess.mbrain", "com.powercess.mbrain.debug", "com.powercess.mbrain.dev"}: raise ValueError("Use an isolated QA package to protect existing application data") adb = [args.adb, "-s", args.serial] source = root / "build/frpc-source/frp-0.71.0"