Add debug-only agent control bridge

This commit is contained in:
xXJsonDeruloXx authored and xXJSONDeruloXx committed 2026-09-24 21:34:50 -04:00
1 parent 643d82e2fd
commit 63b24ca4c0
13 files changed
+991 -22

No files matched your search

@@ -48,6 +48,9 @@ import com.droiddeck.launcher.session.PerfHints
import com.droiddeck.launcher.session.PerfHud
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.wayland.HdrSupport
import com.droiddeck.launcher.session.SessionService
@@ -160,6 +163,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionEvents.begin(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
}
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// Game-tier power policy for the whole session: a sustained clock floor, the panel's
// fastest mode, and the OS told it is in gameplay. Logged so a slow device says why.
@@ -301,12 +311,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
updateOnScreenControls()
WaylandCompositor.setFirstFrameListener {
SessionState.firstFrameSeen = true
SessionEvents.firstFrame()
runOnUiThread {
loading.visible = false
hud.start()
}
}
SessionEvents.markReadyIfPossible()
SessionState.endListener = endListener
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
// The single action waits out the double-press window so the two actions stay distinct.
@@ -393,14 +404,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
* starts when they are in. Nothing else changes.
*/
private fun installThenStart(runtime: Boolean, desktop: Boolean) {
if (SessionState.stopRequested) return
installingRuntime = true
SessionState.installing = if (runtime) "runtime" else "desktop"
SessionEvents.transition(
SessionPhase.INSTALLING_RUNTIME,
if (runtime) "runtime.installing" else "desktop.installing",
mapOf("component" to SessionState.installing),
)
loading.step = if (runtime) "downloading the Linux runtime" else "downloading the desktop"
loading.percent = -1
Thread({
val problem = (if (runtime) installRuntime() else null) ?: (if (desktop) installDesktop() else null)
var failedComponent: String? = null
var problem: String? = null
if (runtime) {
problem = installRuntime()
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
}
if (problem == null && desktop && !SessionState.stopRequested) {
SessionState.installing = "desktop"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
problem = installDesktop()
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
}
uiHandler.post {
installingRuntime = false
if (problem != null) { loading.showEnded(problem); return@post }
SessionState.installing = null
if (SessionState.stopRequested) {
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
collectStartArtifacts("session start cancelled")
finish()
return@post
}
if (problem != null) {
val code = if (failedComponent == "runtime") "RUNTIME_INSTALL_FAILED" else "DESKTOP_INSTALL_FAILED"
SessionEvents.fail(code, problem)
collectStartArtifacts("session start failed")
loading.showEnded(problem)
return@post
}
loading.percent = -1
loading.step = "Starting the session…"
// The surface may have come and gone while the download ran; start on the live one.
@@ -409,6 +452,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "runtime-install").start()
}
private fun collectStartArtifacts(reason: String) {
val dir = SessionPaths.take() ?: return
val appContext = applicationContext
Thread({
SessionArtifacts.collect(appContext, dir, reason)
SessionPaths.release(appContext, dir)
}, "session-failure-artifacts").start()
}
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
private fun progressFor(what: String, mb: Long) = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, p ->
uiHandler.post {
@@ -441,7 +493,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (installingRuntime) return
if (installingRuntime || SessionState.stopRequested) return
if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
// the evdev codes we inject.
@@ -505,6 +560,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
)
if (!SessionState.running) SessionEvents.record("compositor.started")
// ADPF: the compositor thread's frame intervals go to the power HAL against the panel's
// period, so a long frame raises CPU clocks now rather than after the load averages up.
PerfHints.arm(this, refreshHz())
@@ -514,6 +570,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// start nothing, and leave the loading panel counting up over a dead session.
if (!SessionState.running) {
CompositorHost.newSession()
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
SessionService.start(
this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM,
intent.getStringExtra(SessionService.EXTRA_PROGRAM),
@@ -616,6 +673,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val poll = object : Runnable {
override fun run() {
if (!watching) return
if (SessionState.stopRequested && !SessionState.running && !installingRuntime) {
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
collectStartArtifacts("session start cancelled")
finish()
return
}
if (loading.visible && !loading.ended) {
if (!installingRuntime) loading.update(this@SessionActivity, SessionState.logFile)
if (ticks++ % 2 == 0) loading.tick()
@@ -43,6 +43,7 @@ object SessionArtifacts {
copySteamLogs(context, dir)
// A session the system killed leaves its trace here and nowhere else.
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
Log.w(TAG, "collecting session artifacts", e)
@@ -72,6 +73,7 @@ object SessionArtifacts {
* older folder would be handed logs that are not its own. Runs on a worker thread at app
* start; nothing here touches the session that is about to begin.
*/
@Synchronized
fun finishAbandoned(context: Context) {
val parent = LinuxRuntime.debugLogDir()
val abandoned = parent.listFiles { f ->
@@ -97,6 +99,7 @@ object SessionArtifacts {
copySteamLogs(context, dir)
}
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
@@ -0,0 +1,117 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
/** Writes the machine-readable lifecycle stream beside the existing session artifacts. */
object SessionEvents {
private const val TAG = "SessionEvents"
private val lock = Any()
fun begin(context: Context, mode: String) {
// A runtime-install failure can leave the folder claimed before the service ever starts.
// Keep that folder, but give the next attempt its own session directory.
SessionPaths.take()
val dir = SessionPaths.beginOrCurrent(context)
synchronized(SessionState) {
SessionState.phase = SessionPhase.PREPARING
SessionState.mode = mode
SessionState.sessionId = dir.name
SessionState.lastTransitionAt = System.currentTimeMillis()
SessionState.failureCode = null
SessionState.failureMessage = null
SessionState.failureStatus = null
SessionState.logDirectory = dir
SessionState.logFile = File(dir, "session.log")
SessionState.eventsFile = File(dir, "events.jsonl")
SessionState.guestPid = -1
SessionState.installing = null
SessionState.stopRequested = false
SessionState.program = null
SessionState.programArgs = emptyList()
SessionState.steamUi = null
SessionState.steamUrl = null
SessionState.firstFrameSeen = false
SessionState.suspended = false
}
record("session.created", mapOf("mode" to mode), dir)
}
fun transition(
phase: SessionPhase,
event: String,
fields: Map<String, Any?> = emptyMap(),
) {
synchronized(SessionState) {
if (SessionState.phase != phase) {
SessionState.phase = phase
SessionState.lastTransitionAt = System.currentTimeMillis()
}
}
record(event, fields)
}
fun record(event: String, fields: Map<String, Any?> = emptyMap(), directory: File? = null) {
val dir = directory ?: SessionState.logDirectory ?: SessionPaths.current() ?: return
val target = if (directory == null) SessionState.eventsFile ?: File(dir, "events.jsonl")
else File(dir, "events.jsonl")
val payload = JSONObject()
.put("t", System.currentTimeMillis())
.put("event", event)
.put("sessionId", dir.name)
fields.forEach { (key, value) -> payload.put(key, value ?: JSONObject.NULL) }
try {
synchronized(lock) {
target.parentFile?.mkdirs()
FileOutputStream(target, true).use { stream ->
stream.write((payload.toString() + "\n").toByteArray(Charsets.UTF_8))
}
}
} catch (e: Exception) {
Log.w(TAG, "writing ${target.name}", e)
}
}
fun fail(code: String, message: String, status: Int? = null) {
synchronized(SessionState) {
SessionState.phase = SessionPhase.FAILED
SessionState.lastTransitionAt = System.currentTimeMillis()
SessionState.failureCode = code
SessionState.failureMessage = message
SessionState.failureStatus = status
}
record("session.failed", mapOf("code" to code, "message" to message, "status" to status))
}
fun firstFrame() {
SessionState.firstFrameSeen = true
record("frame.first")
markReadyIfPossible()
}
fun guestStarted(pid: Int) {
SessionState.guestPid = pid
record("guest.started", mapOf("pid" to pid))
if (SessionState.mode == SessionService.MODE_STEAM) {
transition(SessionPhase.STARTING_STEAM, "steam.starting")
}
markReadyIfPossible()
}
fun markReadyIfPossible() {
if (!SessionState.running || SessionState.guestPid <= 1 || !SessionState.firstFrameSeen || SessionState.suspended) return
if (SessionState.phase != SessionPhase.READY) {
transition(SessionPhase.READY, "session.ready")
}
}
fun resumePhase(): SessionPhase = when {
SessionState.firstFrameSeen && SessionState.guestPid > 1 -> SessionPhase.READY
SessionState.mode == SessionService.MODE_STEAM && SessionState.guestPid > 1 -> SessionPhase.STARTING_STEAM
else -> SessionPhase.STARTING_GUEST
}
}
@@ -41,7 +41,10 @@ object SessionPaths {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val made = File(parent, "session-$stamp")
val baseName = "session-$stamp"
var made = File(parent, baseName)
var suffix = 2
while (made.exists()) made = File(parent, "$baseName-${suffix++}")
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
@@ -155,6 +155,11 @@ class SessionService : Service() {
}
startForeground(NOTIFICATION_ID, buildNotification())
if (SessionState.running) return START_NOT_STICKY
if (SessionState.stopRequested) {
SessionState.running = true
stopSession(0)
return START_NOT_STICKY
}
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
activityVisible = true
@@ -168,11 +173,17 @@ class SessionService : Service() {
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
SessionState.running = true
if (SessionState.stopRequested) {
stopSession(0)
return START_NOT_STICKY
}
// Another Steam client on the device signs ours out seconds after every login; the one that
// does it here runs from boot without being opened. Only the Steam session signs in.
if (SessionState.mode == MODE_STEAM) RivalClients.stopBeforeSession(this)
SessionState.running = true
SessionState.firstFrameSeen = false
SessionState.guestPid = -1
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
// This session's number, claimed here and not when its process starts: the session it
// replaces can report its own exit in the gap between the two, and that exit must not
// be taken as this one's.
@@ -249,6 +260,10 @@ class SessionService : Service() {
val sessionDir = SessionPaths.beginOrCurrent(this)
val sessionLog = File(sessionDir, "session.log")
SessionState.logFile = sessionLog
SessionState.logDirectory = sessionDir
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
// Written first, so a session that dies in its first second still says what it ran on.
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
@@ -590,6 +605,14 @@ class SessionService : Service() {
stopSession(status ?: -1)
}, null)
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
if (gen == sessionGen && SessionState.running && sessionPid > 1) {
SessionEvents.guestStarted(sessionPid)
} else if (gen == sessionGen && SessionState.running) {
SessionEvents.record("guest.start_failed", mapOf("pid" to sessionPid))
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", sessionPid)
stopSession(-1)
return
}
if (gen == sessionGen && SessionState.running) {
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
@@ -752,6 +775,7 @@ class SessionService : Service() {
suspendOperationPending = false
if (success) {
SessionState.suspended = true
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
} else {
@@ -769,6 +793,7 @@ class SessionService : Service() {
suspendOperationPending = false
if (success) {
SessionState.suspended = false
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
refreshNotification()
} else {
suspendAttemptFailed = true
@@ -783,7 +808,16 @@ class SessionService : Service() {
private fun finishSessionStop(status: Int) {
mainHandler.post {
SessionState.suspended = false
SessionState.guestPid = -1
releaseLocks()
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
@@ -793,6 +827,9 @@ class SessionService : Service() {
private fun stopSession(status: Int) {
if (!SessionState.running) return
SessionState.running = false
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false
launchWatcher?.stopWatching()
launchWatcher = null
@@ -11,14 +11,51 @@ import androidx.compose.runtime.setValue
* either can outlive the other.
*/
object SessionState {
@Volatile
var phase = SessionPhase.IDLE
@Volatile
var sessionId: String? = null
@Volatile
var lastTransitionAt = 0L
@Volatile
var failureCode: String? = null
@Volatile
var failureMessage: String? = null
@Volatile
var failureStatus: Int? = null
@Volatile
var logDirectory: File? = null
@Volatile
var eventsFile: File? = null
@Volatile
var guestPid = -1
@Volatile
var installing: String? = null
@Volatile
var stopRequested = false
@Volatile
var running = false
var suspended by mutableStateOf(false)
/** MODE_RUN: the program inside the runtime the session was started for. */
@Volatile
var program: String? = null
@Volatile
var programArgs: List<String> = emptyList()
/** MODE_STEAM: "desktop" for the client's desktop UI, else Big Picture; and a steam:// URL to hand it. */
@Volatile
var steamUi: String? = null
@Volatile
var steamUrl: String? = null
/** A session the guest asked for (the desktop's Steam launchers): started by the activity once this one has ended. */
var relaunch: android.content.Intent? = null
@@ -57,3 +94,17 @@ object SessionState {
endListener?.invoke(status)
}
}
/** Stable lifecycle values returned by the debug agent bridge. */
enum class SessionPhase {
IDLE,
PREPARING,
INSTALLING_RUNTIME,
STARTING_COMPOSITOR,
STARTING_GUEST,
STARTING_STEAM,
READY,
SUSPENDED,
STOPPING,
FAILED,
}