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

@@ -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,
}