A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix(ui): screen lifecycle, port-forward dialog, and diagnostic export
ExTv59d4ad7adc76
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.ktindex 2b3e468..14f5eeb 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@@ -29,6 +29,7 @@ import androidx.compose.material3.windowsizeclass.WindowHeightSizeClassimport androidx.compose.material3.windowsizeclass.WindowSizeClassimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContext@@ -68,7 +69,9 @@ fun HomeScreen(val isRunning = vmState is VmState.Runningval isStarting = vmState is VmState.Startingval uptimeLabel = viewModel.uptimeLabel(uptimeTick)- val phoneIp = viewModel.phoneIp()+ // Bug 6: cache the result of the ConnectivityManager binder call so it doesn't+ // re-run on every 1 Hz tick or incidental recomposition.+ val phoneIp = remember { viewModel.phoneIp() }updateInfo?.let { info ->AlertDialog(@@ -78,7 +81,11 @@ fun HomeScreen(text = { Text("Version ${info.latestVersion} is available. You have ${BuildConfig.VERSION_NAME}.") },confirmButton = {TextButton(onClick = {- context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(info.releaseUrl)))+ // Bug 9: guard against ActivityNotFoundException (no browser) or a+ // blank/malformed releaseUrl from the remote JSON source.+ runCatching {+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(info.releaseUrl)))+ }viewModel.dismissUpdate()}) { Text("Download") }},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.ktindex 000ab53..680f296 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@@ -22,7 +22,9 @@ import kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.distinctUntilChangedimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.stateInimport kotlinx.coroutines.launch@@ -86,15 +88,21 @@ class HomeViewModel @Inject constructor(HomeMeta(ramMb = 512, cpus = 2, storageGb = 8, sshEnabled = false, portForwardCount = 0, lastBootDurationMs = 0L),)- // Ticker — drives uptime display refresh every second while running. The- // formatted label is computed synchronously by uptimeLabel(); this flow- // exists only to recompose the consumer once per second.- val uptimeTicker: StateFlow<Long> = flow {- while (true) {- emit(System.currentTimeMillis() / 1000)- delay(1000)+ // Ticker — drives uptime display refresh every second, but only while the VM+ // is Running. Gated via flatMapLatest on vmState so no ticks (and no HomeScreen+ // recompositions) happen while the VM is Idle/Starting/Stopped.+ val uptimeTicker: StateFlow<Long> = engine.state+ .map { it is VmState.Running }+ .distinctUntilChanged()+ .flatMapLatest { isRunning ->+ if (isRunning) flow {+ while (true) {+ emit(System.currentTimeMillis() / 1000)+ delay(1000)+ }+ } else flowOf(0L)}- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0L)+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0L)/** Phone IPv4 — cheap, lazily recomputed when the screen reads it. */fun phoneIp(): String = NetworkUtils.localIpv4(context)@@ -177,12 +185,17 @@ class HomeViewModel @Inject constructor(fun restartVm() {PodroidService.stop(context)viewModelScope.launch {- withTimeoutOrNull(10_000) {+ // Only start if we observed a terminal state within the timeout window.+ // A null result means QEMU is still tearing down — starting over it would+ // race two instances on the same socket files and storage.img.+ val reached = withTimeoutOrNull(10_000) {engine.state.first { state ->state is VmState.Stopped || state is VmState.Idle || state is VmState.Error}}- PodroidService.start(context)+ if (reached != null) {+ PodroidService.start(context)+ }}}}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.ktindex 6d54502..5a4c86e 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@@ -54,7 +54,6 @@ import androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel-import androidx.compose.runtime.collectAsStateimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport com.excp.podroid.BuildConfigimport com.excp.podroid.data.repository.PortForwardRule@@ -272,7 +271,8 @@ fun SettingsScreen(onClick = { viewModel.exportConsoleLogs() },)Spacer(Modifier.height(PodroidTokens.Spacing.SM))- val avfVerbose by viewModel.avfVerboseLogging.collectAsState()+ // Bug 7: use lifecycle-aware collection to match the rest of the screen.+ val avfVerbose by viewModel.avfVerboseLogging.collectAsStateWithLifecycle()PodroidListRow(label = "Verbose AVF logging",rightSlot = {@@ -311,8 +311,12 @@ fun SettingsScreen(AddPortForwardDialog(onDismiss = { showAddDialog = false },onAdd = { hostPort, guestPort, protocol ->- viewModel.addPortForward(hostPort, guestPort, protocol)- showAddDialog = false+ // Bug 8: only close the dialog when the rule was actually added.+ // addPortForward returns false if the (hostPort, protocol) pair+ // already exists; in that case the dialog stays open with an error.+ val added = viewModel.addPortForward(hostPort, guestPort, protocol)+ if (added) showAddDialog = false+ added},)}@@ -606,7 +610,9 @@ private fun AdvancedFieldsBlock(@Composableprivate fun AddPortForwardDialog(onDismiss: () -> Unit,- onAdd: (hostPort: Int, guestPort: Int, protocol: String) -> Unit,+ // Bug 8: returns true if the rule was added, false if it was a duplicate.+ // The dialog shows an error and stays open on false.+ onAdd: (hostPort: Int, guestPort: Int, protocol: String) -> Boolean,) {var hostPort by remember { mutableStateOf("") }var guestPort by remember { mutableStateOf("") }@@ -669,7 +675,8 @@ private fun AddPortForwardDialog(error = "Enter valid port numbers (1–65535)"return@TextButton}- onAdd(hp, gp, protocol)+ val added = onAdd(hp, gp, protocol)+ if (!added) error = "Port $hp (${protocol.uppercase()}) is already forwarded"}) {Text("Add")}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.ktindex 854224c..0d4ef82 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@@ -189,19 +189,23 @@ class SettingsViewModel @Inject constructor(viewModelScope.launch { settingsRepository.setTerminalFont(value) }}- // "both" expands into separate TCP + UDP rules. Existing rules with the- // same host port + protocol are skipped so the persisted Set doesn't grow.- // Live add/remove is handled by EngineHolder's rule-diff loop — we just- // write to DataStore and the holder picks up the change.- fun addPortForward(hostPort: Int, guestPort: Int, protocol: String = "tcp") {+ // "both" expands into separate TCP + UDP rules. Returns true if at least one+ // rule was added; false if every expansion was already present (duplicate).+ // Bug 8: the caller uses the return value to show feedback instead of silently+ // closing the dialog on a duplicate.+ fun addPortForward(hostPort: Int, guestPort: Int, protocol: String = "tcp"): Boolean {val protos = if (protocol == "both") listOf("tcp", "udp") else listOf(protocol)+ val existing = portForwardRules.value.toSet()+ val toAdd = protos.filter { proto ->+ existing.none { it.hostPort == hostPort && it.protocol == proto }+ }+ if (toAdd.isEmpty()) return falseviewModelScope.launch {- val existing = portForwardRules.value.toSet()- protos.forEach { proto ->- if (existing.any { it.hostPort == hostPort && it.protocol == proto }) return@forEach+ toAdd.forEach { proto ->portForwardRepository.addRule(PortForwardRule(hostPort, guestPort, proto))}}+ return true}/** Current LAN IP of the Android device — shown next to port forward rules. Cached for the VM lifetime. */@@ -354,11 +358,16 @@ class SettingsViewModel @Inject constructor(appendLine("verboseLogging = ${settingsRepository.getAvfVerboseLoggingSnapshot()}")appendLine()+ appendLine("=== Engine Diagnostics ===")+ val engineDiag = runCatching { engine.diagnosticsReport() }.getOrDefault("")+ append(if (engineDiag.isBlank()) "(none)\n" else engineDiag)+ appendLine()+appendLine("=== App Logcat (this process) ===")append(captureAppLogcat())appendLine()- appendLine("=== QEMU Console Log ===")+ appendLine("=== VM Console Log (backend=${activeBackendId()}) ===")val consoleFile = File(context.filesDir, "console.log")if (consoleFile.exists() && consoleFile.length() > 0) {val text = consoleFile.readText()@@ -374,19 +383,28 @@ class SettingsViewModel @Inject constructor(}/**- * Dump the current process's logcat buffer. Apps on Android 4.1+ can only- * read their own logs, so --pid filtering is redundant for security but- * keeps the output focused on Podroid tags.+ * Dump this process's own logcat, filtered to Podroid's tags (+ `*:S` to+ * silence everything else). Apps can only read their own logs, but that+ * per-pid buffer is otherwise ~95% framework noise (ImeTracker, Surface,+ * InsetsController, ...) that pushes the engine/vsock/boot lines out of the+ * window before we can capture them; the allowlist keeps the signal.*/private fun captureAppLogcat(): String {return try {val pid = android.os.Process.myPid().toString()val proc = Runtime.getRuntime().exec(- arrayOf("logcat", "-d", "-v", "time", "-t", "2000", "--pid=$pid")+ (listOf("logcat", "-d", "-v", "time", "--pid=$pid") ++ APP_LOG_TAGS.map { "$it:V" } + "*:S").toTypedArray())val output = proc.inputStream.bufferedReader().use { it.readText() }proc.waitFor()- if (output.isBlank()) "(logcat returned no lines)\n" else output+ val lines = output.trimEnd().lines().filter { it.isNotBlank() }+ when {+ lines.isEmpty() -> "(no Podroid-tagged logcat lines)\n"+ lines.size <= MAX_LOGCAT_LINES -> lines.joinToString("\n") + "\n"+ else -> (listOf("... (${lines.size - MAX_LOGCAT_LINES} earlier lines trimmed) ...") ++ lines.takeLast(MAX_LOGCAT_LINES)).joinToString("\n") + "\n"+ }} catch (e: Exception) {"(failed to capture logcat: ${e.message})\n"}@@ -394,5 +412,17 @@ class SettingsViewModel @Inject constructor(companion object {private const val TAG = "SettingsViewModel"+ private const val MAX_LOGCAT_LINES = 1500+ /**+ * Podroid's own logcat tags: the const TAGs plus the two literal-string+ * tags (AvfReflect, PodroidVM-err for QEMU stderr). Keep in sync when a+ * new component starts logging, or its lines won't reach the export.+ */+ private val APP_LOG_TAGS = listOf(+ "AudioStreamer", "AvfEngine", "AvfReflect", "ConsoleFanout",+ "EngineHolder", "PodroidApp", "PodroidService", "PodroidVM-err",+ "QemuEngine", "QmpClient", "SettingsViewModel", "TerminalVM",+ "VsockControlChannel", "VsockPortForwarder",+ )}}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/setup/SetupScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/setup/SetupScreen.ktindex ae033b6..c77a612 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/setup/SetupScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/setup/SetupScreen.kt@@ -7,10 +7,13 @@ import android.net.Uriimport android.os.Buildimport android.os.Environmentimport android.provider.Settings-import androidx.activity.ComponentActivity+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts.RequestPermissionimport androidx.compose.animation.core.animateDpAsState-import androidx.core.app.ActivityCompatimport androidx.core.content.ContextCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwnerimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box@@ -38,12 +41,14 @@ import androidx.compose.material3.FilterChipimport androidx.compose.material3.windowsizeclass.WindowHeightSizeClassimport androidx.compose.material3.windowsizeclass.WindowSizeClassimport androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -72,29 +77,50 @@ fun SetupScreen(viewModel: SetupViewModel = hiltViewModel(),) {val context = LocalContext.current- var selectedGb by remember { mutableIntStateOf(DEFAULT_STORAGE_GB) }- var sshEnabled by remember { mutableStateOf(true) }- var storageAccessEnabled by remember { mutableStateOf(false) }+ // rememberSaveable preserves wizard choices through config changes (rotation, font-scale, etc.)+ // so a mid-wizard rotation doesn't silently reset storage to 8 GB (not resizable later).+ var selectedGb by rememberSaveable { mutableIntStateOf(DEFAULT_STORAGE_GB) }+ var sshEnabled by rememberSaveable { mutableStateOf(true) }+ var storageAccessEnabled by rememberSaveable { mutableStateOf(false) }val setupComplete by viewModel.setupComplete.collectAsStateWithLifecycle()val pagerState = rememberPagerState(pageCount = { 3 })val scope = rememberCoroutineScope()+ // Bug 4: request the notification permission BEFORE navigating away; using+ // rememberLauncherForActivityResult registers it while the composable is still+ // alive, so the result actually arrives. ActivityCompat.requestPermissions+ // after onSetupComplete() fires against a transitioning Activity and is dropped+ // on some OEMs.+ val notifPermLauncher = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ rememberLauncherForActivityResult(RequestPermission()) { /* grant result: no-op */ }+ } else null+LaunchedEffect(setupComplete) {if (setupComplete) {- onSetupComplete()if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {- val activity = context as? ComponentActivity ?: return@LaunchedEffect- if (ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS)+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)!= PackageManager.PERMISSION_GRANTED) {- ActivityCompat.requestPermissions(- activity,- arrayOf(Manifest.permission.POST_NOTIFICATIONS),- 0,- )+ notifPermLauncher?.launch(Manifest.permission.POST_NOTIFICATIONS)}}+ onSetupComplete()+ }+ }++ // Bug 10: re-sync storageAccessEnabled against the actual OS grant on every+ // resume (the user may have denied the all-files-access screen we sent them to).+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME &&+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.R+ ) {+ storageAccessEnabled = storageAccessEnabled && Environment.isExternalStorageManager()+ }}+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }}Scaffold { innerPadding ->diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.ktindex bee4b6a..1b42eb1 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt@@ -159,6 +159,10 @@ fun TerminalScreen(val terminalFont by viewModel.terminalFont.collectAsStateWithLifecycle()if (showQuickSettings) {+ // Bug 5: pass the screen's viewModel explicitly so QuickSettingsDialog uses+ // the same instance rather than resolving a second entry-scoped one via+ // the hiltViewModel() default, which would give it a different (orphaned)+ // instance with stale/empty session state.QuickSettingsDialog(fontSize = fontSize,onFontSizeChange = { viewModel.setTerminalFontSize(it) },@@ -171,6 +175,7 @@ fun TerminalScreen(onColorThemeChange = { viewModel.setTerminalColorTheme(it) },terminalFont = terminalFont,onFontChange = { viewModel.setTerminalFont(it) },+ viewModel = viewModel,)}