fix: harden native store handoffs

This commit is contained in:
Kurt Himebauch committed 2026-10-28 19:04:31 -04:00
1 parent ab7390e844
commit 090b87c37c
16 files changed
+161 -68

No files matched your search

@@ -1039,21 +1039,7 @@ class FrontEndActivity : ComponentActivity() {
if (!com.droiddeck.launcher.session.SteamSessionUrl.isSupported(url)) {
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
} else if (!SessionState.running) {
if (!startSession(Intent(this, SessionActivity::class.java), steamSession = true)) {
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
} else {
val context = applicationContext
Thread({
val opened = runCatching {
com.droiddeck.launcher.agent.AgentGuest.awaitAndOpenSteamUrl(context, url)
}.isSuccess
if (!opened) ui.post {
if (!isDestroyed) android.widget.Toast.makeText(
this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
}, "steam-navigation-start").start()
}
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
} else if (SessionState.mode != SessionService.MODE_STEAM) {
android.widget.Toast.makeText(this, R.string.steam_navigation_switch_mode, android.widget.Toast.LENGTH_LONG).show()
} else if (SessionState.stopRequested) {
@@ -1061,14 +1047,21 @@ class FrontEndActivity : ComponentActivity() {
} else {
if (SessionState.suspended) SessionService.resume(this)
val context = applicationContext
val sessionId = SessionState.sessionId
Thread({
val opened = runCatching {
com.droiddeck.launcher.agent.AgentGuest.openSteamUrl(context, url)
}.isSuccess
ui.post {
if (opened) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
val canResume = com.droiddeck.launcher.session.SteamSessionUrl.canResume(
sessionId, SessionState.sessionId, SessionState.running,
SessionState.stopRequested, isDestroyed,
)
if (opened && canResume) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
else if (!opened && !isDestroyed) android.widget.Toast.makeText(
this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
}, "steam-navigation").start()
}
@@ -1082,7 +1075,11 @@ class FrontEndActivity : ComponentActivity() {
if (shortcutPicker) chooseGameShortcut(g)
else {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g, onBlocked = {
android.widget.Toast.makeText(
this, R.string.store_maintenance_launch_blocked, android.widget.Toast.LENGTH_LONG,
).show()
}) { launchGame(g) }
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -108,22 +108,6 @@ object AgentGuest {
return result
}
fun awaitAndOpenSteamUrl(context: Context, url: String, timeoutMs: Long = STEAM_START_URL_TIMEOUT_MS): JSONObject {
require(SteamSessionUrl.isSupported(url)) { "Unsupported Steam navigation URL" }
val deadline = android.os.SystemClock.elapsedRealtime() + timeoutMs
while (android.os.SystemClock.elapsedRealtime() < deadline) {
check(SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested) {
"The Steam session ended before its UI became ready"
}
if (hello(context) != null) {
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
return openSteamUrl(context, url, minOf(STEAM_URL_TIMEOUT_MS, remaining))
}
Thread.sleep(POLL_MS)
}
throw AgentException("AGENT_UNAVAILABLE", "The Steam guest agent did not become ready")
}
fun selectedSteamAppId(context: Context): Long? {
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
if (!result.optBoolean("ok") || result.isNull("appId")) return null
@@ -224,5 +208,4 @@ object AgentGuest {
}
private const val STEAM_URL_TIMEOUT_MS = 125_000L
private const val STEAM_START_URL_TIMEOUT_MS = 180_000L
}
@@ -2,8 +2,22 @@ package com.droiddeck.launcher.session
object SteamSessionUrl {
private val allowed = Regex("steam://(?:open/downloads|uninstall/[1-9][0-9]{0,9})")
private const val MAX_STEAM_APP_ID = 4_294_967_295L
fun isSupported(url: String): Boolean = allowed.matches(url)
fun isSupported(url: String): Boolean {
if (!allowed.matches(url)) return false
val appId = url.removePrefix("steam://uninstall/").takeIf { it != url }?.toLongOrNull()
return appId == null || appId <= MAX_STEAM_APP_ID
}
internal fun wasOpened(ok: Boolean, launched: Boolean): Boolean = ok && launched
internal fun canResume(
expectedSessionId: String?,
currentSessionId: String?,
running: Boolean,
stopping: Boolean,
activityDestroyed: Boolean,
): Boolean = expectedSessionId != null && expectedSessionId == currentSessionId &&
running && !stopping && !activityDestroyed
}
@@ -93,7 +93,7 @@ object StoreLaunch {
}
}
fun prepare(context: Context, store: Store, id: String, onReady: () -> Unit) {
fun prepare(context: Context, store: Store, id: String, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
val selected = try {
@@ -105,6 +105,7 @@ object StoreLaunch {
if (selected != null && com.droiddeck.launcher.stores.maintenance.StoreMaintenance.launchExcluded(
InstalledStoreGame(selected.second, selected.first))) {
Log.i(TAG, "launch blocked while ${store.label} maintenance is active: $id")
StoresState.post(onBlocked)
return@Thread
}
if (store == Store.EPIC) epicCode(app, id)
@@ -146,11 +147,11 @@ object StoreLaunch {
return result
}
fun prepare(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
fun prepare(context: Context, game: Library.SteamGame, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
val store = Store.byId(game.source)
val id = game.storeId
if (store == null || id == null) { StoresState.post(onReady); return }
prepare(context, store, id, onReady)
prepare(context, store, id, onBlocked = onBlocked, onReady = onReady)
}
}
@@ -366,7 +366,7 @@ internal fun GameActions(
if (store == Store.ITCH && installed != null && StoreMaintenance.adapter(installed) == null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store != Store.GOG && installed != null && StoreMaintenance.adapter(installed) != null) StoreMaintenanceActions(installed)
if (store == null && game != null && game.source == Library.SOURCE_STEAM && game.appId > 0) SteamClientMaintenanceActions(a)
if (store == null && game != null && game.source == Library.SOURCE_STEAM && game.appId > 0) SteamClientMaintenanceActions(a, s.sessionRunning)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
if (StoreMaintenance.adapter(installed) == null) SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
@@ -36,10 +36,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun SteamClientMaintenanceActions(actions: FrontEndActions) {
internal fun SteamClientMaintenanceActions(actions: FrontEndActions, sessionRunning: Boolean) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton("Open Steam downloads") { actions.onSteamUrl("steam://open/downloads") }
if (sessionRunning) SecondaryButton("Open Steam downloads", modifier = Modifier.testTag("steam-downloads")) {
actions.onSteamUrl("steam://open/downloads")
} else SecondaryButton("Start Steam", modifier = Modifier.testTag("steam-start")) { actions.onPlay() }
}
Text("In Steam, open this game’s Properties → Installed Files → Verify integrity.",
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -129,7 +131,12 @@ internal fun StoreMaintenanceActions(game: InstalledStoreGame) {
MaintenanceCheckState.CHECKING -> Text("Checking for updates…", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
MaintenanceCheckState.CURRENT -> Text("Up to date", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
MaintenanceCheckState.AVAILABLE -> if (MaintenanceAction.UPDATE !in capabilities) {
Text("An update is available. Use ${adapter.openClientLabel(game)} to apply it.",
val message = if (MaintenanceAction.OPEN_CLIENT in capabilities) {
"An update is available. Use ${adapter.openClientLabel(game)} to apply it."
} else {
"An update is available."
}
Text(message,
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
MaintenanceCheckState.UNKNOWN, MaintenanceCheckState.FAILED -> if (current.reason.isNotBlank())
@@ -1256,6 +1256,7 @@
<string name="game_link_invalid">Enlace de inicio de juego no válido.</string>
<string name="game_link_missing">Este juego ya no está en tu biblioteca de DroidDeck.</string>
<string name="game_link_session_busy">Detén la sesión actual antes de iniciar un juego de Steam.</string>
<string name="store_maintenance_launch_blocked">El mantenimiento está en curso. Termínalo antes de iniciar este juego.</string>
<string name="game_link_failed">No se pudo enviar el juego a Steam. Intenta iniciarlo de nuevo.</string>
<string name="setup_retry_removal">Reintentar eliminación</string>
<string name="runtime_removing">Eliminando</string>
+1
View File
@@ -1201,6 +1201,7 @@
<string name="game_link_invalid">Enlace de inicio de juego no válido.</string>
<string name="game_link_missing">Este juego ya no está en tu biblioteca de DroidDeck.</string>
<string name="game_link_session_busy">Detén la sesión actual antes de iniciar un juego de Steam.</string>
<string name="store_maintenance_launch_blocked">Hay una tarea de mantenimiento en curso. Termínala antes de iniciar este juego.</string>
<string name="game_link_failed">No se pudo enviar el juego a Steam. Intenta iniciarlo de nuevo.</string>
<string name="setup_retry_removal">Reintentar eliminación</string>
<string name="runtime_removing">Eliminando</string>
+1
View File
@@ -7,6 +7,7 @@
<string name="gog_refresh">Download full offline installer</string>
<string name="gog_update">Update to %1$s</string>
<string name="gog_resume">Resume GOG maintenance</string>
<string name="store_maintenance_launch_blocked">Maintenance is running. Finish it before launching this game.</string>
<string name="gog_open_patch">Open patch installer</string>
<string name="gog_patch_in_session">Finish or cancel the patch installer in the Linux session.</string>
<string name="gog_patch_requirements">Choose a patch for your installed version and language. Supported source versions may not be listed.</string>
@@ -173,12 +173,17 @@ where
let mut rebuilt: HashMap<u32, Rebuilt> = HashMap::new();
let mut reserved = 0u64;
let budget = budget.min(MAX_REBUILD_MEMORY);
let wanted = needed
.iter()
.filter(|index| !cached.contains(index) && target.chunks.get(**index as usize).is_some())
.count();
for file in &installed.files {
if cancel.load(Ordering::Relaxed) {
break;
}
if !rebuilt.is_empty()
&& rebuilt.values().all(|chunk| !chunk.valid || chunk.uncovered == 0)
&& (reserved >= budget || rebuilt.len() >= wanted)
{
break;
}
@@ -458,7 +463,8 @@ mod tests {
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&game).unwrap();
let needed_chunk = chunk(51, 4);
let unrelated_chunk = chunk(52, 4);
let second_needed_chunk = chunk(52, 4);
let unrelated_chunk = chunk(53, 4);
let installed_bytes = build(&TestManifest {
version: 21,
build: "installed".into(),
@@ -478,6 +484,12 @@ mod tests {
tags: Vec::new(),
parts: vec![PartRef { guid: unrelated_chunk.guid, offset: 0, size: 4 }],
},
TestFile {
path: "second-source.bin".into(),
sha1: Sha1::digest(b"efgh").into(),
tags: Vec::new(),
parts: vec![PartRef { guid: second_needed_chunk.guid, offset: 0, size: 4 }],
},
],
compress: false,
meta_tail: Vec::new(),
@@ -487,13 +499,21 @@ mod tests {
build: "target".into(),
exe: "Game.exe".into(),
prereq: None,
chunks: vec![needed_chunk.clone()],
files: vec![TestFile {
path: "source.bin".into(),
sha1: Sha1::digest(b"abcd").into(),
tags: Vec::new(),
parts: vec![PartRef { guid: needed_chunk.guid, offset: 0, size: 4 }],
}],
chunks: vec![needed_chunk.clone(), second_needed_chunk.clone()],
files: vec![
TestFile {
path: "source.bin".into(),
sha1: Sha1::digest(b"abcd").into(),
tags: Vec::new(),
parts: vec![PartRef { guid: needed_chunk.guid, offset: 0, size: 4 }],
},
TestFile {
path: "second-source.bin".into(),
sha1: Sha1::digest(b"efgh").into(),
tags: Vec::new(),
parts: vec![PartRef { guid: second_needed_chunk.guid, offset: 0, size: 4 }],
},
],
compress: false,
meta_tail: Vec::new(),
});
@@ -501,6 +521,7 @@ mod tests {
let target = crate::epic::manifest::parse(&target_bytes).unwrap();
fs::write(game.join("source.bin"), b"abcd").unwrap();
fs::write(game.join("irrelevant.bin"), b"wxyz").unwrap();
fs::write(game.join("second-source.bin"), b"efgh").unwrap();
let checked = std::cell::RefCell::new(Vec::new());
let cancel = AtomicBool::new(false);
let (seeded, written) = seed_from_verified_installed_with_check(
@@ -508,18 +529,26 @@ mod tests {
&game,
&installed,
&target,
&HashSet::from([0]),
&HashSet::from([0, 1]),
&[],
4,
8,
&cancel,
|path, size, sha1, cancel| {
checked.borrow_mut().push(path.file_name().unwrap().to_owned());
super::super::delta::check(path, size, sha1, cancel)
},
);
assert_eq!(seeded, vec![0]);
assert_eq!(written, 4);
assert_eq!(*checked.borrow(), vec![std::ffi::OsString::from("source.bin")]);
assert_eq!(seeded.len(), 2);
assert!(seeded.contains(&0));
assert!(seeded.contains(&1));
assert_eq!(written, 8);
assert_eq!(
*checked.borrow(),
vec![
std::ffi::OsString::from("source.bin"),
std::ffi::OsString::from("second-source.bin"),
]
);
let _ = fs::remove_dir_all(&root);
}
}
@@ -7,10 +7,10 @@ import org.junit.Test
class SteamSessionUrlTest {
@Test
fun onlySupportedSteamNavigationRoutesAreAccepted() {
listOf("steam://open/downloads", "steam://uninstall/12345")
listOf("steam://open/downloads", "steam://uninstall/12345", "steam://uninstall/4294967295")
.forEach { assertTrue(it, SteamSessionUrl.isSupported(it)) }
listOf("steam://open/settings", "steam://nav/library", "steam://uninstall/0", "steam://uninstall/01",
"steam://open/downloads\n--exec", "https://example.com")
"steam://uninstall/4294967296", "steam://open/downloads\n--exec", "https://example.com")
.forEach { assertFalse(it, SteamSessionUrl.isSupported(it)) }
}
@@ -20,4 +20,15 @@ class SteamSessionUrlTest {
assertFalse(SteamSessionUrl.wasOpened(ok = false, launched = true))
assertFalse(SteamSessionUrl.wasOpened(ok = true, launched = false))
}
@Test
fun resumeTargetsOnlyTheSameLiveSessionAndActivity() {
assertTrue(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = false, activityDestroyed = false))
assertFalse(SteamSessionUrl.canResume("session-a", "session-b", running = true, stopping = false, activityDestroyed = false))
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = false, stopping = false, activityDestroyed = false))
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = true, activityDestroyed = false))
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = false, activityDestroyed = true))
assertFalse(SteamSessionUrl.canResume(null, null, running = true, stopping = false, activityDestroyed = false))
}
}
@@ -10,6 +10,7 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.json.JSONObject
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -61,6 +62,31 @@ class StoreLaunchTest {
assertNull(StoreLaunch.installedGame(app, Store.XBOX, "9NHFVWX1V7QJ"))
}
@Test fun maintenanceBlockedLaunchReportsTheBlockWithoutLaunching() {
val folder = install()
val operation = com.droiddeck.launcher.stores.maintenance.StoreMaintenance.operationFile(folder)
operation.parentFile!!.mkdirs()
operation.writeText(JSONObject().put("schema", 1).put("folder", folder.canonicalPath).put("phase", "applying").toString())
val blocked = CountDownLatch(1)
val ready = AtomicBoolean(false)
try {
StoreLaunch.prepare(app, Store.XBOX, "9NHFVWX1V7QJ", onBlocked = { blocked.countDown() }) {
ready.set(true)
}
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (blocked.count > 0 && System.nanoTime() < deadline) {
org.robolectric.shadows.ShadowLooper.idleMainLooper()
Thread.sleep(10)
}
assertTrue("the blocked callback was not posted", blocked.await(1, TimeUnit.SECONDS))
assertFalse("an excluded install must not reach the launch callback", ready.get())
} finally {
operation.parentFile?.deleteRecursively()
}
}
@Test fun installedTargetWinsOverAnEarlierUpdatingDuplicate() {
val updating = install(StoreGameSidecar.STATE_UPDATING)
val installed = File(updating.parentFile, "ZZZ installed copy")