From eedeaa6bf7f16f24ef65fa0554e89bd4a3325b9e Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 5 Nov 2026 15:34:10 +0100 Subject: [PATCH 01/14] fix(ADFA-5438): Return session ids and failure reasons when installing apk --- .../itsaky/androidide/utils/ApkInstaller.kt | 140 ++++++++++++++++-- .../utils/InstallationResultHandler.kt | 4 +- ...allationResultHandlerSuppressLaunchTest.kt | 2 + 3 files changed, 131 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 97f7466740..3ca3a38d4d 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -40,6 +40,28 @@ object ApkInstaller { */ const val EXTRA_SUPPRESS_POST_INSTALL_LAUNCH = "ide.installer.suppressPostInstallLaunch" + /** + * Outcome of starting an APK install session. + */ + sealed interface SessionLaunchResult { + /** + * The install was handed off to Android. [sessionId] is the committed + * [PackageInstaller] session ID, or `null` when the intent-based fallback was used. + */ + data class Started( + val sessionId: Int?, + ) : SessionLaunchResult + + /** + * [PackageInstaller.createSession] rejected the request because this app UID already + * has the maximum number of active sessions (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManySessions : SessionLaunchResult + + /** Any other failure before or during session creation/commit. */ + data object Failed : SessionLaunchResult + } + /** * Starts a session-based package installation workflow. * @@ -55,14 +77,35 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, - ): Boolean { + ): Boolean = + installApkSession( + context = context, + apk = apk, + launchInDebugMode = launchInDebugMode, + debugFallbackInstaller = debugFallbackInstaller, + suppressPostInstallLaunch = suppressPostInstallLaunch, + ) is SessionLaunchResult.Started + + /** + * Starts a session-based package installation workflow and returns a [SessionLaunchResult] + * with the committed `sessionId` (or a distinct [SessionLaunchResult.TooManySessions] + * when the UID's active session quota is exhausted). + */ + @JvmStatic + suspend fun installApkSession( + context: Context, + apk: File, + launchInDebugMode: Boolean = false, + debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, + suppressPostInstallLaunch: Boolean = false, + ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { apk.exists() && apk.isFile && apk.extension.equals("apk", ignoreCase = true) } if (!isValidApk) { log.error("File is not an APK: {}", apk) - return false + return SessionLaunchResult.Failed } log.info("Installing APK: {}", apk) @@ -83,42 +126,100 @@ object ApkInstaller { " Falling back to intent-based installer.", ) - installUsingIntent(context, apk, baseIntent) - return true + return if (installUsingIntent(context, apk, baseIntent)) { + SessionLaunchResult.Started(sessionId = null) + } else { + SessionLaunchResult.Failed + } } return installUsingSession(context, apk, baseIntent) } + /** + * Abandons a single [PackageInstaller] session if it is still active. Safe to call after + * the session has already succeeded, failed, or been abandoned. + */ + @JvmStatic + fun abandonSession( + context: Context, + sessionId: Int, + ): Boolean = abandonSession(context.packageManager.packageInstaller, sessionId) + + internal fun abandonSession( + installer: PackageInstaller, + sessionId: Int, + ): Boolean = + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + + /** + * Abandons all active [PackageInstaller] sessions owned by this installer package. + * + * Called at Quick Build startup and before creating a new install session so that + * unconfirmed sessions from earlier runs cannot accumulate to Android's 50-session + * per-UID cap (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale + * confirmation dialog in the system `packageinstaller` task. + * + * @return the number of sessions abandoned. + */ + @JvmStatic + fun abandonMySessions(context: Context): Int = abandonMySessions(context.packageManager.packageInstaller) + + internal fun abandonMySessions(installer: PackageInstaller): Int { + val sessions = + runCatching { installer.mySessions } + .onFailure { error -> log.warn("Failed to query existing PackageInstaller sessions", error) } + .getOrNull() + ?: return 0 + + var abandoned = 0 + for (info in sessions) { + if (abandonSession(installer, info.sessionId)) { + abandoned++ + } + } + if (abandoned > 0) { + log.info("Abandoned {} stale PackageInstaller session(s)", abandoned) + } + return abandoned + } + @Suppress("DEPRECATION", "RequestInstallPackagesPolicy") private fun installUsingIntent( context: Context, apk: File, intent: Intent, - ) { + ): Boolean { val uri = context.fileProviderUriFor(apk) intent.setAction(Intent.ACTION_INSTALL_PACKAGE) intent.setDataAndType(uri, "application/vnd.android.package-archive") intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK - try { + return try { context.startActivity(intent) + true } catch (e: Exception) { log.warn("Failed to start installation intent", e) + false } } @Suppress("RequestInstallPackagesPolicy") - private suspend fun installUsingSession( + internal suspend fun installUsingSession( context: Context, apk: File, intent: Intent, - ): Boolean { + ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() return runCatching { withContext(Dispatchers.IO) { + abandonMySessions(installer) val sessionId = installer.createSession(params) var session: PackageInstaller.Session? = null @@ -130,18 +231,33 @@ object ApkInstaller { } addToSession(session, apk) session.commit(callback.intentSender) + sessionId } catch (t: Throwable) { - runCatching { installer.abandonSession(sessionId) } + abandonSession(installer, sessionId) throw t } finally { session?.close() } } - }.onFailure { error -> - log.error("Package installation failed", error) - }.isSuccess + }.fold( + onSuccess = { sessionId -> SessionLaunchResult.Started(sessionId) }, + onFailure = { error -> + log.error("Package installation failed", error) + if (isTooManyActiveSessions(error)) { + SessionLaunchResult.TooManySessions + } else { + SessionLaunchResult.Failed + } + }, + ) } + internal fun isTooManyActiveSessions(error: Throwable): Boolean = + generateSequence(error) { it.cause }.any { cause -> + cause is IllegalStateException && + cause.message?.contains("Too many active sessions", ignoreCase = true) == true + } + private fun createSessionParams(appPackageName: String? = null): PackageInstaller.SessionParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { if (appPackageName != null) { diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt index e5420a4234..a5437cf871 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt @@ -64,9 +64,7 @@ object InstallationResultHandler { @Suppress("DEPRECATION") extras.get(Intent.EXTRA_INTENT)?.let { intent -> if (intent is Intent) { - if ((intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK) != Intent.FLAG_ACTIVITY_NEW_TASK) { - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - } + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) log.debug("startingActivity: intent={}, intent.extras={}", intent, intent.extras) context.startActivity(intent) } diff --git a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt index e80bdd374c..b7321c3c73 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt @@ -88,5 +88,7 @@ class InstallationResultHandlerSuppressLaunchTest { val started = Shadows.shadowOf(activity).nextStartedActivity assertThat(started).isNotNull() assertThat(started.action).isEqualTo("com.android.packageinstaller.CONFIRM") + assertThat(started.flags and Intent.FLAG_ACTIVITY_NEW_TASK).isEqualTo(Intent.FLAG_ACTIVITY_NEW_TASK) + assertThat(started.flags and Intent.FLAG_ACTIVITY_CLEAR_TOP).isEqualTo(Intent.FLAG_ACTIVITY_CLEAR_TOP) } } From 8a2de6a3966848a00d3cf352c8dbac4ed20f4cd5 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 5 Nov 2026 21:19:26 +0100 Subject: [PATCH 02/14] fix(ADFA-5438): Track and abandon install sessions in ProxyAppInstaller --- .../quickbuild/QuickBuildInstallAdapters.kt | 3 + .../quickbuild/InstallationEventFlowTest.kt | 4 + .../service/provision/ProxyAppInstaller.kt | 294 ++++++++++++------ 3 files changed, 209 insertions(+), 92 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt index 8d1d3851de..8fca271c90 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt @@ -160,11 +160,14 @@ class InstallationEventFlow { InstallBroadcast.Status.OTHER } } + val sessionId = + extras.getInt(PackageInstaller.EXTRA_SESSION_ID, Int.MIN_VALUE).takeIf { it != Int.MIN_VALUE } _broadcasts.tryEmit( InstallBroadcast( packageName = extras.getString(PackageInstaller.EXTRA_PACKAGE_NAME), status = status, message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE), + sessionId = sessionId, ), ) } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt index d0231e646a..99263cc803 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt @@ -25,11 +25,15 @@ class InstallationEventFlowTest { status: Int?, packageName: String? = "com.example.app", message: String? = null, + sessionId: Int? = null, ): InstallationEvent.InstallationResultEvent { val extras = mockk() every { extras.getInt(PackageInstaller.EXTRA_STATUS, any()) } answers { status ?: secondArg() } + every { extras.getInt(PackageInstaller.EXTRA_SESSION_ID, any()) } answers { + sessionId ?: secondArg() + } every { extras.getString(PackageInstaller.EXTRA_PACKAGE_NAME) } returns packageName every { extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE) } returns message val intent = mockk() diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index 9951eaba05..c50ee9dd3c 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -16,7 +16,10 @@ import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage import org.slf4j.LoggerFactory import java.io.File import java.security.MessageDigest +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference /** * What the installer needs to know about installed packages; implemented over @@ -79,11 +82,14 @@ interface InstalledPackages { * failure broadcasts often do not; a waiter must then accept it as its own * @property status the mapped status; anything unrecognized arrives as [Status.OTHER] * @property message the OS failure text when there is one, shown to the user verbatim + * @property sessionId the PackageInstaller EXTRA_SESSION_ID when the broadcast carried one, + * used to ignore stale broadcasts from earlier sessions */ data class InstallBroadcast( val packageName: String?, val status: Status, val message: String? = null, + val sessionId: Int? = null, ) { /** ABORTED is STATUS_FAILURE_ABORTED: the user cancelled the confirm dialog. */ enum class Status { SUCCESS, FAILURE, ABORTED, PENDING_USER_ACTION, OTHER } @@ -103,6 +109,30 @@ data class InstallBroadcast( get() = status == Status.SUCCESS || status == Status.FAILURE || status == Status.ABORTED } +/** + * What became of launching an APK install session. + */ +sealed interface InstallLaunchResult { + /** + * The install was handed off to Android. + * + * @property sessionId the committed PackageInstaller session ID, or null when the + * intent-based fallback was used (or when the caller only reports a boolean start) + */ + data class Started( + val sessionId: Int? = null, + ) : InstallLaunchResult + + /** + * PackageInstaller refused to create a session because this UID has reached the + * system's active-session cap (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManySessions : InstallLaunchResult + + /** Any other failure before or during session creation/commit. */ + data object Failed : InstallLaunchResult +} + /** What became of a [ProxyAppInstaller.ensureInstalled]. */ sealed interface InstallOutcome { /** @@ -165,7 +195,7 @@ class ProxyAppInstaller( /** Installed-package facts; every read goes through here so tests need no PackageManager. */ private val packages: InstalledPackages, /** Starts the install (ApkInstaller.installApk); false when it could not start. */ - private val launchInstall: suspend (File) -> Boolean, + private val launchInstall: suspend (File) -> Boolean = { false }, /** InstallationResultReceiver broadcasts, adapted app-side. */ private val broadcasts: Flow, /** @@ -187,6 +217,25 @@ class ProxyAppInstaller( * always-true keeps the plain wait-for-the-user behavior for callers without a probe. */ private val canShowConfirmDialog: () -> Boolean = { true }, + /** Starts the install and returns its session ID or launch failure reason. */ + private val launchInstallSession: suspend (File) -> InstallLaunchResult = { file -> + if (launchInstall(file)) { + InstallLaunchResult.Started() + } else { + InstallLaunchResult.Failed + } + }, + /** + * Abandons a committed PackageInstaller session by its ID. Called before re-issuing a + * silent prompt and in `finally` on every exit path from [ensureInstalled] so unconfirmed + * sessions never accumulate or intercept subsequent confirm dialogs. + */ + private val abandonSession: (Int) -> Unit = {}, + /** + * Sweeps any stale PackageInstaller sessions owned by this UID before launching a new + * install, reclaiming the 50-session pool and dismissing leftover confirm dialogs. + */ + private val sweepStaleSessions: () -> Unit = {}, /** Where the blocking work (APK hashing, PackageManager reads) runs; injectable for tests. */ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ) { @@ -211,119 +260,180 @@ class ProxyAppInstaller( return InstallOutcome.Installed(existingUid) } + runCatching { sweepStaleSessions() } + .onFailure { log.warn("failed to sweep stale install sessions before installing {}", packageName, it) } + return coroutineScope { // Set when the OS reported PENDING_USER_ACTION, which means a confirm dialog // exists; re-issuing the prompt then would stack a second dialog on it. Atomic // because the write happens in the collector child and the read on this // coroutine while that child is still running, so nothing else orders them. val pendingUserActionSeen = AtomicBoolean(false) - // Subscribe before committing the install so a fast broadcast cannot slip - // past us. PENDING_USER_ACTION is decisive too when no confirm dialog can be - // launched, since nobody will ever tap. - val verdict = - async(start = CoroutineStart.UNDISPATCHED) { + val activeSessionId = AtomicReference(null) + val launchedSessionIds = Collections.newSetFromMap(ConcurrentHashMap()) + + try { + // Subscribe before committing the install so a fast broadcast cannot slip + // past us. PENDING_USER_ACTION is decisive too when no confirm dialog can be + // launched, since nobody will ever tap. + val verdict = + async(start = CoroutineStart.UNDISPATCHED) { + try { + Result.success( + broadcasts.first { broadcast -> + val currentSessionId = activeSessionId.get() + val sessionMatches = + currentSessionId == null || + broadcast.sessionId == null || + broadcast.sessionId == currentSessionId + val packageMatches = + broadcast.packageName == null || broadcast.packageName == packageName + val ours = sessionMatches && packageMatches + if (ours && broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { + pendingUserActionSeen.set(true) + } + ours && + ( + broadcast.isTerminal || + ( + broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && + !canShowConfirmDialog() + ) + ) + }, + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // If the flow completes without a match, first() throws and no + // verdict can arrive this way. Captured as a failure so that + // ensureInstalled still never throws. + Result.failure(e) + } + } + val stampChanged = async { awaitStampChange(packageName, initialStamp) } + + val launchResult = try { - Result.success( - broadcasts.first { broadcast -> - val ours = - broadcast.packageName == null || broadcast.packageName == packageName - if (ours && broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { - pendingUserActionSeen.set(true) - } - ours && - ( - broadcast.isTerminal || - ( - broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && - !canShowConfirmDialog() - ) - ) - }, - ) + launchInstallSession(apk) } catch (e: CancellationException) { throw e } catch (e: Exception) { - // If the flow completes without a match, first() throws and no - // verdict can arrive this way. Captured as a failure so that - // ensureInstalled still never throws. - Result.failure(e) + log.error("could not start the install of {}", packageName, e) + InstallLaunchResult.Failed + } + when (launchResult) { + is InstallLaunchResult.Started -> { + launchResult.sessionId?.let { sessionId -> + activeSessionId.set(sessionId) + launchedSessionIds.add(sessionId) + } } - } - val stampChanged = async { awaitStampChange(packageName, initialStamp) } - - val started = - try { - launchInstall(apk) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - log.error("could not start the install of {}", packageName, e) - false - } - if (!started) { - log.warn("install of {} from {} did not start; reporting InstallCouldNotStart", packageName, apk) - verdict.cancel() - stampChanged.cancel() - return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) - } - val awaitVerdict: suspend () -> Verdict = { - select { - verdict.onAwait { result -> - result.fold( - onSuccess = { broadcast -> classify(broadcast) }, - onFailure = { Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)) }, + InstallLaunchResult.TooManySessions -> { + log.warn( + "install of {} from {} hit PackageInstaller session limit; reporting failure", + packageName, + apk, ) + verdict.cancel() + stampChanged.cancel() + // Mapped to QuickBuildMessage.TooManyInstallSessions in Step 4. + return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) + } + + InstallLaunchResult.Failed -> { + log.warn("install of {} from {} did not start; reporting InstallCouldNotStart", packageName, apk) + verdict.cancel() + stampChanged.cancel() + return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) } - stampChanged.onAwait { Verdict.InstalledPendingUid } } - } - val outcome = - withTimeoutOrNull(timeoutMillis) { - // A commit whose confirm dialog never reached the user is indistinguishable - // from one the user is still reading, so the first wait is bounded rather than - // the whole budget. Re-committing costs a second dialog at worst and is the - // only way back from a prompt nobody was shown - what a CoGo process death does - // to the next session's first install, the dialog-owning subscriber being - // lifecycle-bound. The deferreds are reused, so a late verdict still resolves. - withTimeoutOrNull(promptTimeoutMillis) { awaitVerdict() } - ?: run { - // A seen PENDING_USER_ACTION means the OS confirmed a dialog - // exists - the user is reading it, and a re-commit would put a - // second dialog over the first. Only the silent case (no status - // at all) is the lost-prompt one the re-issue repairs. - if (canShowConfirmDialog() && !pendingUserActionSeen.get()) { - log.info( - "no install verdict for {} in {}ms; re-issuing the prompt", - packageName, - promptTimeoutMillis, - ) - try { - launchInstall(apk) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // The first commit is still pending; keep waiting on it. - log.error("could not re-issue the install of {}", packageName, e) + + val awaitVerdict: suspend () -> Verdict = { + select { + verdict.onAwait { result -> + result.fold( + onSuccess = { broadcast -> classify(broadcast) }, + onFailure = { Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)) }, + ) + } + stampChanged.onAwait { Verdict.InstalledPendingUid } + } + } + val outcome = + withTimeoutOrNull(timeoutMillis) { + // A commit whose confirm dialog never reached the user is indistinguishable + // from one the user is still reading, so the first wait is bounded rather than + // the whole budget. Re-committing costs a second dialog at worst and is the + // only way back from a prompt nobody was shown - what a CoGo process death does + // to the next session's first install, the dialog-owning subscriber being + // lifecycle-bound. The deferreds are reused, so a late verdict still resolves. + withTimeoutOrNull(promptTimeoutMillis) { awaitVerdict() } + ?: run { + // A seen PENDING_USER_ACTION means the OS confirmed a dialog + // exists - the user is reading it, and a re-commit would put a + // second dialog over the first. Only the silent case (no status + // at all) is the lost-prompt one the re-issue repairs. + if (canShowConfirmDialog() && !pendingUserActionSeen.get()) { + log.info( + "no install verdict for {} in {}ms; re-issuing the prompt", + packageName, + promptTimeoutMillis, + ) + activeSessionId.getAndSet(null)?.let { staleSessionId -> + abandonSessionSafely(staleSessionId) + launchedSessionIds.remove(staleSessionId) + } + try { + when (val reissued = launchInstallSession(apk)) { + is InstallLaunchResult.Started -> { + reissued.sessionId?.let { sessionId -> + activeSessionId.set(sessionId) + launchedSessionIds.add(sessionId) + } + } + + InstallLaunchResult.TooManySessions, + InstallLaunchResult.Failed, + -> { + log.warn("re-issued install of {} did not start: {}", packageName, reissued) + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Keep waiting on the remaining budget. + log.error("could not re-issue the install of {}", packageName, e) + } } + awaitVerdict() } - awaitVerdict() - } + } + verdict.cancel() + stampChanged.cancel() + // The uid is resolved here, OUTSIDE both timeout windows. It retries over + // PackageManager's post-install lag, and inside the prompt budget a plain SUCCESS + // arriving late had that retry cut short - which read as "no verdict yet" and + // re-prompted the user for an install that had already succeeded. + when (outcome) { + null -> confirmationNotGivenAtTimeout() + Verdict.InstalledPendingUid -> resolveUid(packageName) + is Verdict.Settled -> outcome.outcome + } + } finally { + for (sessionId in launchedSessionIds) { + abandonSessionSafely(sessionId) } - verdict.cancel() - stampChanged.cancel() - // The uid is resolved here, OUTSIDE both timeout windows. It retries over - // PackageManager's post-install lag, and inside the prompt budget a plain SUCCESS - // arriving late had that retry cut short - which read as "no verdict yet" and - // re-prompted the user for an install that had already succeeded. - when (outcome) { - null -> confirmationNotGivenAtTimeout() - Verdict.InstalledPendingUid -> resolveUid(packageName) - is Verdict.Settled -> outcome.outcome } } } + private fun abandonSessionSafely(sessionId: Int) { + runCatching { abandonSession(sessionId) } + .onFailure { log.warn("failed to abandon install session {}", sessionId, it) } + } + /** * What one wait for an install verdict produced, before the uid read. * From 46a56b28c21114b9645ccefe1eb6dffb127d6260 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 5 Nov 2026 21:31:09 +0100 Subject: [PATCH 03/14] fix(ADFA-5438): Sweep stale PackageInstaller sessions at Quick Build startup --- .../itsaky/androidide/di/QuickBuildModule.kt | 34 +++++++++++++------ .../session/QuickBuildSessionManager.kt | 23 +++++++++---- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt index 4da92adb91..79f441fcc3 100644 --- a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt @@ -31,6 +31,7 @@ import org.appdevforall.cotg.quickbuild.domain.telemetry.QuickBuildMetricsSink import org.appdevforall.cotg.quickbuild.service.deploy.DeployChannel import org.appdevforall.cotg.quickbuild.service.deploy.DeploySender import org.appdevforall.cotg.quickbuild.service.deploy.ProxyAppConnections +import org.appdevforall.cotg.quickbuild.service.provision.InstallLaunchResult import org.appdevforall.cotg.quickbuild.service.provision.InstalledPackages import org.appdevforall.cotg.quickbuild.service.provision.ProxyAppInstaller import org.appdevforall.cotg.quickbuild.service.provision.QuickBuildClobberCheck @@ -85,16 +86,6 @@ val quickBuildModule = val context = androidContext() ProxyAppInstaller( packages = get(), - // The exact call the Run button's install flow bottoms out in: - // same PackageInstaller session params, same InstallationResultReceiver, - // same MIUI intent fallback. Post-install launch is suppressed: the session - // switches to the proxy app itself on provisioning success, so the generic - // launch-after-install must not fire a duplicate launch on every install. - launchInstall = { apk -> - withContext(Dispatchers.Main) { - ApkInstaller.installApk(context, apk, suppressPostInstallLaunch = true) - } - }, // Register before any install: the receiver's EventBus events become the // installer's completion signal. broadcasts = InstallationEventFlow().also { it.register() }.broadcasts, @@ -109,6 +100,28 @@ val quickBuildModule = .lifecycle.currentState .isAtLeast(Lifecycle.State.STARTED) }, + // The exact call the Run button's install flow bottoms out in: + // same PackageInstaller session params, same InstallationResultReceiver, + // same MIUI intent fallback. Post-install launch is suppressed: the session + // switches to the proxy app itself on provisioning success, so the generic + // launch-after-install must not fire a duplicate launch on every install. + launchInstallSession = { apk -> + val result = + withContext(Dispatchers.Main) { + ApkInstaller.installApkSession( + context = context, + apk = apk, + suppressPostInstallLaunch = true, + ) + } + when (result) { + is ApkInstaller.SessionLaunchResult.Started -> InstallLaunchResult.Started(result.sessionId) + ApkInstaller.SessionLaunchResult.TooManySessions -> InstallLaunchResult.TooManySessions + ApkInstaller.SessionLaunchResult.Failed -> InstallLaunchResult.Failed + } + }, + abandonSession = { sessionId -> ApkInstaller.abandonSession(context, sessionId) }, + sweepStaleSessions = { ApkInstaller.abandonMySessions(context) }, ) } @@ -201,6 +214,7 @@ val quickBuildModule = // AssetsProvider, which is API 30+. Below that an asset edit would be // extracted and never read, so those edits rebaseline instead. assetsLiveReloadable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R, + sweepInstallSessions = { ApkInstaller.abandonMySessions(androidContext()) }, ).also { manager -> // Narration must be scoped to the session, not to an activity on screen: // an activity-scoped collector misses every generation produced while the diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt index 353850626e..6a7389ace2 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt @@ -158,6 +158,11 @@ class QuickBuildSessionManager( * Defaults to the capable path so this module's unit tests need no Android runtime. */ private val assetsLiveReloadable: Boolean = true, + /** + * Sweeps stale PackageInstaller sessions owned by CoGo at Quick Build startup so an + * already-capped phone (MAX_ACTIVE_SESSIONS = 50) recovers without clearing app data. + */ + private val sweepInstallSessions: () -> Unit = {}, ) { /** Builds the project watcher for a live session; overridden with a fake in tests. */ fun interface WatcherFactory { @@ -461,13 +466,19 @@ class QuickBuildSessionManager( } /** - * The stale-tree sweep. Nothing is live at construction - this manager is the process's - * only session owner - so every tree under the scratch root belongs to a dead session or - * a deleted project. Launched before any tap can dispatch, but sweep() hops to IO and - * frees the dispatcher, so [provision] joins it rather than trusting the launch order: a - * prepare that overtook it would have its fresh tree swept as stale. + * The stale-tree and stale-install-session sweep. Nothing is live at construction - this + * manager is the process's only session owner - so every tree under the scratch root and + * every active PackageInstaller session belongs to a dead session or a deleted project. + * Launched before any tap can dispatch, but sweep() hops to IO and frees the dispatcher, + * so [provision] joins it rather than trusting the launch order: a prepare that overtook + * it would have its fresh tree swept as stale. */ - private val sweepJob = scope.launch { scratch.sweep() } + private val sweepJob = + scope.launch { + runCatching { withContext(ioDispatcher) { sweepInstallSessions() } } + .onFailure { log.warn("Could not sweep stale PackageInstaller sessions at startup", it) } + scratch.sweep() + } /** * Handles the Quick Build tap: starts a session from Idle, triggers a build when live, From c79f2957646d6661af98393c8b26b665446ba028 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 5 Nov 2026 21:50:28 +0100 Subject: [PATCH 04/14] feat(ADFA-5438): Report TooManyInstallSessions distinctly from InstallCouldNotStart --- .../com/itsaky/androidide/quickbuild/QuickBuildMessages.kt | 4 ++++ .../itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt | 2 ++ .../cotg/quickbuild/domain/session/QuickBuildMessage.kt | 6 ++++++ .../cotg/quickbuild/service/provision/ProxyAppInstaller.kt | 5 ++--- resources/src/main/res/values/strings.xml | 1 + 5 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt index 6f5b065d98..fe4ce8daa3 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt @@ -38,6 +38,10 @@ fun QuickBuildMessage.resolve(context: Context): String = context.getString(R.string.quick_build_install_could_not_start) } + QuickBuildMessage.TooManyInstallSessions -> { + context.getString(R.string.quick_build_too_many_install_sessions) + } + QuickBuildMessage.InstallFailed -> { context.getString(R.string.quick_build_install_failed) } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt index afd70825e9..5d27db1fb7 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt @@ -46,6 +46,7 @@ class QuickBuildMessagesTest { assertResolvesTo(QuickBuildMessage.ReinstallDeclined, R.string.quick_build_reinstall_declined) assertResolvesTo(QuickBuildMessage.ReinstallWaitingForGradle, R.string.quick_build_reinstall_waiting_for_gradle) assertResolvesTo(QuickBuildMessage.InstallCouldNotStart, R.string.quick_build_install_could_not_start) + assertResolvesTo(QuickBuildMessage.TooManyInstallSessions, R.string.quick_build_too_many_install_sessions) assertResolvesTo(QuickBuildMessage.InstallFailed, R.string.quick_build_install_failed) assertResolvesTo(QuickBuildMessage.RebuildFailed, R.string.quick_build_rebuild_failed) assertResolvesTo(QuickBuildMessage.ProvisioningFailedUnexpectedly, R.string.quick_build_provisioning_failed_unexpectedly) @@ -112,6 +113,7 @@ class QuickBuildMessagesTest { QuickBuildMessage.ReinstallTimedOut(180), QuickBuildMessage.ReinstallWaitingForGradle, QuickBuildMessage.InstallCouldNotStart, + QuickBuildMessage.TooManyInstallSessions, QuickBuildMessage.InstallFailed, QuickBuildMessage.InstalledButUnresolvable("com.example.app"), QuickBuildMessage.ForeignAppInstalled("com.example.other"), diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt index b6f9f2774e..325344d2fe 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt @@ -47,6 +47,12 @@ sealed interface QuickBuildMessage { /** The installer could not even launch the install. */ data object InstallCouldNotStart : QuickBuildMessage + /** + * Android's PackageInstaller rejected session creation because this app UID has reached the + * per-UID active-session cap (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManyInstallSessions : QuickBuildMessage + /** The install ran and the OS reported a failure with nothing more specific to say. */ data object InstallFailed : QuickBuildMessage diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index c50ee9dd3c..d46e5d58f5 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -332,14 +332,13 @@ class ProxyAppInstaller( InstallLaunchResult.TooManySessions -> { log.warn( - "install of {} from {} hit PackageInstaller session limit; reporting failure", + "install of {} from {} hit PackageInstaller session limit; reporting TooManyInstallSessions", packageName, apk, ) verdict.cancel() stampChanged.cancel() - // Mapped to QuickBuildMessage.TooManyInstallSessions in Step 4. - return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) + return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions) } InstallLaunchResult.Failed -> { diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index cfb33fbc04..eb8e124c60 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1242,6 +1242,7 @@ Your app needs a reinstall - the install prompt went unanswered for %1$d seconds. Tap Quick Build to try again. Waiting for the current Gradle build to finish - your app still needs a reinstall. Tap Quick Build to retry. Quick Build could not start installing your app. + Quick Build could not start installing your app because too many previous install prompts are still open. Tap Quick Build to try again. Quick Build could not install your app. Quick Build installed %1$s, but Android will not open it. Restarting the session reinstalls it. %1$s is already installed on this device and was not built here, so Quick Build cannot replace it without deleting its data. Back it up and uninstall it yourself first. From 636ad7cbfacb48fac2188f9bdade64730733be9c Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Fri, 6 Nov 2026 13:11:02 +0100 Subject: [PATCH 05/14] test(ADFA-5438): Add unit tests for install session abandonment and 50-session cap recovery --- .../quickbuild/InstallationEventFlowTest.kt | 13 + .../utils/ApkInstallerSessionTest.kt | 116 ++++++++ .../provision/ProxyAppInstallerTest.kt | 257 ++++++++++++++++++ .../session/QuickBuildSessionManagerTest.kt | 24 ++ 4 files changed, 410 insertions(+) create mode 100644 app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt index 99263cc803..0c74b3e3ac 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt @@ -148,4 +148,17 @@ class InstallationEventFlowTest { assertThat(broadcasts).isEmpty() } + + @Test + fun `sessionId extra is forwarded on InstallBroadcast when present and null when absent`() { + val broadcasts = + broadcastsFor( + resultEvent(PackageInstaller.STATUS_SUCCESS, sessionId = 987654), + resultEvent(PackageInstaller.STATUS_PENDING_USER_ACTION, sessionId = null), + ) + + assertThat(broadcasts).hasSize(2) + assertThat(broadcasts[0].sessionId).isEqualTo(987654) + assertThat(broadcasts[1].sessionId).isNull() + } } diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt new file mode 100644 index 0000000000..00fc85582b --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -0,0 +1,116 @@ +package com.itsaky.androidide.utils + +import android.app.Application +import android.content.Context +import android.content.Intent +import android.content.pm.PackageInstaller +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import io.mockk.every +import io.mockk.justRun +import io.mockk.mockk +import io.mockk.spyk +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.ByteArrayOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class) +class ApkInstallerSessionTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private fun sessionInfo(id: Int): PackageInstaller.SessionInfo = + mockk { + every { sessionId } returns id + } + + @Test + fun `abandonMySessions abandons all 50 sessions and tolerates already-finalized ones`() { + val active = (1..50).toMutableSet() + val installer = mockk() + every { installer.mySessions } answers { active.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + val id = firstArg() + if (id == 25) { + throw SecurityException("Session 25 already finalized") + } + active.remove(id) + } + + val abandoned = ApkInstaller.abandonMySessions(installer) + + assertThat(abandoned).isEqualTo(49) + assertThat(active).containsExactly(25) + } + + @Test + fun `installUsingSession sweeps 50 outstanding sessions so the 51st session installs`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = (1..50).toMutableSet() + var nextId = 51 + + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + val installer = mockk() + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + every { installer.createSession(any()) } answers { + if (activeSessions.size >= 50) { + throw IllegalStateException("Too many active sessions for UID 10600") + } + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val result = ApkInstaller.installUsingSession(context, apk, Intent()) + + assertThat(result).isEqualTo(ApkInstaller.SessionLaunchResult.Started(51)) + assertThat(activeSessions).containsExactly(51) + } + + @Test + fun `installUsingSession reports TooManySessions distinctly from Failed when cap remains full`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + + val installer = mockk() + every { installer.mySessions } returns emptyList() + every { installer.createSession(any()) } throws + IllegalStateException("Too many active sessions for UID 10600") + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val capResult = ApkInstaller.installUsingSession(context, apk, Intent()) + + every { installer.createSession(any()) } throws IllegalStateException("Some other error") + val genericResult = ApkInstaller.installUsingSession(context, apk, Intent()) + + assertThat(capResult).isEqualTo(ApkInstaller.SessionLaunchResult.TooManySessions) + assertThat(genericResult).isEqualTo(ApkInstaller.SessionLaunchResult.Failed) + } +} diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index 90501bba9b..a600a0ecf4 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -79,6 +79,9 @@ class ProxyAppInstallerTest { /** Scripted "can the confirm dialog be launched right now" probe. */ private var confirmDialogShowable = true + private val abandonedSessionIds = mutableListOf() + private var sweepCount = 0 + // A TestScope extension so the installer's IO hops run on the test scheduler's // virtual time instead of a real Dispatchers.IO thread. private fun TestScope.installer( @@ -96,6 +99,31 @@ class ProxyAppInstallerTest { timeoutMillis = timeoutMillis, promptTimeoutMillis = promptTimeoutMillis, canShowConfirmDialog = { confirmDialogShowable }, + abandonSession = { abandonedSessionIds += it }, + sweepStaleSessions = { sweepCount++ }, + ioDispatcher = StandardTestDispatcher(testScheduler), + ) + + private fun TestScope.sessionInstaller( + timeoutMillis: Long = 180_000L, + promptTimeoutMillis: Long = 45_000L, + broadcastFlow: Flow = broadcasts, + launchSession: suspend (File) -> InstallLaunchResult, + onAbandon: (Int) -> Unit = { abandonedSessionIds += it }, + onSweep: () -> Unit = { sweepCount++ }, + ) = ProxyAppInstaller( + packages = packages, + broadcasts = broadcastFlow, + timeoutMillis = timeoutMillis, + promptTimeoutMillis = promptTimeoutMillis, + canShowConfirmDialog = { confirmDialogShowable }, + launchInstallSession = { file -> + installLaunches += file + onLaunch() + launchSession(file) + }, + abandonSession = onAbandon, + sweepStaleSessions = onSweep, ioDispatcher = StandardTestDispatcher(testScheduler), ) @@ -694,4 +722,233 @@ class ProxyAppInstallerTest { assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) } + + @Test + fun `a committed session is abandoned in every terminal outcome and on cancellation`() = + runTest { + // 1. SUCCESS + val r1 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(101) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 101)) + advanceUntilIdle() + assertThat(r1.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(101) + + // Reset package so subsequent calls don't skip as identical bytes + packages.uid = null + abandonedSessionIds.clear() + + // 2. FAILURE + val r2 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(102) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.FAILURE, "INSTALL_FAILED", sessionId = 102)) + advanceUntilIdle() + assertThat(r2.await()).isInstanceOf(InstallOutcome.Failed::class.java) + assertThat(abandonedSessionIds).containsExactly(102) + abandonedSessionIds.clear() + + // 3. DECLINED (ABORTED) + val r3 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(103) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 103)) + advanceUntilIdle() + assertThat(r3.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallDeclined, + InstallOutcome.ConfirmationNotGiven.Reason.DECLINED, + ), + ) + assertThat(abandonedSessionIds).containsExactly(103) + abandonedSessionIds.clear() + + // 4. DIALOG_NOT_SHOWN (backgrounded when PENDING_USER_ACTION arrives) + confirmDialogShowable = false + val r4 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(104) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 104)) + advanceUntilIdle() + assertThat(r4.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallReturnToCoGo, + InstallOutcome.ConfirmationNotGiven.Reason.DIALOG_NOT_SHOWN, + ), + ) + assertThat(abandonedSessionIds).containsExactly(104) + confirmDialogShowable = true + abandonedSessionIds.clear() + + // 5. TIMED_OUT (user never confirms) + val r5 = + async { + sessionInstaller( + timeoutMillis = 10_000L, + promptTimeoutMillis = 5_000L, + launchSession = { InstallLaunchResult.Started(105) }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 105)) + advanceTimeBy(11_000L) + advanceUntilIdle() + assertThat(r5.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallTimedOut(10), + InstallOutcome.ConfirmationNotGiven.Reason.TIMED_OUT, + ), + ) + assertThat(abandonedSessionIds).containsExactly(105) + abandonedSessionIds.clear() + + // 6. Coroutine cancellation while waiting for user confirmation + val r6 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(106) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + r6.cancel() + advanceUntilIdle() + assertThat(abandonedSessionIds).containsExactly(106) + } + + @Test + fun `re-issuing a silent prompt abandons the first session before committing the second`() = + runTest { + var nextId = 201 + val events = mutableListOf() + + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + val id = nextId++ + events += "launch:$id" + InstallLaunchResult.Started(id) + }, + onAbandon = { id -> + abandonedSessionIds += id + events += "abandon:$id" + }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + assertThat(events).containsExactly("launch:201") + + advanceTimeBy(46_000L) + runCurrent() + + // Session 201 must be abandoned BEFORE session 202 is launched so two + // confirm dialogs / sessions are never active at the same time. + assertThat(events).containsExactly("launch:201", "abandon:201", "launch:202").inOrder() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 202)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(events) + .containsExactly("launch:201", "abandon:201", "launch:202", "abandon:202") + .inOrder() + } + + @Test + fun `broadcasts from a stale sessionId for the same package are ignored`() = + runTest { + val result = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(302) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + + // A leftover dialog from an earlier session (301) for the SAME package is + // cancelled by the user; it must not abort session 302. + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 301)) + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Now session 302's own confirmation succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 302)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(302) + } + + @Test + fun `TooManySessions launch result reports TooManyInstallSessions distinctly from InstallCouldNotStart`() = + runTest { + val outcome = + sessionInstaller(launchSession = { InstallLaunchResult.TooManySessions }) + .ensureInstalled(apk, PKG) + + assertThat(outcome) + .isEqualTo(InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions)) + assertThat(outcome) + .isNotEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + } + + @Test + fun `provisioning still installs when 50 committed sessions are outstanding at the start`() = + runTest { + // Models Android's PackageInstallerService.MAX_ACTIVE_SESSIONS = 50 cap. + val activeSessions = (1..50).toMutableSet() + var nextSessionId = 51 + + val result = + async { + sessionInstaller( + launchSession = { + if (activeSessions.size >= 50) { + InstallLaunchResult.TooManySessions + } else { + val id = nextSessionId++ + activeSessions += id + InstallLaunchResult.Started(id) + } + }, + onAbandon = { id -> + activeSessions -= id + abandonedSessionIds += id + }, + onSweep = { + sweepCount++ + activeSessions.clear() + }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 51)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(sweepCount).isEqualTo(1) + assertThat(activeSessions).isEmpty() + assertThat(abandonedSessionIds).containsExactly(51) + } } diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt index ae7120ce84..61da2de072 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt @@ -308,6 +308,7 @@ class QuickBuildSessionManagerTest { // The layout's tree walks hop off the session dispatcher; keep them on the test // scheduler so they stay inside virtual time rather than on a real IO thread. ioDispatcher: CoroutineDispatcher = StandardTestDispatcher(testScheduler), + sweepInstallSessions: () -> Unit = {}, ): QuickBuildSessionManager { val provisioner = object : QuickBuildProvisioner { @@ -407,6 +408,7 @@ class QuickBuildSessionManagerTest { FakePaths(projectRoot).projectScratchRoot, ioDispatcher = StandardTestDispatcher(testScheduler), ), + sweepInstallSessions = sweepInstallSessions, ).also { manager -> // Same hazard [recordNotices] documents, and the same reason for Unconfined. if (collectUserMessages) { @@ -5480,4 +5482,26 @@ class QuickBuildSessionManagerTest { assertThat(io.dispatches).isEqualTo(hopsBefore + 1) assertThat(proxyAppRebuildCount).isEqualTo(0) } + + @Test + fun `startup sweeps stale PackageInstaller sessions before provisioning runs`() = + runTest { + val staleSessions = (1..50).toMutableSet() + var sweptBeforeProvision = false + provisionOutcome = { + sweptBeforeProvision = staleSessions.isEmpty() + defaultProvisionOutcome() + } + + val manager = + createManager( + sweepInstallSessions = { staleSessions.clear() }, + ) + manager.onQuickBuildTapped() + advanceUntilIdle() + + assertThat(staleSessions).isEmpty() + assertThat(sweptBeforeProvision).isTrue() + assertThat(manager.state.value).isEqualTo(QuickBuildSessionState.Ready(0)) + } } From 1372ae9c433dbdcb071a40e8c75aa1e72586b860 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Fri, 6 Nov 2026 14:27:55 +0100 Subject: [PATCH 06/14] fix(ADFA-5438): ignore aborted broadcasts from abandoned install sessions --- .../itsaky/androidide/di/QuickBuildModule.kt | 93 +++++++++++-------- .../itsaky/androidide/utils/ApkInstaller.kt | 41 +++++++- .../service/provision/ProxyAppInstaller.kt | 32 ++++++- .../provision/ProxyAppInstallerTest.kt | 53 +++++++++++ 4 files changed, 172 insertions(+), 47 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt index 79f441fcc3..42287a5b71 100644 --- a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt @@ -84,45 +84,54 @@ val quickBuildModule = single { val context = androidContext() - ProxyAppInstaller( - packages = get(), - // Register before any install: the receiver's EventBus events become the - // installer's completion signal. - broadcasts = InstallationEventFlow().also { it.register() }.broadcasts, - // Whether the install-confirm dialog can be launched right now. The - // dialog-owning subscriber (BaseEditorActivity -> InstallationResultHandler) - // is EventBus lifecycle-bound - registered onStart, unregistered onStop - - // so it can show the dialog exactly while the process is STARTED. Racy - // reads err toward waiting (the installer's timeout is the backstop). - canShowConfirmDialog = { - ProcessLifecycleOwner - .get() - .lifecycle.currentState - .isAtLeast(Lifecycle.State.STARTED) - }, - // The exact call the Run button's install flow bottoms out in: - // same PackageInstaller session params, same InstallationResultReceiver, - // same MIUI intent fallback. Post-install launch is suppressed: the session - // switches to the proxy app itself on provisioning success, so the generic - // launch-after-install must not fire a duplicate launch on every install. - launchInstallSession = { apk -> - val result = - withContext(Dispatchers.Main) { - ApkInstaller.installApkSession( - context = context, - apk = apk, - suppressPostInstallLaunch = true, - ) + lateinit var installer: ProxyAppInstaller + installer = + ProxyAppInstaller( + packages = get(), + // Register before any install: the receiver's EventBus events become the + // installer's completion signal. + broadcasts = InstallationEventFlow().also { it.register() }.broadcasts, + // Whether the install-confirm dialog can be launched right now. The + // dialog-owning subscriber (BaseEditorActivity -> InstallationResultHandler) + // is EventBus lifecycle-bound - registered onStart, unregistered onStop - + // so it can show the dialog exactly while the process is STARTED. Racy + // reads err toward waiting (the installer's timeout is the backstop). + canShowConfirmDialog = { + ProcessLifecycleOwner + .get() + .lifecycle.currentState + .isAtLeast(Lifecycle.State.STARTED) + }, + // The exact call the Run button's install flow bottoms out in: + // same PackageInstaller session params, same InstallationResultReceiver, + // same MIUI intent fallback. Post-install launch is suppressed: the session + // switches to the proxy app itself on provisioning success, so the generic + // launch-after-install must not fire a duplicate launch on every install. + launchInstallSession = { apk -> + val result = + withContext(Dispatchers.Main) { + ApkInstaller.installApkSession( + context = context, + apk = apk, + suppressPostInstallLaunch = true, + onBeforeAbandon = installer::recordAbandonedSession, + ) + } + when (result) { + is ApkInstaller.SessionLaunchResult.Started -> InstallLaunchResult.Started(result.sessionId) + ApkInstaller.SessionLaunchResult.TooManySessions -> InstallLaunchResult.TooManySessions + ApkInstaller.SessionLaunchResult.Failed -> InstallLaunchResult.Failed } - when (result) { - is ApkInstaller.SessionLaunchResult.Started -> InstallLaunchResult.Started(result.sessionId) - ApkInstaller.SessionLaunchResult.TooManySessions -> InstallLaunchResult.TooManySessions - ApkInstaller.SessionLaunchResult.Failed -> InstallLaunchResult.Failed - } - }, - abandonSession = { sessionId -> ApkInstaller.abandonSession(context, sessionId) }, - sweepStaleSessions = { ApkInstaller.abandonMySessions(context) }, - ) + }, + abandonSession = { sessionId -> ApkInstaller.abandonSession(context, sessionId) }, + sweepStaleSessions = { + ApkInstaller.abandonMySessions( + context = context, + onBeforeAbandon = installer::recordAbandonedSession, + ) + }, + ) + installer } single { @@ -214,7 +223,13 @@ val quickBuildModule = // AssetsProvider, which is API 30+. Below that an asset edit would be // extracted and never read, so those edits rebaseline instead. assetsLiveReloadable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R, - sweepInstallSessions = { ApkInstaller.abandonMySessions(androidContext()) }, + sweepInstallSessions = { + val installer = get() + ApkInstaller.abandonMySessions( + context = androidContext(), + onBeforeAbandon = installer::recordAbandonedSession, + ) + }, ).also { manager -> // Narration must be scoped to the session, not to an activity on screen: // an activity-scoped collector misses every generation produced while the diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 3ca3a38d4d..fe78b88c54 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -98,6 +98,7 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, + onBeforeAbandon: (Int) -> Unit = {}, ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { @@ -133,7 +134,7 @@ object ApkInstaller { } } - return installUsingSession(context, apk, baseIntent) + return installUsingSession(context, apk, baseIntent, onBeforeAbandon) } /** @@ -146,6 +147,10 @@ object ApkInstaller { sessionId: Int, ): Boolean = abandonSession(context.packageManager.packageInstaller, sessionId) + /** + * Abandons [sessionId] on [installer], returning `true` if `abandonSession` succeeded and + * `false` if the session was already finalized or no longer exists. + */ internal fun abandonSession( installer: PackageInstaller, sessionId: Int, @@ -164,12 +169,25 @@ object ApkInstaller { * per-UID cap (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale * confirmation dialog in the system `packageinstaller` task. * + * @param onBeforeAbandon invoked with each session ID before `abandonSession` runs so + * callers can ignore the `STATUS_FAILURE_ABORTED` broadcast Android emits on abandonment. * @return the number of sessions abandoned. */ @JvmStatic - fun abandonMySessions(context: Context): Int = abandonMySessions(context.packageManager.packageInstaller) + @JvmOverloads + fun abandonMySessions( + context: Context, + onBeforeAbandon: (Int) -> Unit = {}, + ): Int = abandonMySessions(context.packageManager.packageInstaller, onBeforeAbandon) - internal fun abandonMySessions(installer: PackageInstaller): Int { + /** + * Queries [PackageInstaller.getMySessions] on [installer] and abandons each session after + * notifying [onBeforeAbandon]. + */ + internal fun abandonMySessions( + installer: PackageInstaller, + onBeforeAbandon: (Int) -> Unit = {}, + ): Int { val sessions = runCatching { installer.mySessions } .onFailure { error -> log.warn("Failed to query existing PackageInstaller sessions", error) } @@ -178,6 +196,7 @@ object ApkInstaller { var abandoned = 0 for (info in sessions) { + runCatching { onBeforeAbandon(info.sessionId) } if (abandonSession(installer, info.sessionId)) { abandoned++ } @@ -188,6 +207,10 @@ object ApkInstaller { return abandoned } + /** + * Launches a fallback `ACTION_INSTALL_PACKAGE` activity intent for devices where + * session-based installation is disabled, returning `true` if the activity started. + */ @Suppress("DEPRECATION", "RequestInstallPackagesPolicy") private fun installUsingIntent( context: Context, @@ -208,18 +231,23 @@ object ApkInstaller { } } + /** + * Creates, populates, and commits a [PackageInstaller] session for [apk], returning + * a [SessionLaunchResult] with the committed session ID or failure classification. + */ @Suppress("RequestInstallPackagesPolicy") internal suspend fun installUsingSession( context: Context, apk: File, intent: Intent, + onBeforeAbandon: (Int) -> Unit = {}, ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() return runCatching { withContext(Dispatchers.IO) { - abandonMySessions(installer) + abandonMySessions(installer, onBeforeAbandon) val sessionId = installer.createSession(params) var session: PackageInstaller.Session? = null @@ -233,6 +261,7 @@ object ApkInstaller { session.commit(callback.intentSender) sessionId } catch (t: Throwable) { + runCatching { onBeforeAbandon(sessionId) } abandonSession(installer, sessionId) throw t } finally { @@ -252,6 +281,10 @@ object ApkInstaller { ) } + /** + * Returns `true` when [error] or any cause in its chain is the `IllegalStateException` + * thrown by Android's `PackageInstallerService` when the per-UID session cap is reached. + */ internal fun isTooManyActiveSessions(error: Throwable): Boolean = generateSequence(error) { it.cause }.any { cause -> cause is IllegalStateException && diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index d46e5d58f5..dd4442a487 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -239,6 +239,18 @@ class ProxyAppInstaller( /** Where the blocking work (APK hashing, PackageManager reads) runs; injectable for tests. */ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ) { + private val abandonedSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + /** + * Records [sessionId] as abandoned before `PackageInstaller.abandonSession` runs so that + * Android's resulting `STATUS_FAILURE_ABORTED` broadcast cannot match an in-flight install + * while `activeSessionId` is still `null`. + */ + fun recordAbandonedSession(sessionId: Int) { + abandonedSessionIds.add(sessionId) + } + /** * Gets [packageName] installed from [apk], skipping the install when the bytes on * device already match. @@ -283,9 +295,12 @@ class ProxyAppInstaller( broadcasts.first { broadcast -> val currentSessionId = activeSessionId.get() val sessionMatches = - currentSessionId == null || - broadcast.sessionId == null || - broadcast.sessionId == currentSessionId + broadcast.sessionId?.let { it in abandonedSessionIds } != true && + ( + currentSessionId == null || + broadcast.sessionId == null || + broadcast.sessionId == currentSessionId + ) val packageMatches = broadcast.packageName == null || broadcast.packageName == packageName val ours = sessionMatches && packageMatches @@ -325,6 +340,7 @@ class ProxyAppInstaller( when (launchResult) { is InstallLaunchResult.Started -> { launchResult.sessionId?.let { sessionId -> + abandonedSessionIds.remove(sessionId) activeSessionId.set(sessionId) launchedSessionIds.add(sessionId) } @@ -380,7 +396,9 @@ class ProxyAppInstaller( packageName, promptTimeoutMillis, ) - activeSessionId.getAndSet(null)?.let { staleSessionId -> + activeSessionId.get()?.let { staleSessionId -> + abandonedSessionIds.add(staleSessionId) + activeSessionId.set(null) abandonSessionSafely(staleSessionId) launchedSessionIds.remove(staleSessionId) } @@ -388,6 +406,7 @@ class ProxyAppInstaller( when (val reissued = launchInstallSession(apk)) { is InstallLaunchResult.Started -> { reissued.sessionId?.let { sessionId -> + abandonedSessionIds.remove(sessionId) activeSessionId.set(sessionId) launchedSessionIds.add(sessionId) } @@ -428,7 +447,12 @@ class ProxyAppInstaller( } } + /** + * Marks [sessionId] as abandoned and invokes [abandonSession], swallowing any exception so + * cleanup in `finally` never masks the install outcome. + */ private fun abandonSessionSafely(sessionId: Int) { + abandonedSessionIds.add(sessionId) runCatching { abandonSession(sessionId) } .onFailure { log.warn("failed to abandon install session {}", sessionId, it) } } diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index a600a0ecf4..a91c689a82 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -951,4 +951,57 @@ class ProxyAppInstallerTest { assertThat(activeSessions).isEmpty() assertThat(abandonedSessionIds).containsExactly(51) } + + @Test + fun `ABORTED broadcasts triggered by abandoning committed sessions during sweep or re-issue do not cause false ReinstallDeclined`() = + runTest { + var nextId = 401 + lateinit var installerUnderTest: ProxyAppInstaller + + installerUnderTest = + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + val id = nextId++ + InstallLaunchResult.Started(id) + }, + onAbandon = { id -> + abandonedSessionIds += id + // Android's PackageInstallerSession.abandon() dispatches + // STATUS_FAILURE_ABORTED when a committed session is abandoned. + broadcasts.tryEmit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = id), + ) + }, + onSweep = { + sweepCount++ + // Sweep records and abandons a pre-existing committed session (400) + // before activeSessionId is assigned. + installerUnderTest.recordAbandonedSession(400) + broadcasts.tryEmit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 400), + ) + }, + ) + + val result = async { installerUnderTest.ensureInstalled(apk, PKG) } + runCurrent() + + // Neither the sweep's ABORTED(400) nor the 45s re-issue's ABORTED(401) + // (emitted while activeSessionId is null) may terminate ensureInstalled as ReinstallDeclined. + assertThat(result.isCompleted).isFalse() + + advanceTimeBy(46_000L) + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Session 402 succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 402)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(401, 402).inOrder() + } } From 585cd66089e5815867dd8a2f61b82042b54e62c7 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Fri, 6 Nov 2026 15:02:12 +0100 Subject: [PATCH 07/14] fix(ADFA-5438): Avoid cancelling in-flight user installs during session sweeps --- .../itsaky/androidide/di/QuickBuildModule.kt | 1 - .../services/InstallationResultReceiver.kt | 2 + .../itsaky/androidide/utils/ApkInstaller.kt | 72 +++++++++++++++---- .../utils/InstallationResultHandler.kt | 2 + .../viewmodel/ApkInstallationViewModel.kt | 2 +- .../utils/ApkInstallerSessionTest.kt | 50 +++++++++++-- 6 files changed, 106 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt index 42287a5b71..d4ac6697b3 100644 --- a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt @@ -114,7 +114,6 @@ val quickBuildModule = context = context, apk = apk, suppressPostInstallLaunch = true, - onBeforeAbandon = installer::recordAbandonedSession, ) } when (result) { diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index a121e32ae1..89d3fb660c 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -22,6 +22,7 @@ import android.content.Context import android.content.Intent import com.itsaky.androidide.buildinfo.BuildInfo import com.itsaky.androidide.events.InstallationEvent.InstallationResultEvent +import com.itsaky.androidide.utils.ApkInstaller import org.greenrobot.eventbus.EventBus /** @@ -38,6 +39,7 @@ class InstallationResultReceiver : BroadcastReceiver() { context: Context, intent: Intent, ) { + ApkInstaller.onInstallStatusBroadcast(intent) EventBus.getDefault().post(InstallationResultEvent(intent)) } } diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index fe78b88c54..21505dd881 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -15,6 +15,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import java.io.File +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap /** * Utility class for installing APKs. @@ -25,6 +27,15 @@ object ApkInstaller { private val log = LoggerFactory.getLogger(ApkInstaller::class.java) private const val DEBUG_FALLBACK_INSTALLER = false + /** + * Session IDs of committed non-Quick-Build installs (Run button and `InstallFileAction`) + * that have not yet delivered a terminal status broadcast or been explicitly abandoned. + * Preserved by [abandonMySessions] so a Quick Build sweep does not cancel a user install + * that is still waiting for confirmation. + */ + private val inFlightUserSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + /** * Boolean extra riding the install callback intent: on STATUS_SUCCESS, do not run the * launch-after-install behavior for this package. @@ -98,7 +109,6 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, - onBeforeAbandon: (Int) -> Unit = {}, ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { @@ -134,7 +144,7 @@ object ApkInstaller { } } - return installUsingSession(context, apk, baseIntent, onBeforeAbandon) + return installUsingSession(context, apk, baseIntent) } /** @@ -154,20 +164,47 @@ object ApkInstaller { internal fun abandonSession( installer: PackageInstaller, sessionId: Int, - ): Boolean = - runCatching { + ): Boolean { + inFlightUserSessionIds.remove(sessionId) + return runCatching { installer.abandonSession(sessionId) }.onFailure { error -> log.debug("Session {} already finalized or could not be abandoned", sessionId, error) }.isSuccess + } + + /** + * Records a status broadcast from [InstallationResultReceiver] so any non-Quick-Build + * session that reaches a terminal outcome is removed from [inFlightUserSessionIds]. + */ + internal fun onInstallStatusBroadcast(intent: Intent?) { + val extras = intent?.extras ?: return + if (!extras.containsKey(PackageInstaller.EXTRA_STATUS)) return + val status = extras.getInt(PackageInstaller.EXTRA_STATUS) + if (status != PackageInstaller.STATUS_PENDING_USER_ACTION && + extras.containsKey(PackageInstaller.EXTRA_SESSION_ID) + ) { + inFlightUserSessionIds.remove(extras.getInt(PackageInstaller.EXTRA_SESSION_ID)) + } + } + + /** + * Clears tracked in-flight user session IDs between unit tests. + */ + internal fun clearInFlightUserSessionsForTesting() { + inFlightUserSessionIds.clear() + } /** - * Abandons all active [PackageInstaller] sessions owned by this installer package. + * Abandons stale [PackageInstaller] sessions owned by this installer package while + * preserving any in-flight non-Quick-Build install sessions ([inFlightUserSessionIds]) + * that are still waiting for user confirmation. * - * Called at Quick Build startup and before creating a new install session so that - * unconfirmed sessions from earlier runs cannot accumulate to Android's 50-session - * per-UID cap (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale - * confirmation dialog in the system `packageinstaller` task. + * Called at Quick Build startup and before Quick Build provisioning so that unconfirmed + * sessions from earlier runs cannot accumulate to Android's 50-session per-UID cap + * (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale confirmation dialog + * in the system `packageinstaller` task, without cancelling a concurrent Run-button or + * `InstallFileAction` install. * * @param onBeforeAbandon invoked with each session ID before `abandonSession` runs so * callers can ignore the `STATUS_FAILURE_ABORTED` broadcast Android emits on abandonment. @@ -181,8 +218,8 @@ object ApkInstaller { ): Int = abandonMySessions(context.packageManager.packageInstaller, onBeforeAbandon) /** - * Queries [PackageInstaller.getMySessions] on [installer] and abandons each session after - * notifying [onBeforeAbandon]. + * Queries [PackageInstaller.getMySessions] on [installer] and abandons each stale session + * (excluding [inFlightUserSessionIds]) after notifying [onBeforeAbandon]. */ internal fun abandonMySessions( installer: PackageInstaller, @@ -194,8 +231,14 @@ object ApkInstaller { .getOrNull() ?: return 0 + val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } + inFlightUserSessionIds.retainAll(activeIds) + var abandoned = 0 for (info in sessions) { + if (info.sessionId in inFlightUserSessionIds) { + continue + } runCatching { onBeforeAbandon(info.sessionId) } if (abandonSession(installer, info.sessionId)) { abandoned++ @@ -240,14 +283,13 @@ object ApkInstaller { context: Context, apk: File, intent: Intent, - onBeforeAbandon: (Int) -> Unit = {}, ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() + val isQuickBuildInstall = intent.getBooleanExtra(EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, false) return runCatching { withContext(Dispatchers.IO) { - abandonMySessions(installer, onBeforeAbandon) val sessionId = installer.createSession(params) var session: PackageInstaller.Session? = null @@ -259,9 +301,11 @@ object ApkInstaller { } addToSession(session, apk) session.commit(callback.intentSender) + if (!isQuickBuildInstall) { + inFlightUserSessionIds.add(sessionId) + } sessionId } catch (t: Throwable) { - runCatching { onBeforeAbandon(sessionId) } abandonSession(installer, sessionId) throw t } finally { diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt index a5437cf871..fe11ec9166 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt @@ -58,6 +58,8 @@ object InstallationResultHandler { val status = extras.getInt(PackageInstaller.EXTRA_STATUS) val message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE) + ApkInstaller.onInstallStatusBroadcast(intent) + return when (status) { PackageInstaller.STATUS_PENDING_USER_ACTION -> { log.debug("PENDING_USER_ACTION: extras={}", extras) diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt index 68784cbbbc..a062a47a4f 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt @@ -208,7 +208,7 @@ class ApkInstallationViewModel : ViewModel() { } try { - packageInstaller.abandonSession(sessionId) + ApkInstaller.abandonSession(packageInstaller, sessionId) } catch (e: Exception) { logger.error("Failed to abandon session with ID: {}", sessionId, e) } finally { diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index 00fc85582b..9c7e5c35db 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -11,6 +11,8 @@ import io.mockk.justRun import io.mockk.mockk import io.mockk.spyk import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -25,6 +27,12 @@ class ApkInstallerSessionTest { @get:Rule val tempFolder = TemporaryFolder() + @Before + @After + fun resetInFlightSessions() { + ApkInstaller.clearInFlightUserSessionsForTesting() + } + private fun sessionInfo(id: Int): PackageInstaller.SessionInfo = mockk { every { sessionId } returns id @@ -50,11 +58,11 @@ class ApkInstallerSessionTest { } @Test - fun `installUsingSession sweeps 50 outstanding sessions so the 51st session installs`() = + fun `installUsingSession does not abandon other in-flight sessions and abandonMySessions preserves pending user installs`() = runTest { val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } - val activeSessions = (1..50).toMutableSet() - var nextId = 51 + val activeSessions = (1..49).toMutableSet() + var nextId = 100 val session = mockk(relaxed = true) every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() @@ -83,10 +91,38 @@ class ApkInstallerSessionTest { val context = spyk(baseContext) every { context.packageManager } returns pm - val result = ApkInstaller.installUsingSession(context, apk, Intent()) - - assertThat(result).isEqualTo(ApkInstaller.SessionLaunchResult.Started(51)) - assertThat(activeSessions).containsExactly(51) + // 1. Start a Run-button / InstallFileAction install (session 100); it is now waiting for confirmation. + val runButtonResult = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(runButtonResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(100)) + assertThat(activeSessions).contains(100) + + // 2. Quick Build sweeps stale sessions before provisioning: all 49 stale sessions are + // abandoned, but the pending Run-button session (100) is preserved. + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(49) + assertThat(activeSessions).containsExactly(100) + + // 3. Quick Build starts its proxy install (session 101): session 100 is still not abandoned. + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val quickBuildResult = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(quickBuildResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(101)) + assertThat(activeSessions).containsExactly(100, 101) + + // 4. Reverse direction: another Run-button / InstallFileAction install (session 102) + // does not abandon the pending Quick Build session (101). + val secondUserInstall = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(secondUserInstall).isEqualTo(ApkInstaller.SessionLaunchResult.Started(102)) + assertThat(activeSessions).containsExactly(100, 101, 102) + + // 5. Once session 100 delivers a terminal broadcast, it is no longer protected as in-flight. + ApkInstaller.onInstallStatusBroadcast( + Intent() + .putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE_ABORTED) + .putExtra(PackageInstaller.EXTRA_SESSION_ID, 100), + ) + ApkInstaller.abandonMySessions(installer) + assertThat(activeSessions).containsExactly(102) } @Test From ed70b17949ebdca5e1b0229f3f79bd70c724a57c Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Tue, 10 Nov 2026 18:33:46 +0100 Subject: [PATCH 08/14] fix(ADFA-5438): Persist sessions across restarts --- .../services/InstallationResultReceiver.kt | 2 +- .../itsaky/androidide/utils/ApkInstaller.kt | 180 +++++++++++++++--- .../utils/InstallationResultHandler.kt | 2 +- .../viewmodel/ApkInstallationViewModel.kt | 2 +- .../utils/ApkInstallerSessionTest.kt | 82 +++++++- .../service/provision/ProxyAppInstaller.kt | 9 +- .../session/QuickBuildSessionManager.kt | 22 ++- .../provision/ProxyAppInstallerTest.kt | 14 +- 8 files changed, 266 insertions(+), 47 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index 89d3fb660c..81b0a25a13 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -39,7 +39,7 @@ class InstallationResultReceiver : BroadcastReceiver() { context: Context, intent: Intent, ) { - ApkInstaller.onInstallStatusBroadcast(intent) + ApkInstaller.onInstallStatusBroadcast(intent, context) EventBus.getDefault().post(InstallationResultEvent(intent)) } } diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 21505dd881..24585e0bf5 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -26,12 +26,25 @@ import java.util.concurrent.ConcurrentHashMap object ApkInstaller { private val log = LoggerFactory.getLogger(ApkInstaller::class.java) private const val DEBUG_FALLBACK_INSTALLER = false + private const val PREFS_INSTALLER_SESSIONS = "ide.installer.sessions" + private const val KEY_QUICK_BUILD_SESSIONS = "quick_build_session_ids" + private const val KEY_IN_FLIGHT_USER_SESSIONS = "in_flight_user_session_ids" + private const val MAX_ACTIVE_SESSIONS = 50 /** - * Session IDs of committed non-Quick-Build installs (Run button and `InstallFileAction`) - * that have not yet delivered a terminal status broadcast or been explicitly abandoned. - * Preserved by [abandonMySessions] so a Quick Build sweep does not cancel a user install - * that is still waiting for confirmation. + * Session IDs of Quick Build proxy-app installs created by this app, persisted across + * process restarts in `SharedPreferences` so [abandonMySessions] can identify and sweep + * stale Quick Build sessions without abandoning Standard Run installs. + */ + private val quickBuildSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + /** + * Session IDs of active non-Quick-Build installs (Standard Run and `InstallFileAction`) + * recorded immediately at [PackageInstaller.createSession] (covering both APK staging and + * user confirmation) until a terminal status broadcast or explicit abandonment. Persisted + * to `SharedPreferences` so a Quick Build sweep excludes Standard Run sessions even across + * configuration changes or process restarts. */ private val inFlightUserSessionIds: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) @@ -155,7 +168,10 @@ object ApkInstaller { fun abandonSession( context: Context, sessionId: Int, - ): Boolean = abandonSession(context.packageManager.packageInstaller, sessionId) + ): Boolean { + removeTrackedSession(context, sessionId) + return abandonSession(context.packageManager.packageInstaller, sessionId) + } /** * Abandons [sessionId] on [installer], returning `true` if `abandonSession` succeeded and @@ -166,6 +182,7 @@ object ApkInstaller { sessionId: Int, ): Boolean { inFlightUserSessionIds.remove(sessionId) + quickBuildSessionIds.remove(sessionId) return runCatching { installer.abandonSession(sessionId) }.onFailure { error -> @@ -174,36 +191,131 @@ object ApkInstaller { } /** - * Records a status broadcast from [InstallationResultReceiver] so any non-Quick-Build - * session that reaches a terminal outcome is removed from [inFlightUserSessionIds]. + * Records a status broadcast from [InstallationResultReceiver] so any session that reaches + * a terminal outcome is removed from tracked session sets and persisted storage. */ - internal fun onInstallStatusBroadcast(intent: Intent?) { + @JvmOverloads + internal fun onInstallStatusBroadcast( + intent: Intent?, + context: Context? = null, + ) { val extras = intent?.extras ?: return if (!extras.containsKey(PackageInstaller.EXTRA_STATUS)) return val status = extras.getInt(PackageInstaller.EXTRA_STATUS) if (status != PackageInstaller.STATUS_PENDING_USER_ACTION && extras.containsKey(PackageInstaller.EXTRA_SESSION_ID) ) { - inFlightUserSessionIds.remove(extras.getInt(PackageInstaller.EXTRA_SESSION_ID)) + removeTrackedSession(context, extras.getInt(PackageInstaller.EXTRA_SESSION_ID)) } } /** - * Clears tracked in-flight user session IDs between unit tests. + * Clears in-memory tracked session IDs (and persisted preferences when [context] is given) + * between unit tests. */ - internal fun clearInFlightUserSessionsForTesting() { + internal fun clearInFlightUserSessionsForTesting(context: Context? = null) { inFlightUserSessionIds.clear() + quickBuildSessionIds.clear() + if (context != null) { + runCatching { + context.applicationContext + .getSharedPreferences(PREFS_INSTALLER_SESSIONS, Context.MODE_PRIVATE) + .edit() + .remove(KEY_IN_FLIGHT_USER_SESSIONS) + .remove(KEY_QUICK_BUILD_SESSIONS) + .commit() + } + } } /** - * Abandons stale [PackageInstaller] sessions owned by this installer package while - * preserving any in-flight non-Quick-Build install sessions ([inFlightUserSessionIds]) - * that are still waiting for user confirmation. + * Clears only the in-memory session sets to simulate an app process restart in unit tests + * while keeping `SharedPreferences` state intact. + */ + internal fun clearInMemorySessionsForTesting() { + inFlightUserSessionIds.clear() + quickBuildSessionIds.clear() + } + + private fun recordQuickBuildSession( + context: Context, + sessionId: Int, + ) { + loadPersistedSessions(context) + inFlightUserSessionIds.remove(sessionId) + quickBuildSessionIds.add(sessionId) + persistTrackedSessions(context) + } + + private fun recordInFlightUserSession( + context: Context, + sessionId: Int, + ) { + loadPersistedSessions(context) + quickBuildSessionIds.remove(sessionId) + inFlightUserSessionIds.add(sessionId) + persistTrackedSessions(context) + } + + private fun removeTrackedSession( + context: Context?, + sessionId: Int, + ) { + if (context != null) { + loadPersistedSessions(context) + } + val removedUser = inFlightUserSessionIds.remove(sessionId) + val removedQb = quickBuildSessionIds.remove(sessionId) + if (context != null && (removedUser || removedQb)) { + persistTrackedSessions(context) + } + } + + private fun loadPersistedSessions(context: Context) { + runCatching { + val prefs = + context.applicationContext.getSharedPreferences( + PREFS_INSTALLER_SESSIONS, + Context.MODE_PRIVATE, + ) + prefs + .getStringSet(KEY_IN_FLIGHT_USER_SESSIONS, emptySet()) + .orEmpty() + .mapNotNullTo(inFlightUserSessionIds) { it.toIntOrNull() } + prefs + .getStringSet(KEY_QUICK_BUILD_SESSIONS, emptySet()) + .orEmpty() + .mapNotNullTo(quickBuildSessionIds) { it.toIntOrNull() } + }.onFailure { error -> + log.debug("Unable to read persisted installer session IDs", error) + } + } + + private fun persistTrackedSessions(context: Context) { + runCatching { + val userSnapshot = inFlightUserSessionIds.mapTo(HashSet()) { it.toString() } + val qbSnapshot = quickBuildSessionIds.mapTo(HashSet()) { it.toString() } + context.applicationContext + .getSharedPreferences(PREFS_INSTALLER_SESSIONS, Context.MODE_PRIVATE) + .edit() + .putStringSet(KEY_IN_FLIGHT_USER_SESSIONS, userSnapshot) + .putStringSet(KEY_QUICK_BUILD_SESSIONS, qbSnapshot) + .commit() + }.onFailure { error -> + log.debug("Unable to persist installer session IDs", error) + } + } + + /** + * Abandons stale Quick Build [PackageInstaller] sessions owned by this installer package + * while excluding any active Standard Run or `InstallFileAction` install sessions + * ([inFlightUserSessionIds]), including sessions that are currently staging APK bytes or + * awaiting user confirmation across a restart. * * Called at Quick Build startup and before Quick Build provisioning so that unconfirmed - * sessions from earlier runs cannot accumulate to Android's 50-session per-UID cap - * (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale confirmation dialog - * in the system `packageinstaller` task, without cancelling a concurrent Run-button or + * Quick Build sessions from earlier runs cannot accumulate to Android's 50-session per-UID + * cap (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale confirmation dialog + * in the system `packageinstaller` task, without cancelling a concurrent Standard Run or * `InstallFileAction` install. * * @param onBeforeAbandon invoked with each session ID before `abandonSession` runs so @@ -215,11 +327,17 @@ object ApkInstaller { fun abandonMySessions( context: Context, onBeforeAbandon: (Int) -> Unit = {}, - ): Int = abandonMySessions(context.packageManager.packageInstaller, onBeforeAbandon) + ): Int { + loadPersistedSessions(context) + val abandoned = abandonMySessions(context.packageManager.packageInstaller, onBeforeAbandon) + persistTrackedSessions(context) + return abandoned + } /** - * Queries [PackageInstaller.getMySessions] on [installer] and abandons each stale session - * (excluding [inFlightUserSessionIds]) after notifying [onBeforeAbandon]. + * Queries [PackageInstaller.getMySessions] on [installer] and abandons each stale Quick Build + * session (or legacy cap-overflow session when the 50-session limit is reached), always + * excluding [inFlightUserSessionIds], after notifying [onBeforeAbandon]. */ internal fun abandonMySessions( installer: PackageInstaller, @@ -233,14 +351,20 @@ object ApkInstaller { val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } inFlightUserSessionIds.retainAll(activeIds) + quickBuildSessionIds.retainAll(activeIds) + val isAtSessionCap = sessions.size >= MAX_ACTIVE_SESSIONS var abandoned = 0 for (info in sessions) { - if (info.sessionId in inFlightUserSessionIds) { + val id = info.sessionId + if (id in inFlightUserSessionIds) { + continue + } + if (id !in quickBuildSessionIds && !isAtSessionCap) { continue } - runCatching { onBeforeAbandon(info.sessionId) } - if (abandonSession(installer, info.sessionId)) { + runCatching { onBeforeAbandon(id) } + if (abandonSession(installer, id)) { abandoned++ } } @@ -291,6 +415,11 @@ object ApkInstaller { return runCatching { withContext(Dispatchers.IO) { val sessionId = installer.createSession(params) + if (isQuickBuildInstall) { + recordQuickBuildSession(context, sessionId) + } else { + recordInFlightUserSession(context, sessionId) + } var session: PackageInstaller.Session? = null try { @@ -301,12 +430,9 @@ object ApkInstaller { } addToSession(session, apk) session.commit(callback.intentSender) - if (!isQuickBuildInstall) { - inFlightUserSessionIds.add(sessionId) - } sessionId } catch (t: Throwable) { - abandonSession(installer, sessionId) + abandonSession(context, sessionId) throw t } finally { session?.close() diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt index fe11ec9166..69953467af 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt @@ -58,7 +58,7 @@ object InstallationResultHandler { val status = extras.getInt(PackageInstaller.EXTRA_STATUS) val message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE) - ApkInstaller.onInstallStatusBroadcast(intent) + ApkInstaller.onInstallStatusBroadcast(intent, context) return when (status) { PackageInstaller.STATUS_PENDING_USER_ACTION -> { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt index a062a47a4f..e883f71f68 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt @@ -208,7 +208,7 @@ class ApkInstallationViewModel : ViewModel() { } try { - ApkInstaller.abandonSession(packageInstaller, sessionId) + ApkInstaller.abandonSession(context, sessionId) } catch (e: Exception) { logger.error("Failed to abandon session with ID: {}", sessionId, e) } finally { diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index 9c7e5c35db..0f78f1eca9 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -30,7 +30,9 @@ class ApkInstallerSessionTest { @Before @After fun resetInFlightSessions() { - ApkInstaller.clearInFlightUserSessionsForTesting() + ApkInstaller.clearInFlightUserSessionsForTesting( + ApplicationProvider.getApplicationContext(), + ) } private fun sessionInfo(id: Int): PackageInstaller.SessionInfo = @@ -115,16 +117,90 @@ class ApkInstallerSessionTest { assertThat(secondUserInstall).isEqualTo(ApkInstaller.SessionLaunchResult.Started(102)) assertThat(activeSessions).containsExactly(100, 101, 102) - // 5. Once session 100 delivers a terminal broadcast, it is no longer protected as in-flight. + // 5. Once session 100 finishes with a terminal broadcast, sweeping abandons the stale + // Quick Build session (101) while preserving the active Standard Run session (102). + activeSessions.remove(100) ApkInstaller.onInstallStatusBroadcast( Intent() .putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE_ABORTED) .putExtra(PackageInstaller.EXTRA_SESSION_ID, 100), + context, ) - ApkInstaller.abandonMySessions(installer) + ApkInstaller.abandonMySessions(context) assertThat(activeSessions).containsExactly(102) } + @Test + fun `abandonMySessions tracks Quick Build ownership across restarts and excludes staging or active Standard Run sessions`() = + runTest { + val apk = tempFolder.newFile("staging.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = mutableSetOf() + var nextId = 200 + + val installer = mockk() + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + var sweepDuringStaging = false + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } answers { + if (sweepDuringStaging) { + // Simulate Quick Build's startup sweep running WHILE Standard Run is actively + // staging APK bytes (after createSession, before session.commit). + ApkInstaller.abandonMySessions(context) + } + ByteArrayOutputStream() + } + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + every { installer.createSession(any()) } answers { + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + // 1. Create a Quick Build session (200) before Standard Run starts. + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val firstQuickBuild = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(firstQuickBuild).isEqualTo(ApkInstaller.SessionLaunchResult.Started(200)) + assertThat(activeSessions).containsExactly(200) + + // 2. Start a Standard Run install (201) whose openWrite triggers a Quick Build sweep + // mid-staging: stale Quick Build session 200 is abandoned, while staging Standard Run + // session 201 is preserved. + sweepDuringStaging = true + val standardRunResult = ApkInstaller.installUsingSession(context, apk, Intent()) + sweepDuringStaging = false + assertThat(standardRunResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(201)) + assertThat(activeSessions).containsExactly(201) + + // 3. Create another Quick Build session (202) and an untracked non-Quick-Build session (203), + // then clear in-memory state to simulate an app process restart. + val secondQuickBuild = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(secondQuickBuild).isEqualTo(ApkInstaller.SessionLaunchResult.Started(202)) + activeSessions += 203 + assertThat(activeSessions).containsExactly(201, 202, 203) + + ApkInstaller.clearInMemorySessionsForTesting() + + // 4. After restart, startup sweep abandons only the persisted Quick Build session (202) + // and excludes both the persisted Standard Run session (201) and untracked session (203). + val sweptAfterRestart = ApkInstaller.abandonMySessions(context) + assertThat(sweptAfterRestart).isEqualTo(1) + assertThat(activeSessions).containsExactly(201, 203) + } + @Test fun `installUsingSession reports TooManySessions distinctly from Failed when cap remains full`() = runTest { diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index dd4442a487..62e4df30d3 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -272,8 +272,13 @@ class ProxyAppInstaller( return InstallOutcome.Installed(existingUid) } - runCatching { sweepStaleSessions() } - .onFailure { log.warn("failed to sweep stale install sessions before installing {}", packageName, it) } + try { + withContext(ioDispatcher) { sweepStaleSessions() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("failed to sweep stale install sessions before installing {}", packageName, e) + } return coroutineScope { // Set when the OS reported PENDING_USER_ACTION, which means a confirm dialog diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt index 6a7389ace2..e9965a25e1 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt @@ -1,6 +1,7 @@ package org.appdevforall.cotg.quickbuild.service.session import android.content.ComponentCallbacks2 +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope @@ -159,8 +160,9 @@ class QuickBuildSessionManager( */ private val assetsLiveReloadable: Boolean = true, /** - * Sweeps stale PackageInstaller sessions owned by CoGo at Quick Build startup so an - * already-capped phone (MAX_ACTIVE_SESSIONS = 50) recovers without clearing app data. + * Sweeps stale Quick Build PackageInstaller sessions at Quick Build startup (excluding any + * active Standard Run or `InstallFileAction` install sessions) so an already-capped phone + * (MAX_ACTIVE_SESSIONS = 50) recovers without clearing app data. */ private val sweepInstallSessions: () -> Unit = {}, ) { @@ -466,17 +468,23 @@ class QuickBuildSessionManager( } /** - * The stale-tree and stale-install-session sweep. Nothing is live at construction - this - * manager is the process's only session owner - so every tree under the scratch root and - * every active PackageInstaller session belongs to a dead session or a deleted project. + * The stale-tree and stale-install-session sweep. No Quick Build session is live at + * construction - this manager is the process's only Quick Build session owner - so every + * tree under the scratch root and every stale Quick Build PackageInstaller session + * (excluding any active Standard Run or `InstallFileAction` install) can be reclaimed. * Launched before any tap can dispatch, but sweep() hops to IO and frees the dispatcher, * so [provision] joins it rather than trusting the launch order: a prepare that overtook * it would have its fresh tree swept as stale. */ private val sweepJob = scope.launch { - runCatching { withContext(ioDispatcher) { sweepInstallSessions() } } - .onFailure { log.warn("Could not sweep stale PackageInstaller sessions at startup", it) } + try { + withContext(ioDispatcher) { sweepInstallSessions() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Could not sweep stale PackageInstaller sessions at startup", e) + } scratch.sweep() } diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index a91c689a82..133de6c43e 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -964,6 +964,13 @@ class ProxyAppInstallerTest { promptTimeoutMillis = 45_000L, launchSession = { val id = nextId++ + if (id == 401) { + // Delayed ABORTED for the swept session arrives after the broadcast + // collector is subscribed and while activeSessionId is still null. + broadcasts.tryEmit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 400), + ) + } InstallLaunchResult.Started(id) }, onAbandon = { id -> @@ -976,12 +983,9 @@ class ProxyAppInstallerTest { }, onSweep = { sweepCount++ - // Sweep records and abandons a pre-existing committed session (400) - // before activeSessionId is assigned. + // Sweep records a pre-existing committed session (400) before + // activeSessionId is assigned. installerUnderTest.recordAbandonedSession(400) - broadcasts.tryEmit( - InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 400), - ) }, ) From 940e008ded4a595dd5775a2e182a31cb60ff21de Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 12 Nov 2026 16:10:40 +0100 Subject: [PATCH 09/14] fix(ADFA-5438): Fail immediately when prompt-timeout re-issue does not start --- .../service/provision/ProxyAppInstaller.kt | 67 +++++--- .../provision/ProxyAppInstallerTest.kt | 149 ++++++++++++++++++ 2 files changed, 195 insertions(+), 21 deletions(-) diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index 62e4df30d3..d9e54e6081 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -4,6 +4,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay @@ -404,30 +405,50 @@ class ProxyAppInstaller( activeSessionId.get()?.let { staleSessionId -> abandonedSessionIds.add(staleSessionId) activeSessionId.set(null) - abandonSessionSafely(staleSessionId) + withContext(ioDispatcher + NonCancellable) { + abandonSessionSafely(staleSessionId) + } launchedSessionIds.remove(staleSessionId) } - try { - when (val reissued = launchInstallSession(apk)) { - is InstallLaunchResult.Started -> { - reissued.sessionId?.let { sessionId -> - abandonedSessionIds.remove(sessionId) - activeSessionId.set(sessionId) - launchedSessionIds.add(sessionId) - } + val reissued = + try { + launchInstallSession(apk) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("could not re-issue the install of {}", packageName, e) + InstallLaunchResult.Failed + } + when (reissued) { + is InstallLaunchResult.Started -> { + reissued.sessionId?.let { sessionId -> + abandonedSessionIds.remove(sessionId) + activeSessionId.set(sessionId) + launchedSessionIds.add(sessionId) } + } - InstallLaunchResult.TooManySessions, - InstallLaunchResult.Failed, - -> { - log.warn("re-issued install of {} did not start: {}", packageName, reissued) - } + InstallLaunchResult.TooManySessions -> { + log.warn( + "re-issued install of {} from {} hit PackageInstaller session limit; reporting TooManyInstallSessions", + packageName, + apk, + ) + return@run Verdict.Settled( + InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions), + ) + } + + InstallLaunchResult.Failed -> { + log.warn( + "re-issued install of {} from {} did not start; reporting InstallCouldNotStart", + packageName, + apk, + ) + return@run Verdict.Settled( + InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart), + ) } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // Keep waiting on the remaining budget. - log.error("could not re-issue the install of {}", packageName, e) } } awaitVerdict() @@ -445,8 +466,12 @@ class ProxyAppInstaller( is Verdict.Settled -> outcome.outcome } } finally { - for (sessionId in launchedSessionIds) { - abandonSessionSafely(sessionId) + if (launchedSessionIds.isNotEmpty()) { + withContext(ioDispatcher + NonCancellable) { + for (sessionId in launchedSessionIds) { + abandonSessionSafely(sessionId) + } + } } } } diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index 133de6c43e..3b09ba626e 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -1008,4 +1008,153 @@ class ProxyAppInstallerTest { assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) assertThat(abandonedSessionIds).containsExactly(401, 402).inOrder() } + + @Test + fun `re-issue returning Failed fails immediately with InstallCouldNotStart instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(501) + } else { + InstallLaunchResult.Failed + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + advanceTimeBy(45_001L) + runCurrent() + + // Must fail immediately after re-issue without waiting out the remaining 75s budget. + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + assertThat(abandonedSessionIds).containsExactly(501) + } + + @Test + fun `re-issue returning TooManySessions fails immediately with TooManyInstallSessions instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(502) + } else { + InstallLaunchResult.TooManySessions + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + advanceTimeBy(45_001L) + runCurrent() + + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions)) + assertThat(abandonedSessionIds).containsExactly(502) + } + + @Test + fun `re-issue throwing fails immediately with InstallCouldNotStart instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(503) + } else { + error("boom during re-issue") + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + advanceTimeBy(45_001L) + runCurrent() + + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + assertThat(abandonedSessionIds).containsExactly(503) + } + + @Test + fun `re-issue and finally abandonSession calls dispatch through ioDispatcher`() = + runTest { + val abandonedOnIoDispatcher = mutableListOf() + val inIoDispatcher = + java.util.concurrent.atomic + .AtomicBoolean(false) + val delegate = StandardTestDispatcher(testScheduler) + val trackingIoDispatcher = + object : kotlinx.coroutines.CoroutineDispatcher() { + override fun isDispatchNeeded(context: kotlin.coroutines.CoroutineContext): Boolean = true + + override fun dispatch( + context: kotlin.coroutines.CoroutineContext, + block: Runnable, + ) { + delegate.dispatch(context) { + val prev = inIoDispatcher.getAndSet(true) + try { + block.run() + } finally { + inIoDispatcher.set(prev) + } + } + } + } + var nextId = 601 + val installerUnderTest = + ProxyAppInstaller( + packages = packages, + broadcasts = broadcasts, + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + canShowConfirmDialog = { true }, + launchInstallSession = { InstallLaunchResult.Started(nextId++) }, + abandonSession = { id -> + abandonedSessionIds += id + abandonedOnIoDispatcher += inIoDispatcher.get() + }, + sweepStaleSessions = { sweepCount++ }, + ioDispatcher = trackingIoDispatcher, + ) + + val result = async { installerUnderTest.ensureInstalled(apk, PKG) } + runCurrent() + + // Trigger prompt-timeout re-issue (abandons 601 on ioDispatcher). + advanceTimeBy(45_001L) + runCurrent() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 602)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(601, 602).inOrder() + assertThat(abandonedOnIoDispatcher).containsExactly(true, true) + } } From 9176e026cc72e3a38aeb8399f612c6cc3d089af0 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 12 Nov 2026 16:11:13 +0100 Subject: [PATCH 10/14] fix(ADFA-5438): Sweep orphaned persisted user sessions --- .../itsaky/androidide/utils/ApkInstaller.kt | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 24585e0bf5..b52bdb2a79 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -49,6 +49,14 @@ object ApkInstaller { private val inFlightUserSessionIds: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) + /** + * Session IDs of active Standard Run or `InstallFileAction` installs created in the current + * process (never loaded from `SharedPreferences`). Even when the 50-session cap is reached, + * these belong to a live install in this process and are never swept. + */ + private val liveInFlightUserSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + /** * Boolean extra riding the install callback intent: on STATUS_SUCCESS, do not run the * launch-after-install behavior for this package. @@ -181,6 +189,7 @@ object ApkInstaller { installer: PackageInstaller, sessionId: Int, ): Boolean { + liveInFlightUserSessionIds.remove(sessionId) inFlightUserSessionIds.remove(sessionId) quickBuildSessionIds.remove(sessionId) return runCatching { @@ -214,6 +223,7 @@ object ApkInstaller { * between unit tests. */ internal fun clearInFlightUserSessionsForTesting(context: Context? = null) { + liveInFlightUserSessionIds.clear() inFlightUserSessionIds.clear() quickBuildSessionIds.clear() if (context != null) { @@ -233,6 +243,7 @@ object ApkInstaller { * while keeping `SharedPreferences` state intact. */ internal fun clearInMemorySessionsForTesting() { + liveInFlightUserSessionIds.clear() inFlightUserSessionIds.clear() quickBuildSessionIds.clear() } @@ -242,6 +253,7 @@ object ApkInstaller { sessionId: Int, ) { loadPersistedSessions(context) + liveInFlightUserSessionIds.remove(sessionId) inFlightUserSessionIds.remove(sessionId) quickBuildSessionIds.add(sessionId) persistTrackedSessions(context) @@ -253,6 +265,7 @@ object ApkInstaller { ) { loadPersistedSessions(context) quickBuildSessionIds.remove(sessionId) + liveInFlightUserSessionIds.add(sessionId) inFlightUserSessionIds.add(sessionId) persistTrackedSessions(context) } @@ -264,6 +277,7 @@ object ApkInstaller { if (context != null) { loadPersistedSessions(context) } + liveInFlightUserSessionIds.remove(sessionId) val removedUser = inFlightUserSessionIds.remove(sessionId) val removedQb = quickBuildSessionIds.remove(sessionId) if (context != null && (removedUser || removedQb)) { @@ -350,6 +364,7 @@ object ApkInstaller { ?: return 0 val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } + liveInFlightUserSessionIds.retainAll(activeIds) inFlightUserSessionIds.retainAll(activeIds) quickBuildSessionIds.retainAll(activeIds) @@ -357,7 +372,10 @@ object ApkInstaller { var abandoned = 0 for (info in sessions) { val id = info.sessionId - if (id in inFlightUserSessionIds) { + if (id in liveInFlightUserSessionIds) { + continue + } + if (id in inFlightUserSessionIds && !isAtSessionCap) { continue } if (id !in quickBuildSessionIds && !isAtSessionCap) { From 3fe68c6130d642c8a0a6b2f583ed7637ba6b8918 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 12 Nov 2026 16:12:25 +0100 Subject: [PATCH 11/14] fix(ADFA-5438): Drop unnecessary flag --- .../com/itsaky/androidide/utils/InstallationResultHandler.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt index 69953467af..fba284e0b5 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt @@ -66,7 +66,9 @@ object InstallationResultHandler { @Suppress("DEPRECATION") extras.get(Intent.EXTRA_INTENT)?.let { intent -> if (intent is Intent) { - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) + if ((intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK) != Intent.FLAG_ACTIVITY_NEW_TASK) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } log.debug("startingActivity: intent={}, intent.extras={}", intent, intent.extras) context.startActivity(intent) } From 270fe87ec4459c8d8c2b2587f032168d7e173679 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 12 Nov 2026 16:13:07 +0100 Subject: [PATCH 12/14] test(ADFA-5438): Add unit tests --- .../utils/ApkInstallerSessionTest.kt | 57 +++++++++++++++++++ ...allationResultHandlerSuppressLaunchTest.kt | 1 - 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index 0f78f1eca9..2f332864a6 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -225,4 +225,61 @@ class ApkInstallerSessionTest { assertThat(capResult).isEqualTo(ApkInstaller.SessionLaunchResult.TooManySessions) assertThat(genericResult).isEqualTo(ApkInstaller.SessionLaunchResult.Failed) } + + @Test + fun `abandonMySessions at 50-session cap sweeps persisted user sessions from dead process but preserves live ones`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = mutableListOf() + + fun sessionInfo(id: Int): PackageInstaller.SessionInfo = + mockk().apply { + every { sessionId } returns id + } + + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } answers { java.io.ByteArrayOutputStream() } + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + val installer = mockk() + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + var nextId = 1 + every { installer.createSession(any()) } answers { + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + // 1. Standard Run session (1) from a previous process, persisted before restart. + val deadProcessSession = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(deadProcessSession).isEqualTo(ApkInstaller.SessionLaunchResult.Started(1)) + ApkInstaller.clearInMemorySessionsForTesting() + + // 2. Fill up to 49 sessions with untracked sessions, then start a live Standard Run (50). + for (id in 2..49) { + activeSessions += id + } + nextId = 50 + val liveSession = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(liveSession).isEqualTo(ApkInstaller.SessionLaunchResult.Started(50)) + assertThat(activeSessions).hasSize(50) + + // 3. At the 50-session cap, sweep abandons the persisted dead-process session (1) and + // untracked sessions (2..49), while preserving the live Standard Run session (50). + val swept = ApkInstaller.abandonMySessions(context) + assertThat(swept).isEqualTo(49) + assertThat(activeSessions).containsExactly(50) + } } diff --git a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt index b7321c3c73..b0ec2d2d7a 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt @@ -89,6 +89,5 @@ class InstallationResultHandlerSuppressLaunchTest { assertThat(started).isNotNull() assertThat(started.action).isEqualTo("com.android.packageinstaller.CONFIRM") assertThat(started.flags and Intent.FLAG_ACTIVITY_NEW_TASK).isEqualTo(Intent.FLAG_ACTIVITY_NEW_TASK) - assertThat(started.flags and Intent.FLAG_ACTIVITY_CLEAR_TOP).isEqualTo(Intent.FLAG_ACTIVITY_CLEAR_TOP) } } From a1ed677b61f734a1d0b1fb34fbbb2aa36b89b2a3 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Fri, 13 Nov 2026 14:15:03 +0100 Subject: [PATCH 13/14] fix(ADFA-5438): Handle thread blokcing operations --- .../itsaky/androidide/utils/ApkInstaller.kt | 112 ++++++----- .../utils/InstallationResultHandler.kt | 2 - .../service/provision/ProxyAppInstaller.kt | 186 ++++++++++++------ .../provision/ProxyAppInstallerTest.kt | 56 ++++++ 4 files changed, 242 insertions(+), 114 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index b52bdb2a79..6043b56d2e 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -57,6 +57,8 @@ object ApkInstaller { private val liveInFlightUserSessionIds: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) + private val sessionTrackingLock = Any() + /** * Boolean extra riding the install callback intent: on STATUS_SUCCESS, do not run the * launch-after-install behavior for this package. @@ -188,16 +190,17 @@ object ApkInstaller { internal fun abandonSession( installer: PackageInstaller, sessionId: Int, - ): Boolean { - liveInFlightUserSessionIds.remove(sessionId) - inFlightUserSessionIds.remove(sessionId) - quickBuildSessionIds.remove(sessionId) - return runCatching { - installer.abandonSession(sessionId) - }.onFailure { error -> - log.debug("Session {} already finalized or could not be abandoned", sessionId, error) - }.isSuccess - } + ): Boolean = + synchronized(sessionTrackingLock) { + liveInFlightUserSessionIds.remove(sessionId) + inFlightUserSessionIds.remove(sessionId) + quickBuildSessionIds.remove(sessionId) + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + } /** * Records a status broadcast from [InstallationResultReceiver] so any session that reaches @@ -251,7 +254,7 @@ object ApkInstaller { private fun recordQuickBuildSession( context: Context, sessionId: Int, - ) { + ) = synchronized(sessionTrackingLock) { loadPersistedSessions(context) liveInFlightUserSessionIds.remove(sessionId) inFlightUserSessionIds.remove(sessionId) @@ -262,7 +265,7 @@ object ApkInstaller { private fun recordInFlightUserSession( context: Context, sessionId: Int, - ) { + ) = synchronized(sessionTrackingLock) { loadPersistedSessions(context) quickBuildSessionIds.remove(sessionId) liveInFlightUserSessionIds.add(sessionId) @@ -273,7 +276,7 @@ object ApkInstaller { private fun removeTrackedSession( context: Context?, sessionId: Int, - ) { + ) = synchronized(sessionTrackingLock) { if (context != null) { loadPersistedSessions(context) } @@ -314,7 +317,7 @@ object ApkInstaller { .edit() .putStringSet(KEY_IN_FLIGHT_USER_SESSIONS, userSnapshot) .putStringSet(KEY_QUICK_BUILD_SESSIONS, qbSnapshot) - .commit() + .apply() }.onFailure { error -> log.debug("Unable to persist installer session IDs", error) } @@ -356,41 +359,42 @@ object ApkInstaller { internal fun abandonMySessions( installer: PackageInstaller, onBeforeAbandon: (Int) -> Unit = {}, - ): Int { - val sessions = - runCatching { installer.mySessions } - .onFailure { error -> log.warn("Failed to query existing PackageInstaller sessions", error) } - .getOrNull() - ?: return 0 - - val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } - liveInFlightUserSessionIds.retainAll(activeIds) - inFlightUserSessionIds.retainAll(activeIds) - quickBuildSessionIds.retainAll(activeIds) - - val isAtSessionCap = sessions.size >= MAX_ACTIVE_SESSIONS - var abandoned = 0 - for (info in sessions) { - val id = info.sessionId - if (id in liveInFlightUserSessionIds) { - continue - } - if (id in inFlightUserSessionIds && !isAtSessionCap) { - continue - } - if (id !in quickBuildSessionIds && !isAtSessionCap) { - continue + ): Int = + synchronized(sessionTrackingLock) { + val sessions = + runCatching { installer.mySessions } + .onFailure { error -> log.warn("Failed to query existing PackageInstaller sessions", error) } + .getOrNull() + ?: return 0 + + val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } + liveInFlightUserSessionIds.retainAll(activeIds) + inFlightUserSessionIds.retainAll(activeIds) + quickBuildSessionIds.retainAll(activeIds) + + val isAtSessionCap = sessions.size >= MAX_ACTIVE_SESSIONS + var abandoned = 0 + for (info in sessions) { + val id = info.sessionId + if (id in liveInFlightUserSessionIds) { + continue + } + if (id in inFlightUserSessionIds && !isAtSessionCap) { + continue + } + if (id !in quickBuildSessionIds && !isAtSessionCap) { + continue + } + runCatching { onBeforeAbandon(id) } + if (abandonSession(installer, id)) { + abandoned++ + } } - runCatching { onBeforeAbandon(id) } - if (abandonSession(installer, id)) { - abandoned++ + if (abandoned > 0) { + log.info("Abandoned {} stale PackageInstaller session(s)", abandoned) } + abandoned } - if (abandoned > 0) { - log.info("Abandoned {} stale PackageInstaller session(s)", abandoned) - } - return abandoned - } /** * Launches a fallback `ACTION_INSTALL_PACKAGE` activity intent for devices where @@ -432,12 +436,16 @@ object ApkInstaller { return runCatching { withContext(Dispatchers.IO) { - val sessionId = installer.createSession(params) - if (isQuickBuildInstall) { - recordQuickBuildSession(context, sessionId) - } else { - recordInFlightUserSession(context, sessionId) - } + val sessionId = + synchronized(sessionTrackingLock) { + val id = installer.createSession(params) + if (isQuickBuildInstall) { + recordQuickBuildSession(context, id) + } else { + recordInFlightUserSession(context, id) + } + id + } var session: PackageInstaller.Session? = null try { diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt index fba284e0b5..e5420a4234 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallationResultHandler.kt @@ -58,8 +58,6 @@ object InstallationResultHandler { val status = extras.getInt(PackageInstaller.EXTRA_STATUS) val message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE) - ApkInstaller.onInstallStatusBroadcast(intent, context) - return when (status) { PackageInstaller.STATUS_PENDING_USER_ACTION -> { log.debug("PENDING_USER_ACTION: extras={}", extras) diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index d9e54e6081..995385c41d 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -1,6 +1,7 @@ package org.appdevforall.cotg.quickbuild.service.provision import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers @@ -9,7 +10,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull @@ -289,49 +290,110 @@ class ProxyAppInstaller( val pendingUserActionSeen = AtomicBoolean(false) val activeSessionId = AtomicReference(null) val launchedSessionIds = Collections.newSetFromMap(ConcurrentHashMap()) + val stateLock = Any() + var expectedSession: ExpectedSession = ExpectedSession.AwaitingLaunch + val earlyBroadcasts = mutableListOf() + val verdictDeferred = CompletableDeferred() + + fun isBroadcastDecisive(broadcast: InstallBroadcast): Boolean = + broadcast.isTerminal || + ( + broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && + !canShowConfirmDialog() + ) + + fun matchesExpectedSession( + broadcast: InstallBroadcast, + state: ExpectedSession, + ): Boolean { + val packageMatches = broadcast.packageName == null || broadcast.packageName == packageName + if (!packageMatches) return false + return when (state) { + is ExpectedSession.AwaitingLaunch -> { + false + } - try { - // Subscribe before committing the install so a fast broadcast cannot slip - // past us. PENDING_USER_ACTION is decisive too when no confirm dialog can be - // launched, since nobody will ever tap. - val verdict = - async(start = CoroutineStart.UNDISPATCHED) { - try { - Result.success( - broadcasts.first { broadcast -> - val currentSessionId = activeSessionId.get() - val sessionMatches = - broadcast.sessionId?.let { it in abandonedSessionIds } != true && - ( - currentSessionId == null || - broadcast.sessionId == null || - broadcast.sessionId == currentSessionId - ) - val packageMatches = - broadcast.packageName == null || broadcast.packageName == packageName - val ours = sessionMatches && packageMatches - if (ours && broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { - pendingUserActionSeen.set(true) - } - ours && - ( - broadcast.isTerminal || - ( - broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && - !canShowConfirmDialog() - ) - ) - }, - ) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // If the flow completes without a match, first() throws and no - // verdict can arrive this way. Captured as a failure so that - // ensureInstalled still never throws. - Result.failure(e) + is ExpectedSession.Session -> { + broadcast.sessionId == state.id && state.id !in abandonedSessionIds + } + + is ExpectedSession.FallbackWithoutSession -> { + broadcast.sessionId == null + } + } + } + + fun handleMatchingBroadcast(broadcast: InstallBroadcast) { + if (broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { + pendingUserActionSeen.set(true) + } + if (isBroadcastDecisive(broadcast)) { + verdictDeferred.complete(classify(broadcast)) + } + } + + fun onLaunchStarted(launchResult: InstallLaunchResult.Started) { + synchronized(stateLock) { + val sessionId = launchResult.sessionId + val state = + if (sessionId != null) { + abandonedSessionIds.remove(sessionId) + activeSessionId.set(sessionId) + launchedSessionIds.add(sessionId) + ExpectedSession.Session(sessionId) + } else { + activeSessionId.set(null) + ExpectedSession.FallbackWithoutSession + } + expectedSession = state + val iterator = earlyBroadcasts.iterator() + while (iterator.hasNext()) { + val broadcast = iterator.next() + iterator.remove() + if (matchesExpectedSession(broadcast, state)) { + handleMatchingBroadcast(broadcast) + if (verdictDeferred.isCompleted) { + break + } + } + } + } + } + + val collector = + launch(start = CoroutineStart.UNDISPATCHED) { + try { + broadcasts.collect { broadcast -> + synchronized(stateLock) { + if (verdictDeferred.isCompleted) return@collect + val state = expectedSession + if (state is ExpectedSession.AwaitingLaunch) { + earlyBroadcasts.add(broadcast) + } else if (matchesExpectedSession(broadcast, state)) { + handleMatchingBroadcast(broadcast) + } + } + } + // If the flow completes without a match, complete as Failed so that + // ensureInstalled still never throws or hangs indefinitely. + synchronized(stateLock) { + if (!verdictDeferred.isCompleted) { + verdictDeferred.complete( + Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)), + ) + } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("broadcast collector failed", e) + verdictDeferred.complete( + Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)), + ) } + } + + try { val stampChanged = async { awaitStampChange(packageName, initialStamp) } val launchResult = @@ -345,11 +407,7 @@ class ProxyAppInstaller( } when (launchResult) { is InstallLaunchResult.Started -> { - launchResult.sessionId?.let { sessionId -> - abandonedSessionIds.remove(sessionId) - activeSessionId.set(sessionId) - launchedSessionIds.add(sessionId) - } + onLaunchStarted(launchResult) } InstallLaunchResult.TooManySessions -> { @@ -358,14 +416,16 @@ class ProxyAppInstaller( packageName, apk, ) - verdict.cancel() + collector.cancel() + verdictDeferred.cancel() stampChanged.cancel() return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions) } InstallLaunchResult.Failed -> { log.warn("install of {} from {} did not start; reporting InstallCouldNotStart", packageName, apk) - verdict.cancel() + collector.cancel() + verdictDeferred.cancel() stampChanged.cancel() return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) } @@ -373,12 +433,7 @@ class ProxyAppInstaller( val awaitVerdict: suspend () -> Verdict = { select { - verdict.onAwait { result -> - result.fold( - onSuccess = { broadcast -> classify(broadcast) }, - onFailure = { Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)) }, - ) - } + verdictDeferred.onAwait { it } stampChanged.onAwait { Verdict.InstalledPendingUid } } } @@ -410,6 +465,10 @@ class ProxyAppInstaller( } launchedSessionIds.remove(staleSessionId) } + synchronized(stateLock) { + expectedSession = ExpectedSession.AwaitingLaunch + earlyBroadcasts.clear() + } val reissued = try { launchInstallSession(apk) @@ -421,11 +480,7 @@ class ProxyAppInstaller( } when (reissued) { is InstallLaunchResult.Started -> { - reissued.sessionId?.let { sessionId -> - abandonedSessionIds.remove(sessionId) - activeSessionId.set(sessionId) - launchedSessionIds.add(sessionId) - } + onLaunchStarted(reissued) } InstallLaunchResult.TooManySessions -> { @@ -454,7 +509,8 @@ class ProxyAppInstaller( awaitVerdict() } } - verdict.cancel() + collector.cancel() + verdictDeferred.cancel() stampChanged.cancel() // The uid is resolved here, OUTSIDE both timeout windows. It retries over // PackageManager's post-install lag, and inside the prompt budget a plain SUCCESS @@ -487,6 +543,16 @@ class ProxyAppInstaller( .onFailure { log.warn("failed to abandon install session {}", sessionId, it) } } + private sealed interface ExpectedSession { + data object AwaitingLaunch : ExpectedSession + + data class Session( + val id: Int, + ) : ExpectedSession + + data object FallbackWithoutSession : ExpectedSession + } + /** * What one wait for an install verdict produced, before the uid read. * diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index 3b09ba626e..7fef6713a5 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -1157,4 +1157,60 @@ class ProxyAppInstallerTest { assertThat(abandonedSessionIds).containsExactly(601, 602).inOrder() assertThat(abandonedOnIoDispatcher).containsExactly(true, true) } + + @Test + fun `broadcasts from unrelated sessions while launchInstallSession is running are not matched`() = + runTest { + val result = + async { + sessionInstaller( + launchSession = { + // While launchInstallSession is running for session 302, an unrelated session 301 + // emits ABORTED. This must not match session 302 or fail the install as DECLINED. + broadcasts.emit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 301), + ) + InstallLaunchResult.Started(302) + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Session 302 succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 302)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(302) + } + + @Test + fun `early broadcast for the launched session emitted during launch is buffered and matched`() = + runTest { + val result = + async { + sessionInstaller( + launchSession = { + // Early PENDING_USER_ACTION arrives for session 303 before launchInstallSession returns. + broadcasts.emit( + InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 303), + ) + InstallLaunchResult.Started(303) + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 303)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(303) + } } From 5afa2800bbda4c8bf4324f65404ae2673d779337 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Fri, 13 Nov 2026 15:44:09 +0100 Subject: [PATCH 14/14] fix(ADFA-5438): Retain tracking on failed abandonment --- .../itsaky/androidide/utils/ApkInstaller.kt | 56 ++++++++++++--- .../utils/ApkInstallerSessionTest.kt | 71 +++++++++++++++++++ 2 files changed, 116 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 6043b56d2e..ce7d347bc8 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -179,28 +179,62 @@ object ApkInstaller { context: Context, sessionId: Int, ): Boolean { - removeTrackedSession(context, sessionId) - return abandonSession(context.packageManager.packageInstaller, sessionId) + val installer = context.packageManager.packageInstaller + return synchronized(sessionTrackingLock) { + var abandonError: Throwable? = null + val abandoned = + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + abandonError = error + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + if (abandoned || isSessionFinalized(installer, sessionId, abandonError)) { + removeTrackedSession(context, sessionId) + } + abandoned + } } /** * Abandons [sessionId] on [installer], returning `true` if `abandonSession` succeeded and - * `false` if the session was already finalized or no longer exists. + * `false` if the session was already finalized or could not be abandoned. */ internal fun abandonSession( installer: PackageInstaller, sessionId: Int, ): Boolean = synchronized(sessionTrackingLock) { - liveInFlightUserSessionIds.remove(sessionId) - inFlightUserSessionIds.remove(sessionId) - quickBuildSessionIds.remove(sessionId) - runCatching { - installer.abandonSession(sessionId) - }.onFailure { error -> - log.debug("Session {} already finalized or could not be abandoned", sessionId, error) - }.isSuccess + var abandonError: Throwable? = null + val abandoned = + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + abandonError = error + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + if (abandoned || isSessionFinalized(installer, sessionId, abandonError)) { + removeTrackedSession(context = null, sessionId = sessionId) + } + abandoned + } + + /** + * Returns `true` when [sessionId] is confirmed to no longer exist or have already been + * finalized in [installer]. + */ + internal fun isSessionFinalized( + installer: PackageInstaller, + sessionId: Int, + error: Throwable? = null, + ): Boolean { + if (error is SecurityException && error.message?.contains("finalized", ignoreCase = true) == true) { + return true } + return runCatching { + installer.getSessionInfo(sessionId) == null + }.getOrDefault(false) + } /** * Records a status broadcast from [InstallationResultReceiver] so any session that reaches diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index 2f332864a6..b3123637af 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -282,4 +282,75 @@ class ApkInstallerSessionTest { assertThat(swept).isEqualTo(49) assertThat(activeSessions).containsExactly(50) } + + @Test + fun `abandonSession retains tracking when abandonment throws and session is not finalized`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val installer = mockk() + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + + every { installer.createSession(any()) } returns 77 + every { installer.openSession(77) } returns session + every { installer.abandonSession(77) } throws RuntimeException("transient IPC binder failure") + every { installer.getSessionInfo(77) } returns sessionInfo(77) + every { installer.mySessions } returns listOf(sessionInfo(77)) + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val launch = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(launch).isEqualTo(ApkInstaller.SessionLaunchResult.Started(77)) + + val abandonedContext = ApkInstaller.abandonSession(context, 77) + assertThat(abandonedContext).isFalse() + + var sweptId: Int? = null + every { installer.abandonSession(77) } answers { + sweptId = 77 + } + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(1) + assertThat(sweptId).isEqualTo(77) + } + + @Test + fun `abandonSession removes tracking when abandonment throws but session is confirmed finalized`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val installer = mockk() + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + + every { installer.createSession(any()) } returns 88 + every { installer.openSession(88) } returns session + every { installer.abandonSession(88) } throws SecurityException("Session 88 already finalized") + every { installer.getSessionInfo(88) } returns null + every { installer.mySessions } returns listOf(sessionInfo(88)) + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + + val abandoned = ApkInstaller.abandonSession(context, 88) + assertThat(abandoned).isFalse() + + var sweepCalled = false + every { installer.abandonSession(88) } answers { sweepCalled = true } + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(0) + assertThat(sweepCalled).isFalse() + } }