From 1882520cac2f8c6d862959334ed4b1f7a12def0e Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:46:48 -0500 Subject: [PATCH] fix(agent): the agent survives Steam session starts, stops and restarts (#2503) * fix(agent): session starts and stops leave the agent's own processes running * feat(agent): droiddeckctl ships with the app and the brief explains the Steam session --- app/build.gradle | 2 + app/src/main/assets/agent/droiddeckctl | 2 + .../com/droiddeck/launcher/agent/AgentHost.kt | 23 ++++++++-- .../droiddeck/launcher/agent/AgentSetup.kt | 42 ++++++++++++------- .../launcher/session/OrphanReaper.kt | 5 ++- .../launcher/session/SessionService.kt | 6 ++- 6 files changed, 58 insertions(+), 22 deletions(-) create mode 100755 app/src/main/assets/agent/droiddeckctl diff --git a/app/build.gradle b/app/build.gradle index 28bf184e32..35201d85c5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -277,6 +277,8 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) { dependsOn(stageSessionScripts) from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' } from(rootProject.file('tools/linuxfs/innoextract')) + from(rootProject.file('tools')) { include 'droiddeckctl', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') } + from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') } from(layout.buildDirectory.dir('prepared-assets')) into(runtimeAssetsDir) } diff --git a/app/src/main/assets/agent/droiddeckctl b/app/src/main/assets/agent/droiddeckctl new file mode 100755 index 0000000000..a72cb2587c --- /dev/null +++ b/app/src/main/assets/agent/droiddeckctl @@ -0,0 +1,2 @@ +#!/bin/sh +exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@" diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index b1e939b088..d82ea8f127 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -14,6 +14,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.OrphanReaper import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.nio.file.Files @@ -50,7 +51,12 @@ object AgentHost { @VisibleForTesting internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " + "and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " + - "droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " + + "droiddeckctl inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " + + "Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " + + "Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " + + "Starting, stopping or restarting a session leaves you running. " + + "Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " + + "End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " + "dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " + "process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " + "Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " + @@ -252,6 +258,7 @@ object AgentHost { val workdir = workspace(app) Thread({ runCatching { current.prepare(LinuxRuntime.rootDir(app)) } + runCatching { AgentSetup.installHelpers(app) } val child = try { guest(app, command, workdir).start() } catch (e: Exception) { @@ -260,6 +267,7 @@ object AgentHost { return@Thread } val started = Turn(child, AgentProcesses.pidOf(child)) + OrphanReaper.keep(started.pid) main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) } child.outputStream.close() var ended = false @@ -278,6 +286,7 @@ object AgentHost { } runCatching { raw?.close() } val status = runCatching { child.waitFor() }.getOrDefault(-1) + OrphanReaper.release(started.pid) main.post { if (turn === started) { turn = null @@ -500,9 +509,15 @@ object AgentHost { val child = guest(app, listOf("sh", "-c", "mkdir -p /root/.cache; DD_LAB_DETACHED=1 exec dd-lab-build \"\$@\" > /root/.cache/dd-lab-build.log 2>&1", "dd-lab-build") + args, cwd).start() main.post { labProcess = child } - child.outputStream.close() - child.inputStream.readBytes() - child.waitFor() + val pid = AgentProcesses.pidOf(child) + OrphanReaper.keep(pid) + try { + child.outputStream.close() + child.inputStream.readBytes() + child.waitFor() + } finally { + OrphanReaper.release(pid) + } }.onFailure { Log.w(TAG, "could not run a Lab build", it) } main.post { labProcess = null diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index bc4ac2c9e9..f5c080a060 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -8,6 +8,7 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.OrphanReaper import java.io.File import java.util.concurrent.TimeUnit @@ -39,7 +40,8 @@ object AgentSetup { private val main = Handler(Looper.getMainLooper()) private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git" private const val CHECKOUT = "/root/DroidDeck" - private val HELPERS = listOf("android-open", "dd-gh-login") + private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl") + internal const val CTL = "/root/.local/share/droiddeck/ctl" private const val PROBE_TIMEOUT_S = 60L fun check(context: Context) { @@ -96,14 +98,20 @@ object AgentSetup { installHelpers(app) runCatching { harness.prepare(LinuxRuntime.rootDir(app)) } val child = AgentHost.guest(app, command).start() - child.outputStream.close() - logFile(app, step).apply { parentFile?.mkdirs() }.bufferedWriter().use { log -> - child.inputStream.bufferedReader().forEachLine { line -> - log.appendLine(line) - val text = line.trim() - if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) } + val pid = AgentProcesses.pidOf(child) + OrphanReaper.keep(pid) + try { + child.outputStream.close() + logFile(app, step).apply { parentFile?.mkdirs() }.bufferedWriter().use { log -> + child.inputStream.bufferedReader().forEachLine { line -> + log.appendLine(line) + val text = line.trim() + if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) } + } + child.waitFor().also { log.appendLine("exit $it") } } - child.waitFor().also { log.appendLine("exit $it") } + } finally { + OrphanReaper.release(pid) } } main.post { @@ -172,12 +180,16 @@ object AgentSetup { } /** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */ - private fun installHelpers(app: Context) { - val bin = File(LinuxRuntime.rootDir(app), "root/.local/bin").apply { mkdirs() } - for (name in HELPERS) { - val target = File(bin, name) - app.assets.open("agent/$name").use { input -> target.outputStream().use { input.copyTo(it) } } - target.setExecutable(true, false) - } + internal fun installHelpers(app: Context) { + val root = LinuxRuntime.rootDir(app) + val bin = File(root, "root/.local/bin").apply { mkdirs() } + for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name)) + val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() } + for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name)) + } + + private fun copyAsset(app: Context, asset: String, target: File) { + app.assets.open(asset).use { input -> target.outputStream().use { input.copyTo(it) } } + target.setExecutable(true, false) } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt index cbcd904bc1..a6c5117665 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt @@ -11,6 +11,9 @@ object OrphanReaper { fun release(pid: Int) { kept.remove(pid) } + /** Kept processes and everything they started, which session cleanups must leave running. */ + fun spared(): Set = descendants(kept) + fun hasOtherProcesses(): Boolean = hasOtherProcesses( File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(), ) { pid -> @@ -30,7 +33,7 @@ object OrphanReaper { fun reap(reason: String, matching: (String) -> Boolean = { true }): Int { val me = android.os.Process.myPid() val uid = android.os.Process.myUid() - val spared = descendants(kept) + val spared = spared() var killed = 0 File("/proc").listFiles()?.forEach { entry -> val pid = entry.name.toIntOrNull() ?: return@forEach diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 4faa870866..2af6510093 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1606,10 +1606,11 @@ class SessionService : Service() { val me = android.os.Process.myPid() val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/" val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return + val spared = OrphanReaper.spared() var killed = 0 for (proc in procs) { val pid = proc.name.toIntOrNull() ?: continue - if (pid == me) continue + if (pid == me || pid in spared) continue val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue } if (!exe.startsWith(rootfs)) continue android.os.Process.killProcess(pid) @@ -1621,10 +1622,11 @@ class SessionService : Service() { private fun killStragglers() { val me = android.os.Process.myPid() val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return + val spared = OrphanReaper.spared() var killed = 0 for (proc in procs) { val pid = proc.name.toIntOrNull() ?: continue - if (pid == me) continue + if (pid == me || pid in spared) continue val cmdline = try { File(proc, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ') } catch (e: Exception) {