Merge upstream main and preserve routed Home input

Integrate upstream 213c2da5, keeping Home/Guide player-slot handling compatible with remapped controls and disabled routing. Preserve the input-settings overlay gate for Home and Steam volume keys.

Validation: 2,707 JVM tests across 389 suites pass. Device validation and latency measurements were not repeated.
This commit is contained in:
Delete228 committed 2026-10-28 12:45:41 +03:00
commit b245017593
121 files changed
+7170 -348

No files matched your search

@@ -0,0 +1,20 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceReportCpuTest {
@Test fun onlyFeatureListsAreReportedAndDifferentCoreCapabilitiesAreKept() {
val cpuInfo = """
processor : 0
Features : fp asimd aes
Serial : private-device-id
processor : 1
Features : fp asimd aes atomics
processor : 2
Features : fp asimd aes
""".trimIndent()
assertEquals("fp asimd aes | fp asimd aes atomics", DeviceReport.cpuFeaturesSummary(cpuInfo))
assertEquals("not reported", DeviceReport.cpuFeaturesSummary("processor : 0\n"))
}
}
@@ -3,9 +3,14 @@ package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.StringWriter
class LogRedactorTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun labelledJwtIsRedacted() {
val out = LogRedactor.redact("Using JWT 25484942796017334")
assertFalse(out.contains("25484942796017334"))
@@ -226,6 +231,103 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redactForShare(once))
}
@Test fun anOversizedDirectInputIsWithheldBeforeRegex() {
val secret = "sessionid=abcdef123456"
val line = "x".repeat(LogRedactor.MAX_LINE_LENGTH) + secret
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redact(line))
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redactForShare(line))
}
@Test fun streamWithholdsAnOversizedLogicalLineWholeAndContinues() {
val secret = "sessionid=abcdef123456"
val src = tmp.newFile("oversized.log")
src.writeText(
"before\r" +
"x".repeat(LogRedactor.MAX_LINE_LENGTH - 3) + secret + "\r\n" +
"after $secret"
)
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(
"before\n${LogRedactor.OVERSIZED_LINE}\nafter sessionid=<redacted:token>\n",
out.toString(),
)
assertFalse(out.toString().contains("abcdef123456"))
}
@Test fun sharedStreamDistinguishesOversizedAndUnsupportedLines() {
val src = tmp.newFile("shared-lines.log")
src.writeText(
"x".repeat(LogRedactor.MAX_LINE_LENGTH + 1) + "\n" +
"private-prefix\u0000private-suffix\n" +
"after sessionid=abcdef123456\n"
)
val out = StringWriter()
assertTrue(LogRedactor.scrubForShare(src, out))
assertEquals(
"${LogRedactor.OVERSIZED_LINE}\n" +
"<unsupported or oversized line withheld>\n" +
"after sessionid=<redacted:token>\n",
out.toString(),
)
}
@Test fun aMaximumLengthLineBeforeCrLfIsStillScrubbed() {
val src = tmp.newFile("maximum.log")
val line = "x ".repeat(LogRedactor.MAX_LINE_LENGTH / 2)
src.writeText(line + "\r\n")
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(line + "\n", out.toString())
assertFalse(out.toString().contains(LogRedactor.OVERSIZED_LINE))
}
@Test fun streamingScrubStopsBetweenInputChunks() {
val src = tmp.newFile("cancelled.log")
src.writeText("first safe line\n" + "x".repeat(20_000) + " sessionid=abcdef123456\n")
val out = StringWriter()
var checks = 0
val complete = LogRedactor.scrubTo(src, out) { ++checks >= 4 }
assertFalse(complete)
assertFalse(out.toString().contains("abcdef123456"))
assertTrue(checks >= 4)
}
@Test fun manyLearnedAccountsKeepBoundariesAndLiteralNames() {
val users = tmp.newFile("loginusers.vdf")
users.writeText((0 until 40).joinToString("\n") {
"\"AccountName\" \"probe_account_$it\""
} + "\n\"PersonaName\" \"Player.+[40]\"\n")
try {
LogRedactor.learnAccounts(users)
assertEquals("owner=<redacted:account> persona=<redacted:account>",
LogRedactor.redact("owner=probe_account_39 persona=Player.+[40]"))
assertEquals("owner=probe_account_390", LogRedactor.redact("owner=probe_account_390"))
} finally {
LogRedactor.learnAccounts(tmp.root.resolve("missing-users"))
}
}
@Test fun manyLearnedAddressesKeepOtherAddresses() {
val link = tmp.newFile("droiddeck-net")
link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" })
try {
LogRedactor.learnOwnAddresses(link)
assertEquals("local=<redacted:ip> server=203.0.113.200",
LogRedactor.redact("local=203.0.113.40 server=203.0.113.200"))
} finally {
LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network"))
}
}
@Test fun learnedAccountsComeFromBothClients() {
val root = java.nio.file.Files.createTempDirectory("redactor").toFile()
try {
@@ -1,6 +1,11 @@
package com.droiddeck.launcher.gpu
import android.os.Environment
import android.os.Build
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@@ -9,6 +14,7 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -16,10 +22,23 @@ class TurnipDriverAutoTest {
@Before fun reset() {
ShadowBuild.setModel("Phone")
ShadowBuild.setDevice("phone")
overrideFile().delete()
}
@After fun cleanUp() {
overrideFile().delete()
SessionPrefs.setAndroidDriver(RuntimeEnvironment.getApplication(), TurnipDriver.AUTO)
File(RuntimeEnvironment.getApplication().filesDir, "graphics_driver/test-pinned").deleteRecursively()
}
private fun overrideFile() = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-driver")
private fun gpu(model: Int, adreno: Boolean = true) = GpuInfo(
"test GPU", model, GpuInfo.familyOf(adreno, model), "", false,
)
@Test fun questModelsUseTheirPatchedDriverAsTheFallback() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication())
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("Quest must not use generic GPU detection") }
for (model in listOf("Quest 3", "Quest 3S", "Quest 2")) {
ShadowBuild.setModel(model)
assertEquals(if (model == "Quest 2") QuestExperimental.DRIVER_A6XX else QuestExperimental.DRIVER,
@@ -27,8 +46,54 @@ class TurnipDriverAutoTest {
}
}
@Test fun otherDevicesRetainTheGenericFallback() {
assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
@Test fun aNonAdrenoDeviceDoesNotAutomaticallyLoadTurnip() {
assertEquals(GpuInfo.Family.NOT_ADRENO, GpuInfo.detect().family)
assertEquals("system", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
}
@Test fun autoSelectionUsesTheDetectedFamilyAndModel() {
val context = RuntimeEnvironment.getApplication()
for ((detected, expected) in listOf(
gpu(0, adreno = false) to "system",
gpu(0) to "turnip25.1.0",
gpu(650) to "turnip26.3.0-a6xx",
gpu(730) to "turnip25.1.0",
gpu(850) to "turnip-sdk36",
)) {
var calls = 0
assertEquals(expected, TurnipDriver(context) { calls++; detected }.autoId())
assertEquals(1, calls)
}
}
@Test fun nonAdrenoDoesNotUseTheAndroid16TurnipFallback() {
val context = RuntimeEnvironment.getApplication()
val sdk = Build.VERSION.SDK_INT
try {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 36)
assertEquals("system", TurnipDriver(context) { gpu(0, adreno = false) }.autoId())
assertEquals("turnip-sdk36", TurnipDriver(context) { gpu(0) }.autoId())
} finally {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", sdk)
}
}
@Test fun externalOverrideStillTakesPriorityOverDetection() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("override must precede detection") }
overrideFile().parentFile!!.mkdirs()
overrideFile().writeText("system")
assertEquals("system", driver.autoId())
overrideFile().writeText("a8")
assertEquals("turnip-sdk36", driver.autoId())
}
@Test fun aManuallySelectedImportedDriverStillTakesPriorityOverDetection() {
val context = RuntimeEnvironment.getApplication()
val dir = File(context.filesDir, "graphics_driver/test-pinned").apply { mkdirs() }
File(dir, "meta.json").writeText("""{"libraryName":"test.so"}""")
File(dir, "test.so").writeText("")
SessionPrefs.setAndroidDriver(context, "test-pinned")
assertEquals("test-pinned", TurnipDriver(context) { error("manual choice must precede detection") }.install())
}
@Test fun normalizedGpuModelsSelectExistingGenerationDrivers() {
@@ -27,6 +27,14 @@ class HomeGuideInputTest {
assertEquals(listOf(true, false), states)
}
@Test fun genericLayoutMoveHomeHoldsGuideLikeHome() {
val down = KeyEvent(10, 110, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102)
val up = KeyEvent(10, 200, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102)
assertTrue(input.onKeyEvent(down, true))
assertTrue(input.onKeyEvent(up, true))
assertEquals(listOf(true, false), states)
}
@Test fun anUnownedHomePressKeepsAndroidBehaviorEvenIfSessionBecomesEligibleBeforeRelease() {
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false))
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), true))
@@ -343,6 +343,102 @@ class PadBridgeQamTest {
assertFalse(pad().isDown(PadState.X))
}
@Test fun homeGuideHoldsOnThePrimaryPlayerWithoutABuiltinPad() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
bridge.setHomeGuidePressed(true)
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.setHomeGuidePressed(false)
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun homeGuideAndControllerGuideReleaseIndependentlyOnThePrimaryPlayer() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE))
bridge.setHomeGuidePressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP))
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE))
bridge.setHomeGuidePressed(false)
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP))
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun playerSlotHomeGuidePreservesRemappedInputAndTheEnableGate() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
routed(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Native(InputControl.B))
.withBinding(InputRole.PHYSICAL, InputControl.LS, InputAction.Native(InputControl.RS)))
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A))
motion(device, MotionEvent.AXIS_X, .6f)
bridge.setHomeGuidePressed(true)
val held = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertTrue(held.isDown(PadState.GUIDE))
assertTrue(held.isDown(PadState.B))
assertFalse(held.isDown(PadState.A))
assertEquals(0f, held.leftX)
assertEquals(.6f, held.rightX)
bridge.setInputEnabled(false)
val disabled = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertTrue(disabled.isDown(PadState.GUIDE))
assertFalse(disabled.isDown(PadState.A))
assertFalse(disabled.isDown(PadState.B))
assertEquals(0f, disabled.leftX)
assertEquals(0f, disabled.rightX)
bridge.cancelHomeGuide()
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun removingThePrimaryPlayerForgetsItsHomeGuide() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP))
bridge.setHomeGuidePressed(true)
bridge.onDeviceRemoved(device.id)
JoyConPadTest.RecordingWriter.pads.remove(1)
bridge.cancelHomeGuide()
bridge.setHomeGuidePressed(false)
assertNull(JoyConPadTest.RecordingWriter.pads[1])
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun cancellingHomeGuideOnAPlayerSlotKeepsItsHeldControls() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A))
bridge.setHomeGuidePressed(true)
bridge.cancelHomeGuide()
val pad = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertFalse(pad.isDown(PadState.GUIDE))
assertTrue(pad.isDown(PadState.A))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun cancellingHomeDiscardsQueuedPartnersAndReleasesGuideImmediately() {
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.press(PadState.LB, true); it.leftY = -1f }, true)
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28, 33])
class SteamVolumeKeysTest {
private val adjustments = mutableListOf<Int>()
private fun key(code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) =
KeyEvent(0L, 0L, action, code, repeat)
private fun dispatch(code: Int, enabled: Boolean = true, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) =
SteamVolumeKeys.dispatch(key(code, action, repeat), enabled, adjustments::add)
@Test fun enabledKeysAdjustOncePerDownAndConsumeRelease() {
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, repeat = 1))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, action = KeyEvent.ACTION_UP))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN, action = KeyEvent.ACTION_UP))
assertEquals(listOf(AudioManager.ADJUST_RAISE, AudioManager.ADJUST_RAISE, AudioManager.ADJUST_LOWER), adjustments)
}
@Test fun muteTogglesOnlyOnInitialPress() {
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, repeat = 1))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, action = KeyEvent.ACTION_UP))
assertEquals(listOf(AudioManager.ADJUST_TOGGLE_MUTE), adjustments)
}
@Test fun disabledAndNonVolumeKeysFallThrough() {
for (code in listOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) {
assertFalse(dispatch(code, enabled = false))
assertFalse(dispatch(code, enabled = false, action = KeyEvent.ACTION_UP))
}
assertFalse(dispatch(KeyEvent.KEYCODE_BUTTON_A))
assertTrue(adjustments.isEmpty())
}
}
@@ -66,6 +66,15 @@ class DeviceControlsComponentTest {
assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC))
}
@Test fun everyVolumeStepIsPublishedWithoutWaitingForThePoll() {
for (level in 2..5) {
audio.setStreamVolume(AudioManager.STREAM_MUSIC, level, 0)
context.sendBroadcast(android.content.Intent("android.media.VOLUME_CHANGED_ACTION"))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(level.toString(), File(directory, "volume.state").readText().split(" ").first())
}
}
@Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
@@ -4,6 +4,7 @@ import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -12,6 +13,8 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -21,10 +24,137 @@ class GameEnvironmentStoreTest {
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
File(context.filesDir, "game-environment.json").delete()
}
@After fun tearDown() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
}
@Test fun gameDebugLogsAreOffByDefault() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsRequireSessionLogsAndPreserveCustomDiagnostics() {
val config = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "0", "WINEDEBUG" to "+warn"))
GameEnvironmentStore.save(context, config)
SessionPrefs.setGameDebugLogsEnabled(context, true)
var published = JSONObject(guest.readText())
assertTrue(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals("0", published.getJSONObject("shared").getString("PROTON_LOG"))
assertEquals("+warn", published.getJSONObject("shared").getString("WINEDEBUG"))
assertEquals(config, GameEnvironmentStore.read(context))
SessionPrefs.setLogsEnabled(context, false)
published = JSONObject(guest.readText())
assertFalse(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
SessionPrefs.setLogsEnabled(context, true)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun failedGameDebugOptOutLeavesTheEnabledPreferenceVisible() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(context, true))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertFalse(SessionPrefs.setGameDebugLogsEnabled(context, false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
GameEnvironmentStore.publish(context)
}
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun unchangedEffectiveDiagnosticsDoNotRequireGuestPublication() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertTrue(SessionPrefs.setLogsEnabled(context, false))
assertFalse(SessionPrefs.logsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
SessionPrefs.setLogsEnabled(context, true)
GameEnvironmentStore.publish(context)
}
}
@Test fun logPreferenceUpdatesUseThePublisherLock() {
GameEnvironmentStore.publish(context)
val entered = CountDownLatch(1)
val finished = CountDownLatch(1)
lateinit var thread: Thread
synchronized(GameEnvironmentStore) {
thread = Thread {
entered.countDown()
SessionPrefs.setGameDebugLogsEnabled(context, true)
finished.countDown()
}
thread.start()
assertTrue(entered.await(5, TimeUnit.SECONDS))
assertFalse(finished.await(100, TimeUnit.MILLISECONDS))
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
assertTrue(finished.await(5, TimeUnit.SECONDS))
thread.join()
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsWaitForARetainedSessionFolder() {
assertNull(SessionPaths.current())
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
SessionPrefs.setLogsEnabled(context, false)
val cacheSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
try {
assertFalse(SessionPaths.currentSessionLogsRetained(context))
SessionPrefs.setLogsEnabled(context, true)
SessionPrefs.setGameDebugLogsEnabled(context, true)
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(cacheSession, SessionPaths.take())
SessionPaths.release(context, cacheSession)
val retainedSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(retainedSession, SessionPaths.current())
} finally {
SessionPaths.take()?.let { ended ->
SessionPaths.release(context, ended)
ended.deleteRecursively()
}
}
}
@Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() {
val config = GameEnvironment.Config(
shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""),
@@ -115,6 +115,22 @@ class RumbleComponentTest {
assertFalse(pad.vibrating)
}
@Test fun quietingStopsAHeldEffectAndDropsEffectsUntilLifted() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS)
rumble.quiet(true)
assertFalse(pad.vibrating)
idle(RumbleComponent.KEEPALIVE_MS * 4 + 100)
assertEquals("the keepalive restarted the motors while quiet", 1, pad.played.size)
effect(strong = 40000, weak = 20000)
assertFalse("an effect played while quiet", pad.vibrating)
rumble.quiet(false)
effect(strong = 40000, weak = 20000)
assertTrue(pad.vibrating)
}
@Test fun aHeldEffectFollowsTheGamesNewStrength() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.session
import android.app.Application
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.GpuInfo
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(
sdk = [33], application = Application::class, qualifiers = "en-rUS",
instrumentedPackages = ["com.droiddeck.launcher.gpu.GpuInfo"],
shadows = [SessionEndHintTest.DetectedGpu::class],
)
class SessionEndHintTest {
@get:Rule val temporary = TemporaryFolder()
private lateinit var activity: SessionActivity
private var previousArchitecture: String? = null
@Before
fun setUp() {
previousArchitecture = SessionState.steamClientArch
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
SessionState.steamClientArch = "arm64"
}
@After
fun tearDown() {
SessionState.steamClientArch = previousArchitecture
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
}
@Test
fun sigillOnArm64IncludesTheExperimentalX64Fallback() {
SessionState.steamClientArch = "arm64"
assertEquals(
activity.getString(R.string.session_end_steam_sigill) + "\n" + activity.getString(R.string.session_end_steam_try_x64),
hintText(sigillLog()),
)
}
@Test
fun sigillOnX86_64DoesNotSuggestSwitchingToItself() {
SessionState.steamClientArch = "x86_64"
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun sigillWithUnknownArchitectureDoesNotAssumeArm64() {
SessionState.steamClientArch = null
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun vulkanFailureOnAdrenoSelectsTheDriverHint() {
for (family in listOf(GpuInfo.Family.A6XX, GpuInfo.Family.ADRENO_UNKNOWN)) {
DetectedGpu.family = family
assertEquals(family.name, activity.getString(R.string.session_end_vulkan_device), hintText(vulkanLog()))
}
}
@Test
fun vulkanFailureOnNonAdrenoExplainsTheMissingLinuxDriver() {
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
assertEquals(activity.getString(R.string.session_end_gpu_unsupported), hintText(vulkanLog()))
}
@Test
fun missingEmptyAndUnrelatedLogsHaveNoHint() {
assertNull(hint(null))
assertNull(hint(File(temporary.root, "missing.log")))
assertNull(hint(log("")))
assertNull(hint(log("game: Illegal instruction\n== steam exited rc=132")))
}
private fun sigillLog() = log("== STEP 12:00:00 starting the Steam client\n== steam exited rc=132\n")
private fun vulkanLog() = log("[gamescope] [Error] vulkan: failed to find physical device\n")
private fun log(text: String): File = temporary.newFile().apply { writeText(text) }
private fun hint(log: File?): Any? = SessionActivity::class.java
.getDeclaredMethod("sessionEndHint", File::class.java).apply { isAccessible = true }.invoke(activity, log)
private fun hintText(log: File): String {
val result = hint(log)
assertNotNull(result)
return ReflectionHelpers.getField(result, "text")
}
@Implements(value = GpuInfo.Companion::class, isInAndroidSdk = false)
class DetectedGpu {
@Implementation
fun detect(): GpuInfo = GpuInfo("test GPU", if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false)
companion object {
var family = GpuInfo.Family.NOT_ADRENO
}
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SessionLaunchFailureTest {
private fun find(vararg lines: String) = SessionLaunchFailure.find(lines.asSequence())
@Test fun installedSteamThatExitsWithSigillHasACpuFailureHint() {
assertEquals(SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION, find(
"== STEP 06:35:36.987 Steam client ready",
"== STEP 06:35:41.058 starting the Steam client",
"/usr/local/bin/droiddeck-session: line 309: 1192 Illegal instruction steam",
"== steam exited rc=132",
"(EE) failed to read Wayland events: Broken pipe",
))
}
@Test fun gamescopeWithoutAPhysicalDeviceHasAGraphicsFailureHint() {
assertEquals(SessionLaunchFailure.VULKAN_DEVICE_MISSING, find(
"[gamescope] [\u001b[0;31mError\u001b[0m] \u001b[0;37mvulkan:\u001b[0m failed to find physical device",
"SDL_Vulkan_CreateSurface failed: VK_KHR_wayland_surface extension is not enabled in the Vulkan instance.Failed to create backend.",
))
}
@Test fun unrelatedIllegalInstructionsAndExitCodesAreNotBlamedOnSteam() {
assertNull(find("game: Illegal instruction", "== steam exited rc=132"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=139"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=1320"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=0"))
}
@Test fun onlyTheLatestClientAttemptCounts() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== STEP 12:01:00 starting the Steam client", "== steam exited rc=0",
))
}
@Test fun aLaterSuccessfulDeviceSelectionClearsTheGraphicsFailure() {
assertNull(find(
"[gamescope] [Error] vulkan: failed to find physical device",
"[gamescope] [Info] vulkan: selecting physical device 'Turnip Adreno (TM) 610': queue family 0",
))
}
@Test fun aNewSessionDoesNotReuseAnOldFailure() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== droiddeck-session Fri Oct 23 12:01:00 mode=steam",
))
}
}
@@ -1,8 +1,10 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -12,6 +14,9 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@@ -147,6 +152,41 @@ class SessionLogShareTest {
assertTrue(zip(folder).values.none { it.contains(leaked) })
}
@Test fun aDirectoryListingFailureLeavesTheTreeUnrecordedButDoesNotStopSiblingScrubbing() {
val folder = tmp.newFolder("2026-10-06-06-listing")
val unavailable = File(folder, "unavailable").apply { mkdirs() }
val unavailableLog = File(unavailable, "session.log").apply { writeText("$secret\n") }
val availableLog = File(folder, "available/session.log").apply {
parentFile!!.mkdirs()
writeText("$secret\n")
}
assertFalse(SessionArtifacts.scrubAndMark(folder, listFiles = {
if (it == unavailable) null else it.listFiles()
}))
assertTrue(unavailableLog.readText().contains(leaked))
assertFalse(availableLog.readText().contains(leaked))
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun aFailedScrubStillRecordsTheCollectionEventWithoutCompletingTheFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = tmp.newFolder("2026-10-06-06-collect")
File(folder, "wayland.log").writeText("test compositor log\n")
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply {
mkdirs()
resolve("blocker").writeText("force marker write failure\n")
}
SessionArtifacts.collect(context, folder, "test")
assertTrue(File(folder, "events.jsonl").readText().contains("session.artifacts_collected"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
}
@Test fun steamLogsPastTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
@@ -160,4 +200,322 @@ class SessionLogShareTest {
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
}
@Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() {
val folder = tmp.newFolder("2026-10-06-08-steam")
val unchanged = File(folder, "unchanged.log")
unchanged.bufferedWriter().use { out -> repeat(5000) { out.write("safe diagnostic $it\n") } }
val originalModified = 1_600_000_000_000L
assertTrue(unchanged.setLastModified(originalModified))
val changed = File(folder, "changed.log")
changed.bufferedWriter().use { out ->
repeat(5000) { out.write("safe diagnostic $it\n") }
out.write("$secret\n")
}
assertTrue(SessionArtifacts.scrubAndMark(folder))
assertEquals(originalModified, unchanged.lastModified())
assertFalse(changed.readText().contains(leaked))
assertTrue(changed.readText().contains("sessionid=<redacted:token>"))
}
@Test fun historicalScrubDefersWithoutLeavingMarkersAndResumes() {
val folder = tmp.newFolder("2026-10-06-09-steam")
val log = File(folder, "session.log").apply { writeText("$secret\n") }
val rulesMarker = File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").apply { writeText("stale\n") }
val treeMarker = File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply { writeText("rules ${LogRedactor.RULES_VERSION}\n") }
SessionState.running = true
try {
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
} finally {
SessionState.running = false
}
assertFalse(rulesMarker.exists())
assertFalse(treeMarker.exists())
assertTrue(log.readText().contains(leaked))
assertTrue(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
assertFalse(log.readText().contains(leaked))
assertTrue(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").isFile)
}
@Test fun historicalScrubCancellationDuringStreamingPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-10-steam")
val original = "first safe line\n" + "x".repeat(20_000) + " $secret\n"
val log = File(folder, "session.log").apply { writeText(original) }
var checks = 0
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { ++checks >= 4 })
assertEquals(original, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubCancellationBeforeComparisonPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-11-steam")
val original = "safe diagnostic\n"
val log = File(folder, "session.log").apply { writeText(original) }
val temporary = File(folder, ".session.log.scrub")
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { temporary.length() > 0 })
assertEquals(original, log.readText())
assertFalse(temporary.exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubDoesNotReplaceALogThatChangedBeforeCommit() {
val folder = tmp.newFolder("2026-10-06-12-steam")
val original = "sessionid=$leaked\n"
val appended = "writer finished after collection started\n"
val log = File(folder, "session.log").apply { writeText(original) }
assertFalse(SessionArtifacts.scrubAndMark(folder, beforeReplace = { it.appendText(appended) }))
assertEquals(original + appended, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun comparisonCancellationWinsOverAnImmediateLengthMismatch() {
val left = tmp.newFile("left.log").apply { writeText("short\n") }
val right = tmp.newFile("right.log").apply { writeText("a different length\n") }
assertNull(SessionArtifacts.sameContents(left, right) { true })
}
@Test fun recoveryRetryKeepsItsSteamLogsWhenALaterSessionLeftNoFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2026-10-08-01-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(folder, "ended-without-teardown.txt").writeText("recovery attempted before session B\n")
val runtime = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertEquals("session B\n", runtime.readText())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun abandonedRecoveryDoesNotCopyLogsFromANewerCompletedSession() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val folder = File(logs, "2026-10-08-02-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(logs, "2026-10-08-03-steam").apply { mkdirs() }
.resolve(SessionArtifacts.COMPLETE_MARKER).writeText("finished session B\n")
File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun startupRecoveryRunsBeforeVacMarkerArmWhileOrdinaryCleanupDefers() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2999-12-31-99-startup-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/startup-recovery-vac.log")
val sessionLog = File(folder, "session.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
sessionLog.writeText("$secret\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("startup VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("startup VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionArtifacts.finishAbandoned(context)
assertFalse(File(folder, "ended-without-teardown.txt").exists())
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("startup VAC evidence\n", File(folder, "steam/startup-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("startup VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertTrue(crashLog.isFile && crashLog.length() > 0L)
assertTrue(sessionLog.readText().contains(leaked))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertFalse(sessionLog.readText().contains(leaked))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun startupRecoveryExcludesCurrentFolderAndCapturesDeferredRuntime() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val olderFolder = File(logs, "$day-8999-older-recovery")
val folder = File(logs, "$day-9000-deferred-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/deferred-recovery-vac.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
val previousLogsEnabled = SessionPrefs.logsEnabled(context)
var currentFolder: File? = null
try {
olderFolder.deleteRecursively()
olderFolder.mkdirs()
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("deferred VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("deferred VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionPrefs.setLogsEnabled(context, true)
currentFolder = SessionPaths.beginOrCurrent(context, "current-session")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("deferred VAC evidence\n", File(folder, "steam/deferred-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("deferred VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(olderFolder, "ended-without-teardown.txt").exists())
assertFalse(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(currentFolder, "ended-without-teardown.txt").exists())
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertTrue(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
SessionPaths.take()?.let { SessionPaths.release(context, it) }
currentFolder?.deleteRecursively()
SessionPrefs.setLogsEnabled(context, previousLogsEnabled)
olderFolder.deleteRecursively()
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun failedPreGuestRuntimeCaptureWritesNeitherCaptureNorCompleteMarker() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-01-vac-failure")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/expired-recovery.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
val firstCrashSnapshot = "first crash snapshot\n".toByteArray()
crashLog.writeBytes(firstCrashSnapshot)
File(folder, "vac.txt").mkdirs()
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("VAC evidence that cannot be reported\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("session A\n") }
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertFalse(File(folder, ".recovery-runtime-captured").exists())
assertTrue(File(folder, ".recovery-runtime-expired").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
File(folder, "vac.txt").deleteRecursively()
runtimeSteamLog.writeText("session B\n")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("session A\n", File(folder, "steam/expired-recovery.log").readText())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun emptyCrashSnapshotIsPreservedAcrossRecovery() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-02-empty-crash")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
crashLog.writeBytes(ByteArray(0))
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
}
}
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -20,6 +21,49 @@ import org.robolectric.annotation.Config
class SessionLogShareZipTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun aLargeSteamLogIsRedactedInTheSharedArchive() {
val session = File(LinuxRuntime.logDir(app), "2026-10-08-02-steam").apply { mkdirs() }
val raw = File(session, "steam-42.log")
val earlySecret = "early-sessionid-abcdef123456"
val trailingSecret = "late-refresh-token-abcdef123456"
try {
// One long line exercises the streaming limit; the final ordinary line must still be redacted.
raw.bufferedWriter().use { out ->
out.write("sessionid=$earlySecret")
val chunk = "x".repeat(8192)
repeat(8192) { out.write(chunk) }
out.write("\nrefresh_token=$trailingSecret\n")
}
assertTrue(raw.length() > 64L * 1024 * 1024)
val zip = SessionLogShare.zipFolder(app, session)!!
ZipFile(zip).use { archive ->
val entry = archive.getEntry("${session.name}/steam-42.log")!!
archive.getInputStream(entry).use { input ->
// Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB.
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
var offset = 0
while (offset < prefix.size) {
val count = input.read(prefix, offset, prefix.size - offset)
assertTrue("zip entry ended before its scrubbed prefix", count > 0)
offset += count
}
assertEquals(expected, String(prefix, StandardCharsets.UTF_8))
input.bufferedReader().use { reader ->
val trailing = requireNotNull(reader.readLine())
assertFalse("trailing secret survived", trailing.contains(trailingSecret))
assertEquals("refresh_token=<redacted:token>", trailing)
assertEquals(null, reader.readLine())
}
}
}
} finally {
SessionLogShare.clear(app)
session.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
@@ -2,10 +2,13 @@ package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.IOException
import java.io.Writer
class SessionSteamLogsTest {
@get:Rule val tmp = TemporaryFolder()
@@ -59,4 +62,37 @@ class SessionSteamLogsTest {
assertEquals(listOf("web.txt"), names(copied))
assertFalse(File(out, "web.txt").readText().contains("abcdef123456"))
}
@Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() {
val logs = tmp.newFolder("logs")
val session = tmp.newFolder("session")
val out = tmp.newFolder("out")
File(logs, "console_log.txt").writeText("new complete line\n")
val snapshot = File(out, "console_log.txt").apply { writeText("previous valid snapshot\n") }
lateinit var staging: File
val copied = SessionArtifacts.copySessionLogs(logs, session, out) { target ->
staging = target
val delegate = target.bufferedWriter()
object : Writer() {
private var failed = false
override fun write(buffer: CharArray, offset: Int, length: Int) {
if (!failed) {
delegate.write(buffer, offset, minOf(length, 4))
delegate.flush()
failed = true
}
throw IOException("injected writer failure")
}
override fun flush() = delegate.flush()
override fun close() = delegate.close()
}
}
assertTrue(copied.isEmpty())
assertEquals("previous valid snapshot\n", snapshot.readText())
assertFalse(staging.exists())
}
}
@@ -40,6 +40,7 @@ class SettingsResetTest {
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
@@ -60,6 +61,10 @@ class SettingsResetTest {
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertFalse(SessionPrefs.gameDebugLogsEnabled(app))
val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck/game-environment.json")
assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.hudShowFps(app))
assertTrue(SessionPrefs.hudShowBattery(app))
assertTrue(SessionPrefs.hudShowGraph(app))
@@ -73,6 +78,22 @@ class SettingsResetTest {
assertFalse(prefs("steam_touch").contains("gyro"))
}
@Test fun aFailedDebugOptOutDoesNotHideTheEnabledPreference() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
val directory = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck")
directory.deleteRecursively()
directory.writeText("blocks configuration publication")
try {
assertFalse(SettingsReset.resetAll(app, gameProfiles = false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(app))
} finally {
directory.delete()
directory.mkdirs()
GameEnvironmentStore.publish(app)
}
}
@Test fun libraryAndRecordsAreKept() {
val folder = "/storage/emulated/0/Games/Foo"
SessionPrefs.setAddedGameName(app, folder, "Foo")
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.stores
import android.app.Application
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
@@ -18,7 +19,7 @@ import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
@Config(sdk = [33], application = Application::class)
class StoreAccountsCipherTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES")
@@ -144,7 +144,7 @@ class GlobalGlassesSettingsTest {
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {})
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {})
}
}
}
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.update.AppUpdates.Offer
import com.droiddeck.launcher.update.AppUpdates.PreviewChange
import com.droiddeck.launcher.update.AppUpdates.PreviewHistoryKind
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.json.JSONArray
@@ -285,4 +286,69 @@ class AppUpdatesTest {
} catch (_: IOException) {
}
}
@Test fun anOlderStableIsGuessedStableAndSaved() {
val g = AppUpdates.guessFollow(catalog, me("eeeeeee999", version = "0.1.9"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun anOlderBuildInPreviewHistoryKeepsStableAsAnUncertainGuess() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.1.0"))
assertEquals(Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anOlderCataloguedBuildDoesNotPersistAGuessAndExplicitChoicesStillWin() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val preferences = context.getSharedPreferences("app_updates", android.content.Context.MODE_PRIVATE)
preferences.edit().clear().commit()
try {
val installed = me("2".repeat(40), version = "0.1.0")
val newerStable = release("0".repeat(40), version = "9999.0.0")
val currentPreview = release(installed.commit)
val newerCatalog = AppUpdates.Catalog(newerStable, currentPreview, emptyList(), 0L)
assertEquals(Channel.STABLE, AppUpdates.follow(context, newerCatalog, installed).channel)
assertNull(preferences.getString("channel", null))
assertEquals(Channel.STABLE, AppUpdates.follow(context, null, installed).channel)
assertNull(preferences.getString("channel", null))
for (choice in listOf(Follow(Channel.STABLE), Follow(Channel.NIGHTLY), Follow(Channel.TEST, 93))) {
AppUpdates.setFollow(context, choice)
val actual = AppUpdates.follow(context, newerCatalog, installed)
assertEquals(choice.channel, actual.channel)
assertEquals(choice.pr, actual.pr)
}
} finally {
preferences.edit().clear().commit()
}
}
@Test fun runningTheCatalogStableIsCertainStable() {
val g = AppUpdates.guessFollow(catalog, me(stable.commit))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun aPublishedPreviewPastStableIsGuessedNightlyWithoutSaving() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.NIGHTLY, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anUncataloguedNewerBuildStaysStableForNow() {
val g = AppUpdates.guessFollow(catalog, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
val offline = AppUpdates.guessFollow(null, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, offline.follow.channel)
assertFalse(offline.certain)
}
@Test fun aPullRequestBuildIsCertainTest() {
val g = AppUpdates.guessFollow(catalog, me("ccccccc2222222222222222222222222222222", pr = 93))
assertEquals(AppUpdates.Channel.TEST, g.follow.channel)
assertTrue(g.certain)
}
}