fix(session): remove the keep-top guard from other displays (#2937)

* fix(session): remove the keep-top guard from other displays

#2763 put a transparent KeepTopActivity on every other display while a
session was on top, so lmkd killing that display's home could not move focus
off the session. A/B on a 12 GB AYN Thor (Android 13) and a Retroid Pocket
Duo (Android 16) found no case where it kept a session alive: with steady
pressure the bottom home (stock launcher or Cocoon) was killed up to 400
times per run without taking focus, and a burst big enough to matter makes
lmkd kill the session at adj 0 with or without the guard.

Its side effects were real:
- Android's ActivityRecordInputSink made the bottom screen ignore touch
  (worked around in #2910 by stepping aside on touch).
- Cocoon tracks each display's top activity, so it could not suspend or
  resume DroidDeck cleanly.
- The Thor's Game Assistant gives every app with an activity on top of the
  bottom display that display's volume, so DroidDeck's audio followed the
  bottom screen's volume slider.

Removes KeepTopActivity, the focus bounce and light pause, the memory
pressure trigger and their tests. onPause runs its departure cleanup every
time again.

tools/memory_guard_ab.py gains a burst mode, reads oom_score_adj without
su (lmkd kills the root manager app and su can then open its request screen
over the game), handles Android 13 dumps, a hung stop and a session that
does not start. docs/development/memory-guard-ab.md has the Thor results.

* test(session): the guard A/B fill mode starts its counter again, and a pressure run with no completed run fails

* test(session): the burst seed is rebuilt unless it is exactly 256 MiB

* test(session): the guard A/B burst takes its last partial chunk, and only a hog run that finished counts
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-20 11:40:10 -05:00
1 parent acb2cba970
commit d0022a35f9
11 files changed
+149 -380

No files matched your search

@@ -3251,8 +3251,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onSessionEnded(status: Int) {
ended = true
uiHandler.removeCallbacks(guardWhenRunning)
com.droiddeck.launcher.session.KeepTopActivity.release()
++steamVrRequestGeneration
if (isInPictureInPictureMode) {
runOnUiThread { finish() }
@@ -5740,11 +5738,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
super.onPictureInPictureModeChanged(inPip, newConfig)
if (inPip) {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
}
if (::pip.isInitialized) pip.changed(inPip)
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
applyUnfoldedControls()
@@ -5753,8 +5746,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
(requestCode >= 0 || intent.component?.packageName == packageName ||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT,
Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background()
super.startActivityForResult(intent, requestCode, options)
@@ -5786,10 +5778,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onStop() {
if (lightPause.stopped()) departureCleanup()
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
if (runtimeRemovalBlocked) { super.onStop(); return }
started = false
if (::hud.isInitialized) hud.setBackgrounded(true)
@@ -5834,13 +5822,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield
uiHandler.removeCallbacks(lightPauseCheck)
when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) {
com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return
com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup()
com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit
}
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
@@ -5906,73 +5887,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
}
private var memoryPressureAt = 0L
private var focusBounce = false
private val lightPause = com.droiddeck.launcher.session.LightPause()
private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() }
private var topResumed = false
private val guardWhenRunning = object : Runnable {
override fun run() {
if (!topResumed || isFinishing) return
if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000)
}
}
// A touch that removed a guard while the session kept the top spot did not move focus to that
// display, so the guard comes back unless the user carries on there.
private val rearmAfterYield = Runnable {
if (topResumed && !isFinishing) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
guardOtherDisplays()
}
}
private val onGuardYield: () -> Unit = {
uiHandler.removeCallbacks(rearmAfterYield)
uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS)
}
// RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up
// as soon as a running session is on top.
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return
memoryPressureAt = android.os.SystemClock.elapsedRealtime()
guardOtherDisplays()
}
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (isTopResumedActivity) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
uiHandler.post(guardWhenRunning)
}
else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim(
android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays()
}
private fun guardOtherDisplays() {
if (!SessionState.running || isFinishing || isInPictureInPictureMode) return
val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)
val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY)
if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS)
}
if (!bounced) return
if (!wasResumed) return
focusBounce = true
uiHandler.postDelayed({ focusBounce = false }, 500)
}
override fun onPause() {
if (focusBounce) {
focusBounce = false
lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces)
uiHandler.postDelayed(lightPauseCheck, 200)
} else departureCleanup()
departureCleanup()
super.onPause()
}
@@ -6635,10 +6551,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onDestroy() {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null
com.droiddeck.launcher.session.KeepTopActivity.release()
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
frameGenRequests.incrementAndGet()
@@ -1,120 +0,0 @@
package com.droiddeck.launcher.session
import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.view.WindowManager
// While a session is on screen, sits invisibly on top of every other display, so that display's
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
// it takes focus from the session, which then drops to adj 50 and is killed next.
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
// display whatever its window flags say, so a touch makes the guard leave that display until the
// session is back on top.
class KeepTopActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@Suppress("DEPRECATION") overridePendingTransition(0, 0)
if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) {
bounces++
finish()
return
}
if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) {
finishAndRemoveTask()
return
}
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
val id = display?.displayId ?: Display.INVALID_DISPLAY
starting.remove(id)
if (id in yielded) {
finishAndRemoveTask()
return
}
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
guards[id] = this
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
val id = display?.displayId ?: Display.INVALID_DISPLAY
yielded.add(id)
Log.i(TAG, "display $id touched, leaving it to the app below")
finishAndRemoveTask()
onYield?.invoke()
}
return true
}
override fun onDestroy() {
guards.values.remove(this)
super.onDestroy()
}
companion object {
private const val TAG = "KeepTop"
private const val EXTRA_BOUNCE = "bounce"
private const val EXTRA_GENERATION = "generation"
private var generation = 0
var bounces = 0
private set
private val guards = HashMap<Int, KeepTopActivity>()
private const val START_TIMEOUT_MS = 2_000L
private val starting = HashMap<Int, Long>()
private val yielded = HashSet<Int>()
const val YIELD_GRACE_MS = 5_000L
var onYield: (() -> Unit)? = null
fun rearm() = yielded.clear()
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
var started = false
for (display in displays) {
val id = display.displayId
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
runCatching {
launch(context, id, bounce = false)
starting[id] = SystemClock.elapsedRealtime()
started = true
Log.i(TAG, "guarding display $id from a home launcher restart")
}.onFailure { Log.w(TAG, "could not guard display $id", it) }
}
if (!started) return false
return runCatching { launch(context, sessionDisplay, bounce = true) }
.onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess
}
fun hasPendingStarts() = starting.isNotEmpty()
const val RETRY_MS = START_TIMEOUT_MS + 250
fun stepAside() {
generation++
guards.values.toList().forEach { it.finishAndRemoveTask() }
guards.clear()
starting.clear()
}
fun release() {
stepAside()
yielded.clear()
}
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
val intent = Intent(context, KeepTopActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
.putExtra(EXTRA_BOUNCE, bounce)
.putExtra(EXTRA_GENERATION, generation)
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
}
}
}
@@ -1,32 +0,0 @@
package com.droiddeck.launcher.session
// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce.
internal class LightPause {
private var pending = false
private var bouncesAtPause = 0
fun paused(bounces: Int) {
pending = true
bouncesAtPause = bounces
}
// The bounce resumes the session within tens of milliseconds; still paused at the timeout means
// something else holds the pause.
fun timedOut(): Boolean = take()
fun stopped(): Boolean = take()
fun resumed(bounces: Int): Resume {
if (!pending) return Resume.NORMAL
pending = false
return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST
}
private fun take(): Boolean {
val was = pending
pending = false
return was
}
enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST }
}
@@ -2394,8 +2394,7 @@ class SessionService : Service() {
override fun onTaskRemoved(rootIntent: Intent?) {
if (rootIntent?.component?.className in setOf(
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
KeepTopActivity::class.java.name)) return
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -1,13 +0,0 @@
package com.droiddeck.launcher.session
import android.content.ComponentCallbacks2
internal object TopUnderPressure {
const val WINDOW_MS = 5_000L
fun isPressure(level: Int) =
level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) =
sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS
}