Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

fix(service,engine): stop replayed terminal state from killing the next start

ExTvd248e5ef9b5b
diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
index 92f4403..208d241 100644
--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
@@ -418,6 +418,17 @@ class QemuEngine @Inject constructor(
exitCode == 0 -> VmState.Stopped
else -> VmState.Error(formatExitError(exitCode, config.storageAccessEnabled))
}
+ } catch (e: CancellationException) {
+ // The start() coroutine lives in PodroidService.serviceScope, which
+ // onDestroy() cancels on every stop/teardown. A stop destroys the
+ // process first (engine.stop() → proc.destroy()), so this cancellation
+ // IS the stop completing — finalize as a clean Stopped instead of
+ // mislabeling it Error("Job was cancelled"). A sticky Error here also
+ // poisoned the next start: its replayed value tore the new service
+ // down before the VM could boot. cleanup() is idempotent.
+ Log.d(TAG, "start() cancelled — finalizing as Stopped")
+ cleanup()
+ _state.value = VmState.Stopped
} catch (e: Exception) {
Log.e(TAG, "Failed to start QEMU", e)
_state.value = VmState.Error(e.message ?: "Unknown error")
diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
index e20dcb8..03b798f 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -202,7 +202,22 @@ class PodroidService : Service() {
*/
private suspend fun observeStateForShutdown() {
var seenActive = false
+ // The engine is a process-lifetime @Singleton, so its StateFlow replays
+ // the PRIOR cycle's retained terminal state (Stopped/Error) the instant
+ // this fresh collector subscribes — before the engine.start() that
+ // launchPodroid is about to run flips it to Starting. Acting on that
+ // replayed value would teardown (stopSelf → onDestroy → serviceScope
+ // .cancel) the very start we are kicking off, cancelling it as "Job was
+ // cancelled" and leaving a new stale Error that poisons the next attempt
+ // too — so the VM never restarts until the process is killed. Consume the
+ // first emission as a baseline; only act on transitions that follow it.
+ var baselineConsumed = false
engine.state.collect { state ->
+ if (!baselineConsumed) {
+ baselineConsumed = true
+ if (state is VmState.Starting || state is VmState.Running) seenActive = true
+ return@collect
+ }
when (state) {
is VmState.Starting, is VmState.Running -> seenActive = true
is VmState.Idle -> {