Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
11 changes: 7 additions & 4 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String>) = 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<String>): 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<String, Any> = 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)
}
}
}
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:label="MBrain" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher" android:allowBackup="false" android:supportsRtl="true"
<application android:label="${appLabel}" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher" android:allowBackup="false" android:supportsRtl="true"
android:theme="@android:style/Theme.Material.Light.NoActionBar"
android:networkSecurityConfig="@xml/network_security_config">
<provider android:name="rikka.shizuku.ShizukuProvider"
Expand Down
Loading
Loading