From fa95df37d0893f4f61ea771adcf15a5b988a4fb7 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Tue, 17 Nov 2026 12:27:54 -0500
Subject: [PATCH] fix(session): keep the session the top app on dual screens
under memory pressure (#2763)
---
app/src/main/AndroidManifest.xml | 9 ++
.../com/droiddeck/launcher/SessionActivity.kt | 70 +++++++++++++-
.../launcher/session/KeepTopActivity.kt | 91 +++++++++++++++++++
.../droiddeck/launcher/session/LightPause.kt | 32 +++++++
.../launcher/session/SessionService.kt | 3 +-
.../launcher/session/TopUnderPressure.kt | 13 +++
.../launcher/session/LightPauseTest.kt | 56 ++++++++++++
.../launcher/session/TopUnderPressureTest.kt | 25 +++++
tools/release/sign-apk.sh | 2 +-
9 files changed, 296 insertions(+), 5 deletions(-)
create mode 100644 app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt
create mode 100644 app/src/main/java/com/droiddeck/launcher/session/LightPause.kt
create mode 100644 app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt
create mode 100644 app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt
create mode 100644 app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 54fe09ca7c..1cb41756c9 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -298,6 +298,15 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
+
= 0 || intent.component?.packageName == packageName ||
+ if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
+ (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)
@@ -5608,6 +5611,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onStop() {
+ if (lightPause.stopped()) departureCleanup()
if (runtimeRemovalBlocked) { super.onStop(); return }
started = false
if (::hud.isInitialized) hud.setBackgrounded(true)
@@ -5651,6 +5655,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
+ 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) }
@@ -5716,10 +5726,63 @@ 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)
+ }
+ }
+
+ // 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)
+ if (isTopResumedActivity) 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) 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()
+ super.onPause()
+ }
+
+ private fun departureCleanup() {
com.droiddeck.launcher.input.SystemKeyCapture.detach(this)
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
- if (runtimeRemovalBlocked) { super.onPause(); return }
+ if (runtimeRemovalBlocked) return
physicalShortcuts.clear()
backQamInput.cancel()
mouseBackInput.cancel()
@@ -5763,7 +5826,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener)
updateHeadTracker()
- super.onPause()
}
private fun steamVrAction(action: String) {
@@ -6375,6 +6437,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onDestroy() {
+ uiHandler.removeCallbacks(guardWhenRunning)
+ com.droiddeck.launcher.session.KeepTopActivity.release()
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
frameGenRequests.incrementAndGet()
diff --git a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt
new file mode 100644
index 0000000000..849c0aafcc
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt
@@ -0,0 +1,91 @@
+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.WindowManager
+
+// While a session runs, sits invisibly on top of every other display until it ends, 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.
+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_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
+ val id = display?.displayId ?: Display.INVALID_DISPLAY
+ starting.remove(id)
+ guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
+ guards[id] = this
+ }
+
+ 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()
+ private const val START_TIMEOUT_MS = 2_000L
+ private val starting = HashMap()
+
+ 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 || 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 release() {
+ generation++
+ guards.values.toList().forEach { it.finishAndRemoveTask() }
+ guards.clear()
+ starting.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())
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt
new file mode 100644
index 0000000000..6ac1eabf9f
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt
@@ -0,0 +1,32 @@
+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 }
+}
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 ed43345497..4bc21b704a 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -2347,7 +2347,8 @@ 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)) return
+ com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
+ KeepTopActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
diff --git a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt
new file mode 100644
index 0000000000..3c7a55adea
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt
@@ -0,0 +1,13 @@
+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
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt
new file mode 100644
index 0000000000..8e14b74147
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt
@@ -0,0 +1,56 @@
+package com.droiddeck.launcher.session
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LightPauseTest {
+ @Test
+ fun theBounceAloneResumesLight() {
+ val pause = LightPause()
+ pause.paused(bounces = 3)
+ assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4))
+ assertFalse(pause.timedOut())
+ }
+
+ @Test
+ fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() {
+ val pause = LightPause()
+ pause.paused(bounces = 3)
+ assertTrue(pause.timedOut())
+ assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3))
+ }
+
+ @Test
+ fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() {
+ val pause = LightPause()
+ pause.paused(bounces = 3)
+ assertTrue(pause.timedOut())
+ assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
+ }
+
+ @Test
+ fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() {
+ val pause = LightPause()
+ pause.paused(bounces = 3)
+ assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3))
+ assertFalse(pause.timedOut())
+ }
+
+ @Test
+ fun aStopAfterALightPauseCleansUpOnce() {
+ val pause = LightPause()
+ pause.paused(bounces = 3)
+ assertTrue(pause.stopped())
+ assertFalse(pause.timedOut())
+ assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
+ }
+
+ @Test
+ fun aNormalPauseIsUntouched() {
+ val pause = LightPause()
+ assertFalse(pause.stopped())
+ assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt
new file mode 100644
index 0000000000..ac0ec06843
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt
@@ -0,0 +1,25 @@
+package com.droiddeck.launcher.session
+
+import android.content.ComponentCallbacks2
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class TopUnderPressureTest {
+ @Test
+ fun onlyRunningLevelsCountAsPressure() {
+ assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL))
+ assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW))
+ assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE))
+ assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN))
+ }
+
+ @Test
+ fun reclaimsOnlyDuringASessionShortlyAfterPressure() {
+ assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false))
+ assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false))
+ assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false))
+ assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false))
+ assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true))
+ }
+}
diff --git a/tools/release/sign-apk.sh b/tools/release/sign-apk.sh
index 15fbb4e33c..0373e80ee5 100755
--- a/tools/release/sign-apk.sh
+++ b/tools/release/sign-apk.sh
@@ -29,7 +29,7 @@ else
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
- "$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" \
+ "$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
fi
got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p")