Skip to content

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

fix(engine): show the actual backend, not the selected one

ExTvf3f7dfbd6694
diff --git a/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt b/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
index 7cf2555..ae6fc53 100644
--- a/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
+++ b/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
@@ -15,12 +15,14 @@
package com.excp.podroid.engine
import android.content.Context
+import com.excp.podroid.R
import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.PortForwardRule
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.avf.AvfCapabilities
import com.excp.podroid.engine.avf.AvfDiagnostics
import com.excp.podroid.engine.avf.AvfEngine
+import com.excp.podroid.engine.avf.AvfReport
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -71,7 +73,7 @@ class EngineHolder @Inject constructor(
// with a side-effect-free QEMU singleton (its ctor starts no VM) and replace
// it with the real pick once firstPick resolves. start() awaits firstPick
// before delegating, so the first Start can NEVER run the seed by mistake.
- private val firstPick: Deferred<VmEngine> =
+ private val firstPick: Deferred<PickResult> =
scope.async { pick(settings.getEngineSelectionSnapshot()) }
// start() runs on the Service's IO thread, not the holder scope, so the
@@ -84,6 +86,22 @@ class EngineHolder @Inject constructor(
val currentFlow: StateFlow<VmEngine> = _currentFlow.asStateFlow()
private val current: VmEngine get() = _currentFlow.value
+ /** Cosmetic mirror of [currentFlow]'s backendId, for UI surfaces that only
+ * need the id (not the whole engine) and want it as a StateFlow they can
+ * collect reactively instead of reading [VmEngine.backendId] once. */
+ val backendIdFlow: StateFlow<String> = _currentFlow
+ .map { it.backendId }
+ .stateIn(scope, SharingStarted.Eagerly, _currentFlow.value.backendId)
+
+ // Non-null only while the current pick is a forced-AVF selection that fell
+ // back to QEMU: a short, localized human reason (see FallbackReason /
+ // pick()). Updated at the same two points _currentFlow is (publishFirstPick,
+ // trySwap) so it always describes the pick that produced the active engine,
+ // even on a no-op swap where the engine instance doesn't change but the
+ // selection (and therefore the reason) does.
+ private val _backendFallback = MutableStateFlow<String?>(null)
+ val backendFallback: StateFlow<String?> = _backendFallback.asStateFlow()
+
/** Last rule set we pushed into the engine, used to compute add/remove diffs. */
@Volatile private var appliedRules: Set<PortForwardRule> = emptySet()
@@ -207,7 +225,11 @@ class EngineHolder @Inject constructor(
}
}
- private fun pick(sel: EngineSelection): VmEngine {
+ /** Result of a pick: the chosen engine plus, when a forced-AVF selection
+ * fell back to QEMU, a short localized reason for [backendFallback]. */
+ private data class PickResult(val engine: VmEngine, val fallbackMessage: String?)
+
+ private fun pick(sel: EngineSelection): PickResult {
val probe = AvfDiagnostics.probe(context)
val capsChoice = AvfCapabilities.choose(probe.capabilitiesRaw)
// avfUsable = AVF can actually start here. serviceReachable is the new
@@ -223,42 +245,52 @@ class EngineHolder @Inject constructor(
probe.serviceReachable &&
probe.customVmConfigSupported &&
capsChoice !is AvfCapabilities.ProtectedVmChoice.Unsupported
- return when {
- sel == EngineSelection.QEMU -> qemuProvider.get()
- // Forced AVF, but AVF can't run here → transparent QEMU fallback
- // instead of an Error state. Protected-only keeps its dedicated log.
- sel == EngineSelection.AVF && !avfUsable -> {
- if (capsChoice is AvfCapabilities.ProtectedVmChoice.Unsupported) {
- android.util.Log.w(
- TAG,
- "AVF forced but device is protected-only; falling back to QEMU. " +
- "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded})"
- )
- } else {
- android.util.Log.w(
- TAG,
- "AVF forced but unavailable; falling back to QEMU. " +
- "feature=${probe.featureSupported} " +
- "perms=${probe.managePermissionGranted}/${probe.customPermissionGranted} " +
- "reachable=${probe.serviceReachable} " +
- "customVm=${probe.customVmConfigSupported} " +
- "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded})"
- )
- }
- qemuProvider.get()
- }
- sel == EngineSelection.AVF -> avfProvider.get()
- avfUsable -> avfProvider.get()
- else -> qemuProvider.get()
- }.also {
- android.util.Log.i(
+ val protectedOnly = capsChoice is AvfCapabilities.ProtectedVmChoice.Unsupported
+ val (backendId, fallbackReason) = decideBackend(sel, avfUsable, protectedOnly)
+ // Logging unchanged from the old inline branch: protected-only keeps its
+ // dedicated message, everything else logs the full prerequisite dump.
+ when (fallbackReason) {
+ FallbackReason.PROTECTED_ONLY -> android.util.Log.w(
+ TAG,
+ "AVF forced but device is protected-only; falling back to QEMU. " +
+ "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded})"
+ )
+ FallbackReason.UNAVAILABLE -> android.util.Log.w(
TAG,
- "pick: selection=$sel feature=${probe.featureSupported} " +
+ "AVF forced but unavailable; falling back to QEMU. " +
+ "feature=${probe.featureSupported} " +
"perms=${probe.managePermissionGranted}/${probe.customPermissionGranted} " +
+ "reachable=${probe.serviceReachable} " +
"customVm=${probe.customVmConfigSupported} " +
- "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded}) → ${it.backendId}"
+ "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded})"
)
+ null -> {}
}
+ val engine = if (backendId == "avf") avfProvider.get() else qemuProvider.get()
+ android.util.Log.i(
+ TAG,
+ "pick: selection=$sel feature=${probe.featureSupported} " +
+ "perms=${probe.managePermissionGranted}/${probe.customPermissionGranted} " +
+ "customVm=${probe.customVmConfigSupported} " +
+ "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded}) → ${engine.backendId}"
+ )
+ val fallbackMessage = fallbackReason?.let { fallbackReasonText(it, probe) }
+ return PickResult(engine, fallbackMessage)
+ }
+
+ /** Short, localized reason for [backendFallback], reusing the same
+ * prerequisite checks the pick() log above already dumps: feature, then
+ * permissions, then service/custom-VM reachability, in that order - the
+ * first one that fails is reported. */
+ private fun fallbackReasonText(reason: FallbackReason, probe: AvfReport): String {
+ val resId = when {
+ reason == FallbackReason.PROTECTED_ONLY -> R.string.backend_fallback_reason_protected_only
+ !probe.featureSupported -> R.string.backend_fallback_reason_feature
+ !probe.managePermissionGranted || !probe.customPermissionGranted ->
+ R.string.backend_fallback_reason_permissions
+ else -> R.string.backend_fallback_reason_service
+ }
+ return context.getString(resId)
}
/**
@@ -269,8 +301,9 @@ class EngineHolder @Inject constructor(
* the sole writer thereafter — both run on the single-thread scope, so the
* flag check + write don't interleave.
*/
- private fun publishFirstPick(first: VmEngine) {
+ private fun publishFirstPick(result: PickResult) {
if (!firstPickPublished.compareAndSet(false, true)) return
+ val first = result.engine
if (first !== _currentFlow.value) {
android.util.Log.i(TAG, "first pick: ${_currentFlow.value.backendId} → ${first.backendId}")
// Fresh selection: this engine has not been started this cycle, so its
@@ -278,6 +311,7 @@ class EngineHolder @Inject constructor(
startedEngine = null
_currentFlow.value = first
}
+ _backendFallback.value = result.fallbackMessage
}
private suspend fun trySwap(newSel: EngineSelection) {
@@ -293,7 +327,12 @@ class EngineHolder @Inject constructor(
// when this swap fired — only possible if the user changed the backend
// within ~ms of cold launch) can never clobber the swapped engine.
firstPickPublished.set(true)
- val next = pick(newSel)
+ val result = pick(newSel)
+ // Update the surfaced reason even on a no-op engine swap: forcing AVF
+ // on an already-QEMU device changes the selection (and therefore the
+ // reason) without changing the engine instance.
+ _backendFallback.value = result.fallbackMessage
+ val next = result.engine
if (next === currentFlow.value) return
// NOTE: AvfEngine.stop() flips state to Stopped before cleanup() finishes
// (socket delete + coroutine cancel), so publishing `next` here can
@@ -366,7 +405,7 @@ class EngineHolder @Inject constructor(
} catch (e: Exception) {
android.util.Log.w(TAG, "first pick failed; recovering for start()", e)
runCatching { pick(settings.getEngineSelectionSnapshot()) }
- .getOrElse { _currentFlow.value }
+ .getOrElse { PickResult(_currentFlow.value, null) }
}
publishFirstPick(picked)
// Capture the launch set for the diff loop's →Running seeding, and mark
@@ -401,6 +440,35 @@ class EngineHolder @Inject constructor(
companion object {
private const val TAG = "EngineHolder"
+ /** Coarse reason a forced-AVF selection fell back to QEMU. Protected-only
+ * devices get their own value because pick() already logs them on a
+ * dedicated branch (a signed pvmfw kernel can never appear later). */
+ enum class FallbackReason { UNAVAILABLE, PROTECTED_ONLY }
+
+ /**
+ * Pure backend-selection decision, extracted from pick() so it's unit
+ * testable without a Context or a binder-IPC AVF probe. Mirrors pick()'s
+ * old inline `when` exactly - no change to which backend gets chosen,
+ * only which id/reason pair describes the choice. The fine-grained
+ * human reason (which prerequisite failed) is derived separately in
+ * pick() from the raw probe, since this function only sees the already-
+ * collapsed avfUsable/protectedOnly booleans.
+ */
+ fun decideBackend(
+ selection: EngineSelection,
+ avfUsable: Boolean,
+ protectedOnly: Boolean,
+ ): Pair<String, FallbackReason?> = when {
+ selection == EngineSelection.QEMU -> "qemu" to null
+ // Forced AVF, but AVF can't run here → transparent QEMU fallback
+ // instead of an Error state.
+ selection == EngineSelection.AVF && !avfUsable ->
+ "qemu" to (if (protectedOnly) FallbackReason.PROTECTED_ONLY else FallbackReason.UNAVAILABLE)
+ selection == EngineSelection.AVF -> "avf" to null
+ avfUsable -> "avf" to null
+ else -> "qemu" to null
+ }
+
/**
* Pure add/remove diff for the port-forward reconciliation loop:
* added = rules to push that aren't applied yet, removed = applied rules
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
index f215527..d7cb877 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
@@ -80,6 +80,7 @@ fun HomeScreen(
val meta by viewModel.meta.collectAsStateWithLifecycle()
val uptimeTick by viewModel.uptimeTicker.collectAsStateWithLifecycle()
val showAvfHint by viewModel.showAvfHint.collectAsStateWithLifecycle()
+ val showBackendFallbackBanner by viewModel.backendFallbackBanner.collectAsStateWithLifecycle()
val avfBootFailure by viewModel.avfBootFailure.collectAsStateWithLifecycle()
val avfFailureAdvice by viewModel.avfFailureAdvice.collectAsStateWithLifecycle()
val avfNetWorkaroundFailed by viewModel.avfNetWorkaroundFailed.collectAsStateWithLifecycle()
@@ -181,6 +182,9 @@ fun HomeScreen(
if (showAvfHint) {
AvfHintBanner(onDismiss = { viewModel.dismissAvfHint() })
}
+ if (showBackendFallbackBanner) {
+ AvfFallbackBanner()
+ }
HomeStatusBlock(
isStarting, isRunning, isStopping, vmState, bootStage, meta, uptimeLabel,
containerCount = containerCount,
@@ -227,6 +231,9 @@ fun HomeScreen(
if (showAvfHint) {
AvfHintBanner(onDismiss = { viewModel.dismissAvfHint() })
}
+ if (showBackendFallbackBanner) {
+ AvfFallbackBanner()
+ }
HomeStatusBlock(
isStarting = isStarting,
isRunning = isRunning,
@@ -304,6 +311,27 @@ private fun AvfHintBanner(onDismiss: () -> Unit) {
}
}
+/** Passive - no dismiss, no actions - just says why AVF (the selected
+ * backend) is not what's actually running. See #66. */
+@Composable
+private fun AvfFallbackBanner() {
+ Card(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(bottom = PodroidTokens.Spacing.MD),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.surfaceVariant,
+ ),
+ ) {
+ Text(
+ text = stringResource(R.string.backend_fallback_banner),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(PodroidTokens.Spacing.MD),
+ )
+ }
+}
+
@Composable
private fun HomeStatusBlock(
isStarting: Boolean,
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
index e5d1978..9358746 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
@@ -9,7 +9,7 @@ import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.data.repository.UpdateInfo
import com.excp.podroid.data.repository.UpdateRepository
-import com.excp.podroid.engine.VmEngine
+import com.excp.podroid.engine.EngineHolder
import com.excp.podroid.engine.VmState
import com.excp.podroid.service.PodroidService
import com.excp.podroid.util.NetworkUtils
@@ -54,7 +54,7 @@ data class HomeMeta(
@HiltViewModel
class HomeViewModel @Inject constructor(
@ApplicationContext private val context: Context,
- private val engine: VmEngine,
+ private val engine: EngineHolder,
private val settingsRepository: SettingsRepository,
private val portForwardRepository: PortForwardRepository,
private val containerStatsRepository: ContainerStatsRepository,
@@ -136,6 +136,16 @@ class HomeViewModel @Inject constructor(
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
+ /** True when AVF is selected but the current pick fell back to QEMU
+ * because this device can't run it. Passive - no actions, just tells the
+ * user why the VM isn't running on the backend they picked. See #66. */
+ val backendFallbackBanner: StateFlow<Boolean> = combine(
+ engine.backendFallback,
+ settingsRepository.engineSelection,
+ ) { fallback, sel ->
+ fallback != null && sel == com.excp.podroid.engine.EngineSelection.AVF
+ }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
+
/** True when AVF was the active backend and the VM ended in Error
* (boot failure / crash). Drives the actionable failure surface. */
val avfBootFailure: StateFlow<Boolean> = vmState
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
index 678469f..e35fc76 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
@@ -136,10 +136,13 @@ fun SettingsScreen(
val ctx = LocalContext.current
val vmNotRunning = vmState !is VmState.Running && vmState !is VmState.Starting
- // Memoize: both values are constant for the process lifetime / until a backend
- // swap, so there's no point re-running reflection on every recomposition.
- val isUsbPassthroughAvailable = remember { viewModel.isUsbPassthroughAvailable() }
- val activeBackendId = remember { viewModel.activeBackendId() }
+ // Reactive: a backend swap (or the async first pick resolving after this
+ // screen is already composed) must update the AVF diagnostic dialog and
+ // the USB row without a re-navigation. A `remember { }` with no key used
+ // to cache these forever, including a pre-first-pick QEMU seed (#66).
+ val activeBackendId by viewModel.activeBackendIdFlow.collectAsStateWithLifecycle()
+ val isUsbPassthroughAvailable = activeBackendId == "qemu"
+ val backendFallback by viewModel.backendFallback.collectAsStateWithLifecycle()
// Re-sync the persisted storageAccessEnabled flag against the real OS grant on
// every resume (user may have denied all-files-access on the system screen we
@@ -372,6 +375,18 @@ fun SettingsScreen(
)
}
}
+ // Annotate, don't disable: the user may grant AVF permissions
+ // later, so the chip stays selectable while explaining why the
+ // VM is actually running on QEMU right now.
+ if (ui.engineSelection == EngineSelection.AVF && backendFallback != null) {
+ Spacer(Modifier.height(PodroidTokens.Spacing.XS))
+ Text(
+ text = stringResource(R.string.backend_avf_unavailable, backendFallback ?: ""),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ modifier = Modifier.padding(horizontal = PodroidTokens.Spacing.MD),
+ )
+ }
Spacer(Modifier.height(PodroidTokens.Spacing.MD))
AdvancedFieldsBlock(
qemuExtraArgs = ui.qemuExtraArgs,
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
index 83f380c..95e1170 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
@@ -20,8 +20,8 @@ import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.PortForwardRule
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.di.ApplicationScope
+import com.excp.podroid.engine.EngineHolder
import com.excp.podroid.engine.EngineSelection
-import com.excp.podroid.engine.VmEngine
import com.excp.podroid.engine.VmState
import com.excp.podroid.util.DeviceResourcePolicy
import com.excp.podroid.util.NetworkUtils
@@ -72,7 +72,7 @@ class SettingsViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val settingsRepository: SettingsRepository,
private val portForwardRepository: PortForwardRepository,
- private val engine: VmEngine,
+ private val engine: EngineHolder,
private val languageManager: LanguageManager,
@ApplicationScope private val externalScope: CoroutineScope,
) : ViewModel() {
@@ -303,11 +303,16 @@ class SettingsViewModel @Inject constructor(
fun activeBackendId(): String = engine.backendId
/**
- * USB passthrough rides the QEMU QMP control socket (add-fd + device_add
- * usb-host); the AVF backend has no QMP channel, so it can never pass a
- * device through. QEMU-only.
+ * Reactive mirror of [activeBackendId] for the UI: a backend swap (or the
+ * async first pick resolving after this screen is already composed) must
+ * update the AVF diagnostic dialog and the USB row without the user having
+ * to leave and reopen Settings. See #66.
*/
- fun isUsbPassthroughAvailable(): Boolean = engine.backendId == "qemu"
+ val activeBackendIdFlow: StateFlow<String> = engine.backendIdFlow
+
+ /** Non-null when the current pick forced AVF but fell back to QEMU; a
+ * short localized reason for the Settings backend caption. See #66. */
+ val backendFallback: StateFlow<String?> = engine.backendFallback
private val _exportError = MutableStateFlow<String?>(null)
/** One-shot export failure message; clear after showing with [clearExportError]. */
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt
index b60abc2..36d96e5 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt
@@ -263,8 +263,13 @@ private fun vmStatusLabel(vmState: VmState, uptime: String?): String = when (vmS
}
@Composable
-private fun backendLabel(selection: EngineSelection, activeId: String): String = when (selection) {
- EngineSelection.AUTO -> "${stringResource(R.string.auto)} ($activeId)"
- EngineSelection.AVF -> stringResource(R.string.avf_kvm)
- EngineSelection.QEMU -> stringResource(R.string.qemu_tcg)
+private fun backendLabel(selection: EngineSelection, activeId: String): String {
+ val activeLabel = if (activeId == "avf") stringResource(R.string.avf_kvm) else stringResource(R.string.qemu_tcg)
+ return when (selection) {
+ EngineSelection.AUTO -> "${stringResource(R.string.auto)} ($activeId)"
+ // Forced AVF but the actual pick fell back to QEMU (device can't run
+ // AVF) - say so instead of claiming AVF is active.
+ EngineSelection.AVF -> if (activeId == "avf") activeLabel else activeLabel + stringResource(R.string.backend_fallback_suffix)
+ EngineSelection.QEMU -> activeLabel
+ }
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt
index e35c5a2..0f75de7 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt
@@ -5,8 +5,8 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.SettingsRepository
+import com.excp.podroid.engine.EngineHolder
import com.excp.podroid.engine.EngineSelection
-import com.excp.podroid.engine.VmEngine
import com.excp.podroid.engine.VmState
import com.excp.podroid.util.HostMetrics
import com.excp.podroid.util.HostMetricsSnapshot
@@ -59,7 +59,7 @@ data class StatusUiState(
@HiltViewModel
class StatusViewModel @Inject constructor(
@ApplicationContext private val context: Context,
- private val engine: VmEngine,
+ private val engine: EngineHolder,
private val settingsRepository: SettingsRepository,
private val portForwardRepository: PortForwardRepository,
) : ViewModel() {
@@ -97,12 +97,13 @@ class StatusViewModel @Inject constructor(
) { pct, history, unavailable ->
arrayOf(pct, history, unavailable)
},
- ) { a, b, c ->
+ engine.backendIdFlow,
+ ) { a, b, c, backendId ->
val vmState = a[0] as VmState
val tick = b[4] as Long
StatusUiState(
vmState = vmState,
- backendId = engine.backendId,
+ backendId = backendId,
engineSelection = b[1] as EngineSelection,
uptimeLabel = uptimeLabel(vmState, tick),
phoneIp = NetworkUtils.localIpv4(context),
diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml
index 2ca782e..fce1932 100644
--- a/app/src/main/res/values-zh/strings.xml
+++ b/app/src/main/res/values-zh/strings.xml
@@ -195,6 +195,15 @@
<string name="avf_hint_needs_pc">需要 PC 上的 adb,或设备上的 Shizuku 应用进行授权。运行一次:</string>
<string name="avf_grant_commands">adb shell pm grant com.excp.podroid \\\n android.permission.MANAGE_VIRTUAL_MACHINE\nadb shell pm grant com.excp.podroid \\\n android.permission.USE_CUSTOM_VIRTUAL_MACHINE</string>
+ <!-- Backend fallback (#66): AVF was forced but this device can't run it -->
+ <string name="backend_fallback_suffix">(AVF 不可用,正在使用 QEMU)</string>
+ <string name="backend_avf_unavailable">此设备无法使用 AVF:%1$s</string>
+ <string name="backend_fallback_banner">已选择 AVF,但此设备不可用。虚拟机正在使用 QEMU(软件模拟)运行。</string>
+ <string name="backend_fallback_reason_feature">虚拟化框架功能不受支持</string>
+ <string name="backend_fallback_reason_permissions">所需权限尚未授予</string>
+ <string name="backend_fallback_reason_service">系统服务不可达</string>
+ <string name="backend_fallback_reason_protected_only">此设备仅支持受保护虚拟机</string>
+
<!-- Setup Steps -->
<string name="step_1_of_4">第 1 步,共 4 步</string>
<string name="step_2_of_4">第 2 步,共 4 步</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 82162ee..92e4c2e 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -195,6 +195,15 @@
<string name="avf_hint_needs_pc">Needs a PC with adb, or the Shizuku app for on-device grant. Run once:</string>
<string name="avf_grant_commands">adb shell pm grant com.excp.podroid \\\n android.permission.MANAGE_VIRTUAL_MACHINE\nadb shell pm grant com.excp.podroid \\\n android.permission.USE_CUSTOM_VIRTUAL_MACHINE</string>
+ <!-- Backend fallback (#66): AVF was forced but this device can't run it -->
+ <string name="backend_fallback_suffix">" - AVF unavailable, running QEMU"</string>
+ <string name="backend_avf_unavailable">AVF is not available on this device: %1$s</string>
+ <string name="backend_fallback_banner">AVF was selected but is unavailable on this device. The VM is running on QEMU (software emulation).</string>
+ <string name="backend_fallback_reason_feature">the virtualization framework feature is not present</string>
+ <string name="backend_fallback_reason_permissions">required permissions have not been granted</string>
+ <string name="backend_fallback_reason_service">the system service is unreachable</string>
+ <string name="backend_fallback_reason_protected_only">this device only supports protected virtual machines</string>
+
<!-- Setup Steps -->
<string name="step_1_of_4">Step 1 of 4</string>
<string name="step_2_of_4">Step 2 of 4</string>
diff --git a/app/src/test/java/com/excp/podroid/engine/EngineHolderDecideBackendTest.kt b/app/src/test/java/com/excp/podroid/engine/EngineHolderDecideBackendTest.kt
new file mode 100644
index 0000000..3f17f76
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/EngineHolderDecideBackendTest.kt
@@ -0,0 +1,88 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.engine
+
+import com.excp.podroid.engine.EngineHolder.Companion.FallbackReason
+import com.excp.podroid.engine.EngineHolder.Companion.decideBackend
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * Pins the pure backend-selection decision extracted from EngineHolder.pick()
+ * (#66). The decision itself must never change here - only its exposure as a
+ * testable function - so these cases mirror pick()'s old inline `when`
+ * branch-for-branch.
+ */
+class EngineHolderDecideBackendTest {
+
+ @Test
+ fun `auto selection with usable AVF picks avf and no fallback`() {
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.AUTO,
+ avfUsable = true,
+ protectedOnly = false,
+ )
+ assertEquals("avf", backendId)
+ assertNull(reason)
+ }
+
+ @Test
+ fun `auto selection with unusable AVF picks qemu and no fallback`() {
+ // AUTO never surfaces a fallback reason: falling through to QEMU is the
+ // normal AUTO behavior, not a forced selection that failed.
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.AUTO,
+ avfUsable = false,
+ protectedOnly = false,
+ )
+ assertEquals("qemu", backendId)
+ assertNull(reason)
+ }
+
+ @Test
+ fun `forced avf with unusable AVF falls back to qemu with a reason`() {
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.AVF,
+ avfUsable = false,
+ protectedOnly = false,
+ )
+ assertEquals("qemu", backendId)
+ assertEquals(FallbackReason.UNAVAILABLE, reason)
+ }
+
+ @Test
+ fun `forced avf with usable AVF picks avf and no fallback`() {
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.AVF,
+ avfUsable = true,
+ protectedOnly = false,
+ )
+ assertEquals("avf", backendId)
+ assertNull(reason)
+ }
+
+ @Test
+ fun `forced qemu always picks qemu regardless of AVF usability`() {
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.QEMU,
+ avfUsable = true,
+ protectedOnly = true,
+ )
+ assertEquals("qemu", backendId)
+ assertNull(reason)
+ }
+
+ @Test
+ fun `forced avf on a protected-only device gets the protected-only reason`() {
+ val (backendId, reason) = decideBackend(
+ selection = EngineSelection.AVF,
+ avfUsable = false,
+ protectedOnly = true,
+ )
+ assertEquals("qemu", backendId)
+ assertEquals(FallbackReason.PROTECTED_ONLY, reason)
+ }
+}