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

+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Debug builds only. Android grants DUMP to adb shell; release APKs have no bridge. -->
<provider
android:name=".agent.AgentBridgeProvider"
android:authorities="${applicationId}.agent"
android:exported="true"
android:permission="android.permission.DUMP"
android:grantUriPermissions="false" />
</application>
</manifest>
@@ -0,0 +1,249 @@
package com.droiddeck.launcher.agent
import android.Manifest
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Binder
import android.os.Bundle
import android.os.Process
import android.util.Base64
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/** A shell-only control surface, installed only by debug builds. */
class AgentBridgeProvider : ContentProvider() {
private val recoveryComplete = CountDownLatch(1)
override fun onCreate(): Boolean {
val appContext = context?.applicationContext ?: return false
Thread({
try {
SessionArtifacts.finishAbandoned(appContext)
} finally {
recoveryComplete.countDown()
}
}, "agent-recover-artifacts").start()
return true
}
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
val context = requireNotNull(context)
if (Binder.getCallingUid() != Process.myUid() &&
context.checkCallingPermission(Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED
) {
throw SecurityException("android.permission.DUMP is required")
}
val response = try {
when (method) {
"state" -> state(context).put("ok", true)
"start" -> start(context, arg.orEmpty(), extras)
"stop" -> stop(context)
"resume" -> resume(context)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
}
} catch (e: Exception) {
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
}
return Bundle().apply { putString(RESULT_JSON, response.toString()) }
}
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
.put("running", SessionState.running)
.put("mode", SessionState.mode)
.put("program", SessionState.program ?: JSONObject.NULL)
.put("steamUi", SessionState.steamUi ?: JSONObject.NULL)
.put("steamUrl", SessionState.steamUrl ?: JSONObject.NULL)
.put("suspended", SessionState.suspended)
.put("firstFrame", SessionState.firstFrameSeen)
.put("output", JSONArray().put(SessionState.outputSize.first).put(SessionState.outputSize.second))
.put("refreshHz", SessionState.refreshHz.toDouble())
.put("lastTransitionAt", SessionState.lastTransitionAt)
.put("guestPid", SessionState.guestPid.takeIf { it > 1 } ?: JSONObject.NULL)
.put("installing", SessionState.installing ?: JSONObject.NULL)
.put("logDir", dir?.absolutePath ?: JSONObject.NULL)
.put("eventsFile", dir?.let { File(it, "events.jsonl").absolutePath } ?: JSONObject.NULL)
.put("artifactsAvailable", dir?.isDirectory ?: false)
.put("artifactsComplete", dir?.let { File(it, ".complete").isFile } ?: false)
val failure = if (SessionState.failureCode == null) JSONObject.NULL else JSONObject()
.put("code", SessionState.failureCode)
.put("message", SessionState.failureMessage ?: JSONObject.NULL)
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
session.put("failure", failure)
return JSONObject()
.put("schema", 1)
.put("build", BuildConfig.BUILD_LABEL)
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
.put("runtime", JSONObject()
.put("installed", LinuxRuntime.isInstalled(context))
.put("version", runtimeVersion ?: JSONObject.NULL))
.put("session", session)
}
private fun latestSessionDirectory(): File? {
val parent = LinuxRuntime.debugLogDir()
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
}
private fun start(context: Context, requested: String, extras: Bundle?): JSONObject {
if (SessionState.running || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
return error("SESSION_ACTIVE", "A session is already starting or running")
}
val request = request(extras)
val mode = request?.optString("mode")?.takeIf { it.isNotBlank() } ?: requested
val intent = Intent(context, SessionActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val sessionMode: String
when (mode) {
"steam" -> {
sessionMode = SessionService.MODE_STEAM
intent.putExtra(SessionService.EXTRA_MODE, sessionMode)
}
"desktop", SessionService.MODE_DESKTOP -> {
sessionMode = SessionService.MODE_DESKTOP
intent.putExtra(SessionService.EXTRA_MODE, sessionMode)
}
"run" -> {
sessionMode = SessionService.MODE_RUN
val program = request?.optString("program")?.takeIf { it.isNotBlank() }
?: return error("PROGRAM_REQUIRED", "Run mode requires a program path")
val args = request?.optJSONArray("programArgs") ?: JSONArray()
val programArgs = Array(args.length()) { index ->
args.optString(index)
}
intent.putExtra(SessionService.EXTRA_MODE, sessionMode)
.putExtra(SessionService.EXTRA_PROGRAM, program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, programArgs)
}
else -> return error("INVALID_MODE", "Mode must be steam, desktop, or run")
}
request?.optString("steamUi")?.takeIf { it == "desktop" }?.let {
intent.putExtra(SessionService.EXTRA_STEAM_UI, it)
}
request?.optString("steamUrl")?.takeIf { it.startsWith("steam://") }?.let {
intent.putExtra(SessionService.EXTRA_STEAM_URL, it)
}
awaitRecovery()
return try {
SessionEvents.begin(context, sessionMode)
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)
SessionEvents.record("agent.start_requested", mapOf("mode" to sessionMode))
context.startActivity(intent)
JSONObject().put("ok", true).put("command", "start").put("mode", mode)
} catch (e: Exception) {
val message = e.message ?: e.javaClass.simpleName
SessionEvents.fail("ACTIVITY_START_FAILED", message)
val dir = SessionPaths.take()
if (dir != null) {
val appContext = context.applicationContext
Thread({
SessionArtifacts.collect(appContext, dir, "activity start failed")
SessionPaths.release(appContext, dir)
}, "agent-start-failure-artifacts").start()
}
error("ACTIVITY_START_FAILED", message)
}
}
private fun stop(context: Context): JSONObject {
if (SessionState.running) {
SessionService.stop(context)
return JSONObject().put("ok", true).put("command", "stop")
}
if (SessionState.phase == SessionPhase.STOPPING) {
return JSONObject().put("ok", true).put("command", "stop")
}
if (SessionState.phase in STARTING_PHASES) {
SessionState.stopRequested = true
SessionEvents.transition(SessionPhase.STOPPING, "session.stop_requested")
return JSONObject().put("ok", true).put("command", "stop")
}
return error("NO_ACTIVE_SESSION", "There is no session to stop")
}
private fun resume(context: Context): JSONObject {
if (!SessionState.running || !SessionState.suspended) {
return error("SESSION_NOT_SUSPENDED", "There is no suspended session to resume")
}
SessionService.resume(context)
return JSONObject().put("ok", true).put("command", "resume")
}
private fun request(extras: Bundle?): JSONObject? {
val encoded = extras?.getString(REQUEST_EXTRA) ?: return null
return try {
val decoded = Base64.decode(encoded, Base64.DEFAULT)
JSONObject(String(decoded, Charsets.UTF_8))
} catch (e: JSONException) {
throw IllegalArgumentException("Invalid request JSON", e)
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid base64 request", e)
}
}
private fun awaitRecovery() {
try {
if (!recoveryComplete.await(90, TimeUnit.SECONDS)) {
throw IllegalStateException("Session artifact recovery did not finish")
}
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw IllegalStateException("Interrupted while recovering session artifacts", e)
}
}
private fun error(code: String, message: String) = JSONObject()
.put("ok", false)
.put("error", JSONObject().put("code", code).put("message", message))
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
companion object {
const val RESULT_JSON = "json"
const val REQUEST_EXTRA = "request"
private val STARTING_PHASES = setOf(
SessionPhase.PREPARING,
SessionPhase.INSTALLING_RUNTIME,
SessionPhase.STARTING_COMPOSITOR,
SessionPhase.STARTING_GUEST,
SessionPhase.STARTING_STEAM,
)
}
}
@@ -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,
}