fix(ctl): reach the agent bridge by broadcast when the shell has no content command (#2321)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-09 00:00:20 -05:00
1 parent 29823bb1bf
commit 88d6b70881
4 files changed
+95

No files matched your search

+8
View File
@@ -352,6 +352,14 @@
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter>
</provider>
<receiver
android:name=".agent.AgentCallReceiver"
android:exported="true"
android:permission="android.permission.DUMP">
<intent-filter>
<action android:name="${applicationId}.AGENT_CALL" />
</intent-filter>
</receiver>
<provider
android:name=".agent.AgentBridgeProvider"
android:authorities="${applicationId}.agent"
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.agent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import java.io.File
/**
* The agent bridge for devices whose shell has no `content` command: the same calls as
* [AgentBridgeProvider], answered in a file under the app's external files folder.
*/
class AgentCallReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val method = intent.getStringExtra("method") ?: return
val id = intent.getStringExtra("id")?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,64}")) } ?: return
val arg = intent.getStringExtra("arg")
val request = intent.getStringExtra(AgentBridgeProvider.EXTRA_REQUEST)
val pending = goAsync()
Thread({
val json = try {
val extras = Bundle().apply { putString(AgentBridgeProvider.EXTRA_REQUEST, request) }
context.contentResolver.call("${context.packageName}.agent", method, arg, extras)
?.getString(AgentBridgeProvider.RESULT_JSON) ?: """{"ok":false,"error":{"code":"NO_RESPONSE","message":"no response"}}"""
} catch (e: Exception) {
org.json.JSONObject().put("ok", false)
.put("error", org.json.JSONObject().put("code", "COMMAND_FAILED").put("message", e.message ?: e.javaClass.simpleName)).toString()
}
try {
val dir = File(context.getExternalFilesDir(null), "agent-calls").apply { mkdirs() }
File(dir, "$id.json.part").writeText(json)
File(dir, "$id.json.part").renameTo(File(dir, "$id.json"))
} finally {
pending.finish()
}
}, "agent-call-$id").start()
}
}
+26
View File
@@ -9,6 +9,7 @@ import gzip
import json
import os
import re
import shlex
import shutil
import subprocess
import struct
@@ -98,6 +99,29 @@ def encode_request(request: dict) -> str:
return encoded
def receiver_call(adb: str, serial: str, method: str, arg: str | None, request: dict | None, timeout: float) -> dict:
"""The agent bridge through a broadcast, for shells without the `content` command."""
call_id = uuid.uuid4().hex[:16]
remote = f"/sdcard/Android/data/{PACKAGE}/files/agent-calls/{call_id}.json"
command = ["shell", "am", "broadcast", "-a", f"{PACKAGE}.AGENT_CALL", "-p", PACKAGE,
"--es", "method", method, "--es", "id", call_id]
if arg is not None:
command += ["--es", "arg", shlex.quote(arg)]
if request is not None:
command += ["--es", "request", encode_request(request)]
started = run_adb(adb, serial, *command, timeout=timeout + 30)
if started.returncode != 0:
raise ControlError((started.stdout + started.stderr).decode(errors="replace").strip() or "ADB broadcast failed", "ADB_FAILED")
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run_adb(adb, serial, "shell", f"cat {remote} 2>/dev/null && rm -f {remote}", timeout=30)
text = result.stdout.decode(errors="replace").strip()
if result.returncode == 0 and text:
return json.loads(text)
time.sleep(0.25)
raise ControlError(f"No answer to {method} within {timeout:g} s", "TIMEOUT")
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None,
timeout: float = 30) -> dict:
command = ["shell", "content", "call", "--uri", AUTHORITY, "--method", method]
@@ -108,6 +132,8 @@ def provider_call(adb: str, serial: str, method: str, arg: str | None = None, re
command.extend(["--extra", f"request:s:{encoded}"])
result = run_adb(adb, serial, *command, timeout=timeout)
output = (result.stdout + result.stderr).decode(errors="replace")
if "content: inaccessible or not found" in output:
return receiver_call(adb, serial, method, arg, request, timeout)
response = _content_result(output)
if result.returncode != 0 and response.get("ok") is not False:
raise ControlError(output.strip() or "ADB content call failed", "ADB_FAILED")
+22
View File
@@ -398,6 +398,28 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_provider_call_falls_back_to_a_broadcast_without_content(self):
calls = []
answers = iter([b"", b'{"ok": true, "command": "state"}'])
def adb(_adb, _serial, *args, timeout=30):
calls.append(args)
if args[:2] == ("shell", "content"):
return ctl.subprocess.CompletedProcess(args, 127, b"", b"/system/bin/sh: content: inaccessible or not found")
if args[:2] == ("shell", "am"):
return ctl.subprocess.CompletedProcess(args, 0, b"Broadcast completed: result=0", b"")
return ctl.subprocess.CompletedProcess(args, 0, next(answers), b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
answer = ctl.provider_call("adb", "fake-1", "state", arg="a b", request={"x": 1})
self.assertEqual({"ok": True, "command": "state"}, answer)
broadcast = calls[1]
self.assertEqual(("shell", "am", "broadcast", "-a", ctl.PACKAGE + ".AGENT_CALL", "-p", ctl.PACKAGE), broadcast[:7])
self.assertIn("'a b'", broadcast)
self.assertEqual(ctl.encode_request({"x": 1}), broadcast[broadcast.index("request") + 1])
call_id = broadcast[broadcast.index("id") + 1]
self.assertIn("agent-calls/%s.json" % call_id, calls[-1][1])
def test_pacing_turns_timestats_off_when_the_dump_fails(self):
calls = []