Skip to content

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

feat(control): add a shell-only adb interface for device testing

ExTvacc1f1040448
diff --git a/CLAUDE.md b/CLAUDE.md
index e54127f..3526d90 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -160,6 +160,7 @@ Single-activity Compose app: `ui/navigation/NavGraph.kt` routes `setup → home
│ │ │ │ └── ninep/ # in-process 9p2000.L server (Ninep2000LServer, NinepCodec)
│ │ │ ├── hostbridge/ # guest->Android bridge (transport, server, dispatcher, notify)
│ │ │ │ └── HeadlessModeManager.kt # single source of truth for server (headless) mode
+│ │ │ ├── control/ # ControlProvider: shell-only `adb shell content call` test interface
│ │ │ └── usb/ # UsbPassthroughManager
│ │ ├── service/PodroidService.kt # foreground service; owns VM lifecycle, wakelock, notification; also VmControlReceiver (boot autostart + START_VM/STOP_VM automation intents)
│ │ ├── data/repository/ # Settings, PortForward, Update, Language, ContainerBackup, ContainerStats (all DataStore)
@@ -270,6 +271,23 @@ A device without that feature can *never* run `AvfEngine`, no matter the `Engine
**A change that touches both backends is unproven until it has been installed and walked on both.** Backend asymmetry is the #1 source of bugs (see Quirks & gotchas), and `AvfEngine.kt` is the most-churned file in the repository, so a QEMU-only test is the easiest way to ship a regression.
+### Driving the app from adb
+
+`engine/control/ControlProvider.kt` answers `adb shell content call`, so a device test does not have to tap through the UI. It ships in both build types, because release is where R8 bugs show up. Each call returns one line, `ok ...` or `error ...`.
+
+```bash
+C="adb shell content call --uri content://com.excp.podroid.control --method" # debug: com.excp.podroid.debug.control
+$C state # vm, backend, selection, boot stage, forwards, versionCode
+$C set-backend --arg qemu # auto | avf | qemu; force-stop and relaunch to re-pick
+$C forward-add --arg tcp:8080:80 # goes through PortForwardRepository, so EngineHolder applies it live
+$C forward-remove --arg tcp:8080:80
+$C backups # archive names the app sees
+$C navigate --arg container_backup # home | terminal | settings | status | container_backup
+adb shell am broadcast -a com.excp.podroid.action.START_VM -n com.excp.podroid/.service.VmControlReceiver # and STOP_VM
+```
+
+The framework does **not** permission-check `ContentProvider.call()`, so the manifest `android:permission` is only defense in depth. The real gate is `isCallerAllowed()` in `call()`: uid 0, uid 2000 (shell), or a caller holding `DUMP`. Keep that check first in `call()`; without it any installed app could open a LAN-facing port forward. New methods must go through the same repositories the UI uses, never straight to an engine.
+
Reading the VM console depends on build type: `run-as` works on debug, but **release builds are not `run-as`-able**, so use `su` or **Settings → Diagnostics → Export Log** there.
```bash
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index c1c1a2a..7059881 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -119,6 +119,19 @@
android:resource="@xml/file_paths" />
</provider>
+ <!--
+ adb-only control surface for on-device test automation (state,
+ backend switch, port forwards, backups, navigate). The manifest
+ permission is defense in depth only - ControlProvider.call()
+ enforces the real check (shell/root uid or DUMP) in code, since
+ the framework performs no permission check on call() itself.
+ -->
+ <provider
+ android:name=".engine.control.ControlProvider"
+ android:authorities="${applicationId}.control"
+ android:exported="true"
+ android:permission="android.permission.DUMP" />
+
<!-- Foreground service that hosts the QEMU process -->
<service
android:name=".service.PodroidService"
diff --git a/app/src/main/java/com/excp/podroid/engine/control/ControlProvider.kt b/app/src/main/java/com/excp/podroid/engine/control/ControlProvider.kt
new file mode 100644
index 0000000..458150e
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/control/ControlProvider.kt
@@ -0,0 +1,281 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * ContentProvider answering `adb shell content call` for on-device test
+ * automation: read VM state, switch backend, add/remove a port forward, list
+ * backup archives, jump to a screen. Start/stop already exist as broadcast
+ * intents (service/PodroidService.kt, VmControlReceiver) and are out of scope.
+ *
+ * adb shell content call --uri content://<applicationId>.control --method state
+ *
+ * The framework performs NO permission check on ContentProvider.call() itself,
+ * so isCallerAllowed() below is the real gate; the manifest's
+ * android:permission="android.permission.DUMP" is defense in depth only.
+ */
+package com.excp.podroid.engine.control
+
+import android.content.ContentProvider
+import android.content.ContentValues
+import android.content.Context
+import android.content.pm.PackageManager
+import android.database.Cursor
+import android.net.Uri
+import android.os.Binder
+import android.os.Bundle
+import android.os.Process
+import android.util.Log
+import com.excp.podroid.BuildConfig
+import com.excp.podroid.data.repository.AddRuleResult
+import com.excp.podroid.data.repository.ContainerBackupRepository
+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.EngineHolder
+import com.excp.podroid.engine.EngineSelection
+import com.excp.podroid.engine.VmState
+import com.excp.podroid.ui.navigation.Routes
+import dagger.hilt.EntryPoint
+import dagger.hilt.InstallIn
+import dagger.hilt.android.EntryPointAccessors
+import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.runBlocking
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * Routes `navigate` may jump to. Never `setup` (mid-wizard, jumping there is
+ * meaningless) and never `terminal/x11` (a nested destination the terminal
+ * screen pushes itself, not a standalone landing point).
+ */
+internal val ALLOWED_NAVIGATE_ROUTES = setOf(
+ Routes.HOME,
+ Routes.TERMINAL,
+ Routes.SETTINGS,
+ Routes.STATUS,
+ Routes.CONTAINER_BACKUP,
+)
+
+/**
+ * One parsed `call()` request. Kept free of Android types so [parseCommand]
+ * is unit testable on the plain JVM.
+ */
+internal sealed class ControlCommand {
+ object State : ControlCommand()
+ data class SetBackend(val selection: EngineSelection) : ControlCommand()
+ data class ForwardAdd(val rule: PortForwardRule) : ControlCommand()
+ data class ForwardRemove(val rule: PortForwardRule) : ControlCommand()
+ object Backups : ControlCommand()
+ data class Navigate(val route: String) : ControlCommand()
+ object UnknownMethod : ControlCommand()
+ object UnknownRoute : ControlCommand()
+ object BadArg : ControlCommand()
+}
+
+/** Pure method+arg parser. */
+internal fun parseCommand(method: String?, arg: String?): ControlCommand = when (method) {
+ "state" -> ControlCommand.State
+ "set-backend" -> {
+ val selection = arg?.uppercase()?.let { name ->
+ runCatching { EngineSelection.valueOf(name) }.getOrNull()
+ }
+ if (selection == null) ControlCommand.BadArg else ControlCommand.SetBackend(selection)
+ }
+ "forward-add" -> {
+ val rule = arg?.let(PortForwardRule::deserialize)
+ if (rule == null) ControlCommand.BadArg else ControlCommand.ForwardAdd(rule)
+ }
+ "forward-remove" -> {
+ val rule = arg?.let(PortForwardRule::deserialize)
+ if (rule == null) ControlCommand.BadArg else ControlCommand.ForwardRemove(rule)
+ }
+ "backups" -> ControlCommand.Backups
+ "navigate" -> when {
+ arg.isNullOrBlank() -> ControlCommand.BadArg
+ arg !in ALLOWED_NAVIGATE_ROUTES -> ControlCommand.UnknownRoute
+ else -> ControlCommand.Navigate(arg)
+ }
+ else -> ControlCommand.UnknownMethod
+}
+
+/**
+ * Caller check: root, shell, or an app holding android.permission.DUMP. An
+ * ordinary installed app is none of these, so it cannot flip the backend or
+ * add a port forward (user forwards bind 0.0.0.0) through this provider.
+ */
+internal fun isCallerAllowed(uid: Int, hasDumpPermission: Boolean): Boolean =
+ uid == Process.ROOT_UID || uid == Process.SHELL_UID || hasDumpPermission
+
+/**
+ * VmState -> explicit literal. Never javaClass.simpleName/::class.simpleName:
+ * R8 obfuscates those in release builds and the obfuscated name would leak
+ * into the adb reply.
+ */
+internal fun vmStateLiteral(state: VmState): String = when (state) {
+ is VmState.Idle -> "idle"
+ is VmState.Starting -> "starting"
+ is VmState.Running -> "running"
+ is VmState.Stopped -> "stopped"
+ is VmState.Error -> "error"
+}
+
+/** Builds the `state` reply from plain inputs, so it's testable without
+ * Android or a live EngineHolder. */
+internal fun formatStateReply(
+ vmState: VmState,
+ backendId: String,
+ selection: EngineSelection,
+ bootStage: String,
+ forwards: List<PortForwardRule>,
+ versionCode: Int,
+): String {
+ val stage = bootStage.replace(' ', '_')
+ val forwardsField = if (forwards.isEmpty()) "none" else forwards.joinToString(",") { it.serialize() }
+ return "ok vm=${vmStateLiteral(vmState)} backend=$backendId selection=${selection.name} " +
+ "stage=$stage forwards=$forwardsField vc=$versionCode"
+}
+
+/** `forward-add` outcome -> reply literal. */
+internal fun formatAddRuleReply(result: AddRuleResult): String = when (result) {
+ AddRuleResult.ADDED -> "ok added"
+ AddRuleResult.RESERVED -> "error reserved"
+ AddRuleResult.TABLE_FULL -> "error table-full"
+}
+
+/**
+ * Buffered, replay-1 route bus: the provider emits, NavGraph collects. A Hilt
+ * singleton so both sides reach the same instance without threading a
+ * parameter through the whole nav graph.
+ */
+@Singleton
+class ControlNavigator @Inject constructor() {
+ private val _routes = MutableSharedFlow<String>(extraBufferCapacity = 1)
+ val routes: SharedFlow<String> = _routes.asSharedFlow()
+ fun requestNavigate(route: String) {
+ _routes.tryEmit(route)
+ }
+}
+
+/**
+ * Dependencies ControlProvider.call() needs, resolved lazily per call: a
+ * ContentProvider's onCreate() runs before Application.onCreate(), so Hilt's
+ * SingletonComponent isn't installed yet and nothing may be injected there.
+ */
+@EntryPoint
+@InstallIn(SingletonComponent::class)
+internal interface ControlProviderEntryPoint {
+ fun settingsRepository(): SettingsRepository
+ fun portForwardRepository(): PortForwardRepository
+ fun containerBackupRepository(): ContainerBackupRepository
+ fun engineHolder(): EngineHolder
+ fun controlNavigator(): ControlNavigator
+}
+
+/**
+ * `adb shell content call --uri content://<applicationId>.control --method <m> [--arg <a>]`
+ *
+ * Methods: state, set-backend, forward-add, forward-remove, backups, navigate.
+ * Reply is a Bundle with one String key "result": "ok ..." on success,
+ * "error ..." on failure.
+ */
+class ControlProvider : ContentProvider() {
+
+ // Runs before Application.onCreate() - nothing may be injected or touched
+ // here. Dependencies are resolved lazily inside call() instead.
+ override fun onCreate(): Boolean = true
+
+ override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
+ val ctx = context
+ if (ctx == null || !isCallerAllowed(Binder.getCallingUid(), hasDumpPermission(ctx))) {
+ return replyBundle("error denied")
+ }
+ return try {
+ runBlocking { replyBundle(execute(ctx, method, arg)) }
+ } catch (e: Exception) {
+ Log.w(TAG, "call failed: method=$method", e)
+ replyBundle("error ${e.message ?: "internal error"}")
+ }
+ }
+
+ private fun hasDumpPermission(ctx: Context): Boolean =
+ ctx.checkCallingPermission(android.Manifest.permission.DUMP) == PackageManager.PERMISSION_GRANTED
+
+ private suspend fun execute(ctx: Context, method: String, arg: String?): String {
+ val ep = EntryPointAccessors.fromApplication(ctx, ControlProviderEntryPoint::class.java)
+ return when (val command = parseCommand(method, arg)) {
+ ControlCommand.State -> handleState(ep)
+ is ControlCommand.SetBackend -> handleSetBackend(ep, command.selection)
+ is ControlCommand.ForwardAdd -> handleForwardAdd(ep, command.rule)
+ is ControlCommand.ForwardRemove -> handleForwardRemove(ep, command.rule)
+ ControlCommand.Backups -> handleBackups(ep)
+ is ControlCommand.Navigate -> handleNavigate(ep, command.route)
+ ControlCommand.UnknownMethod -> "error unknown-method"
+ ControlCommand.UnknownRoute -> "error unknown-route"
+ ControlCommand.BadArg -> "error bad-arg"
+ }
+ }
+
+ private suspend fun handleState(ep: ControlProviderEntryPoint): String {
+ val holder = ep.engineHolder()
+ return formatStateReply(
+ vmState = holder.state.value,
+ backendId = holder.backendId,
+ selection = ep.settingsRepository().getEngineSelectionSnapshot(),
+ bootStage = holder.bootStage.value,
+ forwards = ep.portForwardRepository().getRulesSnapshot(),
+ versionCode = BuildConfig.VERSION_CODE,
+ )
+ }
+
+ private suspend fun handleSetBackend(ep: ControlProviderEntryPoint, selection: EngineSelection): String {
+ ep.settingsRepository().setEngineSelection(selection)
+ return "ok selection=${selection.name}"
+ }
+
+ // EngineHolder already applies PortForwardRepository changes to the
+ // running VM (its live rule-diff loop); calling the engine directly here
+ // would double-apply, so go through the repository like the UI does.
+ private suspend fun handleForwardAdd(ep: ControlProviderEntryPoint, rule: PortForwardRule): String =
+ formatAddRuleReply(ep.portForwardRepository().addRule(rule))
+
+ private suspend fun handleForwardRemove(ep: ControlProviderEntryPoint, rule: PortForwardRule): String {
+ ep.portForwardRepository().removeRule(rule)
+ return "ok removed"
+ }
+
+ private fun handleBackups(ep: ControlProviderEntryPoint): String {
+ val files = ep.containerBackupRepository().listBackupFiles()
+ return "ok count=${files.size} files=${files.joinToString(",") { it.name }}"
+ }
+
+ private fun handleNavigate(ep: ControlProviderEntryPoint, route: String): String {
+ ep.controlNavigator().requestNavigate(route)
+ return "ok route=$route"
+ }
+
+ private fun replyBundle(result: String): Bundle = Bundle().apply { putString(RESULT_FIELD, result) }
+
+ override fun query(
+ uri: Uri,
+ projection: Array<String>?,
+ selection: String?,
+ selectionArgs: Array<String>?,
+ sortOrder: String?,
+ ): Cursor? = null
+
+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null
+
+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
+
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
+
+ override fun getType(uri: Uri): String? = null
+
+ companion object {
+ private const val TAG = "ControlProvider"
+ private const val RESULT_FIELD = "result"
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
index eb2d3cd..c21ed46 100644
--- a/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
+++ b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
@@ -6,9 +6,11 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
import androidx.activity.compose.LocalActivity
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -16,6 +18,8 @@ import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
+import com.excp.podroid.engine.control.ControlProviderEntryPoint
+import dagger.hilt.android.EntryPointAccessors
import com.excp.podroid.ui.screens.home.HomeScreen
import com.excp.podroid.ui.screens.settings.SettingsScreen
import com.excp.podroid.ui.screens.setup.SetupScreen
@@ -64,6 +68,23 @@ fun PodroidNavGraph(
else -> Routes.SETUP
}
+ // adb `content call --method navigate` control surface (ControlProvider):
+ // collect the Hilt-singleton route bus instead of field-injecting it, so
+ // NavGraph doesn't need its own ViewModel wiring just for this. Emissions
+ // while the wizard is showing are ignored - jumping mid-setup is meaningless.
+ val context = LocalContext.current
+ LaunchedEffect(navController) {
+ val navigator = EntryPointAccessors.fromApplication(
+ context.applicationContext,
+ ControlProviderEntryPoint::class.java,
+ ).controlNavigator()
+ navigator.routes.collect { route ->
+ if (navController.currentDestination?.route != Routes.SETUP) {
+ navController.navigate(route) { launchSingleTop = true }
+ }
+ }
+ }
+
NavHost(
navController = navController,
startDestination = startDestination,
diff --git a/app/src/test/java/com/excp/podroid/engine/control/ControlProviderTest.kt b/app/src/test/java/com/excp/podroid/engine/control/ControlProviderTest.kt
new file mode 100644
index 0000000..399ad5d
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/control/ControlProviderTest.kt
@@ -0,0 +1,213 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Unit tests for ControlProvider's pure logic: caller authorization, method+
+ * arg parsing, VmState -> literal mapping, and state reply formatting. Plain
+ * JVM, no Robolectric - none of the code under test touches Android classes.
+ */
+package com.excp.podroid.engine.control
+
+import com.excp.podroid.data.repository.PortForwardRule
+import com.excp.podroid.engine.EngineSelection
+import com.excp.podroid.engine.VmState
+import com.excp.podroid.ui.navigation.Routes
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ControlProviderTest {
+
+ // ------------------------------------------------------------------
+ // isCallerAllowed
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `shell uid is allowed without DUMP`() {
+ assertTrue(isCallerAllowed(uid = 2000, hasDumpPermission = false))
+ }
+
+ @Test
+ fun `root uid is allowed without DUMP`() {
+ assertTrue(isCallerAllowed(uid = 0, hasDumpPermission = false))
+ }
+
+ @Test
+ fun `ordinary app uid without DUMP is rejected`() {
+ assertFalse(isCallerAllowed(uid = 10280, hasDumpPermission = false))
+ }
+
+ @Test
+ fun `ordinary app uid with DUMP is allowed`() {
+ assertTrue(isCallerAllowed(uid = 10280, hasDumpPermission = true))
+ }
+
+ // ------------------------------------------------------------------
+ // parseCommand - state / backups (no arg)
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `state parses with no arg`() {
+ assertEquals(ControlCommand.State, parseCommand("state", null))
+ }
+
+ @Test
+ fun `backups parses with no arg`() {
+ assertEquals(ControlCommand.Backups, parseCommand("backups", null))
+ }
+
+ // ------------------------------------------------------------------
+ // parseCommand - set-backend
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `set-backend accepts lowercase arg`() {
+ assertEquals(
+ ControlCommand.SetBackend(EngineSelection.QEMU),
+ parseCommand("set-backend", "qemu"),
+ )
+ }
+
+ @Test
+ fun `set-backend accepts uppercase and mixed case arg`() {
+ assertEquals(
+ ControlCommand.SetBackend(EngineSelection.AVF),
+ parseCommand("set-backend", "AVF"),
+ )
+ assertEquals(
+ ControlCommand.SetBackend(EngineSelection.AUTO),
+ parseCommand("set-backend", "Auto"),
+ )
+ }
+
+ @Test
+ fun `set-backend rejects unknown value`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("set-backend", "bogus"))
+ }
+
+ @Test
+ fun `set-backend rejects missing arg`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("set-backend", null))
+ }
+
+ // ------------------------------------------------------------------
+ // parseCommand - forward-add / forward-remove
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `forward-add parses a valid serialized rule`() {
+ assertEquals(
+ ControlCommand.ForwardAdd(PortForwardRule(8080, 80, "tcp")),
+ parseCommand("forward-add", "tcp:8080:80"),
+ )
+ }
+
+ @Test
+ fun `forward-add rejects an unparseable rule`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("forward-add", "not-a-rule"))
+ }
+
+ @Test
+ fun `forward-add rejects missing arg`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("forward-add", null))
+ }
+
+ @Test
+ fun `forward-remove parses a valid serialized rule`() {
+ assertEquals(
+ ControlCommand.ForwardRemove(PortForwardRule(8080, 80, "udp")),
+ parseCommand("forward-remove", "udp:8080:80"),
+ )
+ }
+
+ @Test
+ fun `forward-remove rejects an unparseable rule`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("forward-remove", "garbage"))
+ }
+
+ // ------------------------------------------------------------------
+ // parseCommand - navigate / route whitelist
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `navigate accepts each whitelisted route`() {
+ for (route in setOf(Routes.HOME, Routes.TERMINAL, Routes.SETTINGS, Routes.STATUS, Routes.CONTAINER_BACKUP)) {
+ assertEquals(ControlCommand.Navigate(route), parseCommand("navigate", route))
+ }
+ }
+
+ @Test
+ fun `navigate rejects setup`() {
+ assertEquals(ControlCommand.UnknownRoute, parseCommand("navigate", Routes.SETUP))
+ }
+
+ @Test
+ fun `navigate rejects terminal x11`() {
+ assertEquals(ControlCommand.UnknownRoute, parseCommand("navigate", Routes.TERMINAL_X11))
+ }
+
+ @Test
+ fun `navigate rejects missing arg`() {
+ assertEquals(ControlCommand.BadArg, parseCommand("navigate", null))
+ }
+
+ // ------------------------------------------------------------------
+ // parseCommand - unknown method
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `unknown method is reported`() {
+ assertEquals(ControlCommand.UnknownMethod, parseCommand("bogus-method", null))
+ }
+
+ // ------------------------------------------------------------------
+ // vmStateLiteral
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `vmStateLiteral maps every variant to an explicit literal`() {
+ assertEquals("idle", vmStateLiteral(VmState.Idle))
+ assertEquals("starting", vmStateLiteral(VmState.Starting))
+ assertEquals("running", vmStateLiteral(VmState.Running))
+ assertEquals("stopped", vmStateLiteral(VmState.Stopped))
+ assertEquals("error", vmStateLiteral(VmState.Error("boom")))
+ }
+
+ // ------------------------------------------------------------------
+ // formatStateReply
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `formatStateReply with no forwards reports none`() {
+ val reply = formatStateReply(
+ vmState = VmState.Running,
+ backendId = "qemu",
+ selection = EngineSelection.AUTO,
+ bootStage = "Ready!",
+ forwards = emptyList(),
+ versionCode = 42,
+ )
+ assertEquals(
+ "ok vm=running backend=qemu selection=AUTO stage=Ready! forwards=none vc=42",
+ reply,
+ )
+ }
+
+ @Test
+ fun `formatStateReply replaces spaces in the boot stage and joins forwards`() {
+ val reply = formatStateReply(
+ vmState = VmState.Starting,
+ backendId = "avf",
+ selection = EngineSelection.QEMU,
+ bootStage = "Almost ready...",
+ forwards = listOf(PortForwardRule(8080, 80, "tcp"), PortForwardRule(9922, 22, "tcp")),
+ versionCode = 7,
+ )
+ assertEquals(
+ "ok vm=starting backend=avf selection=QEMU stage=Almost_ready... " +
+ "forwards=tcp:8080:80,tcp:9922:22 vc=7",
+ reply,
+ )
+ }
+}