A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
docs: document guest CLIs and language support; refresh CLAUDE.md
ExTv9a632cadea01
diff --git a/CLAUDE.md b/CLAUDE.mdindex dbc33c8..6ad4043 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,145 +1,227 @@# CLAUDE.md-This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.+Guidance for Claude Code (and any AI assistant or new contributor) working in this repository. This is the deep map: read it before touching anything. Keep it accurate when you change the code.## What Is This-Podroid is an Android app that runs a rootless Alpine Linux VM via QEMU (ARM64) to provide a Podman container runtime without root. It embeds a Termux-based VT100 terminal emulator and communicates with the VM over QEMU serial/unix sockets.+Podroid is an Android app that runs a real **Alpine 3.23** Linux VM on stock Android 9+ (arm64) to provide rootless **Podman / Docker / LXC** containers and an in-app **X11 desktop** - no root, no custom recovery.-The VM runs a standard Alpine 3.23 root with **OpenRC as PID 1**; system services live in `/etc/init.d/podroid-*` (bootstrap, network, ready) inside a read-only squashfs (`/dev/vdb`), and the persistent overlay (`/dev/vda`, ext4) captures user changes (`apk add ...`, `rc-update add ...`).+- **Two interchangeable VM backends** behind one interface (`VmEngine`):+ - **QEMU (TCG)** - software emulation, the default, needs no special permission.+ - **AVF (pKVM)** - hardware-accelerated via the Android Virtualization Framework on Pixel-class devices, after a one-time `pm grant`.+- The guest is a standard Alpine root with **OpenRC as PID 1**. System services live in `/etc/init.d/podroid-*` on a read-only squashfs; a persistent ext4 overlay captures user changes (`apk add`, `rc-update add`).+- An embedded **Termux-based terminal**, an **X11/VNC viewer** (Xvnc + PulseAudio), and a **guest-to-Android bridge** (`podroid-notify` / `podroid-forward`) round it out.++## Key Facts++| | |+|---|---|+| Package | `com.excp.podroid` (debug: `com.excp.podroid.debug`) |+| Version | `versionName` / `versionCode` in `app/build.gradle.kts` |+| Min / target SDK | 28 (Android 9) / 36 |+| Architecture | arm64 (`aarch64`) only |+| Guest | Alpine 3.23 squashfs + persistent ext4 overlay, OpenRC PID 1 |+| Kernel | custom Linux, version pinned by `podroidKernelVersion` in `gradle.properties` |+| QEMU | version pinned by `podroidQemuVersion` in `gradle.properties` |+| UI | Jetpack Compose + Material 3, single Activity |+| DI | Hilt (constructor injection) |+| Async | Coroutines + StateFlow |+| Persistence | Jetpack DataStore (no database; Room is declared but unused) |+| Terminal | vendored Termux fork as local Gradle modules (`terminal-view`, `terminal-emulator`) |+| Languages | English + 中文 (Chinese); see `data/repository/LanguageManager.kt` + `res/values-zh/` |## Build Commands-All components are coordinated by `build-all.sh`:+All native/VM components are coordinated by `build-all.sh` (Docker-cached):```bash-./build-all.sh kernel # Build custom kernel only (podroid_kernel.config, ~5–10 min)-./build-all.sh initramfs # Build kernel + minimal initramfs (~10–15 min)-./build-all.sh rootfs # Build Alpine squashfs (alpine-rootfs.squashfs, ~30 s, Docker-cached)-./build-all.sh qemu # Build QEMU + podroid-bridge via Docker (~30 min first time)-./build-all.sh termux # Build libtermux.so via local NDK (16KB page alignment)-./build-all.sh apk # Build Android APK via Gradle-./build-all.sh all # Build everything-./build-all.sh deploy # Full deploy workflow-./build-all.sh test # Boot validation: deploys APK, polls console.log for "Ready!"+./build-all.sh kernel # custom kernel only (podroid_kernel.config)+./build-all.sh initramfs # kernel + minimal initramfs+./build-all.sh rootfs # Alpine squashfs -> app/src/main/assets/alpine-rootfs.squashfs+./build-all.sh qemu # QEMU + native helpers via Docker (slow first time)+./build-all.sh termux # terminal-emulator JNI for 16KB pages+./build-all.sh apk # Android APK via Gradle+./build-all.sh all # everything+./build-all.sh deploy # all + install + launch+./build-all.sh test # boot validation: installs, polls console.log for "Ready!"```-`podroidKernelVersion` in `gradle.properties` controls the Linux version downloaded. Docker layer-caches the kernel build; only rebuilds if `podroid_kernel.config` or the version changes.+**APK only:** `./gradlew assembleDebug` / `./gradlew installDebug`.-**APK only:**-```bash-./gradlew assembleDebug-./gradlew installDebug-```+**Unit tests:** `./gradlew :app:testDebugUnitTest` (use the `:app:` form, not the bare task).**Monitor VM boot:**```bashadb logcat -s PodroidQemu-adb shell run-as com.excp.podroid cat files/console.log # release buildadb shell run-as com.excp.podroid.debug cat files/console.log # debug build```-**Shipped builds are signed `release` builds** (1.1.9+). `assembleRelease` is wired up via `signingConfigs.release` in `app/build.gradle.kts`, fed by the `PODROID_RELEASE_STORE_FILE` / `_PASSWORD` / `_KEY_ALIAS` / `_KEY_PASSWORD` Gradle properties (keystore: `podroid-release.jks`). For release builds: `applicationId = com.excp.podroid`, `BuildConfig.VERSION_NAME = "1.1.9"`. Debug builds still get `applicationIdSuffix = ".debug"` and `versionNameSuffix = "-debug"` — so `com.excp.podroid.debug` / `1.1.9-debug` for `assembleDebug`. Any code comparing the local version string against an upstream release tag must strip an optional `-debug` suffix (see `UpdateRepository.checkForUpdate`).+**Release builds** are signed via `signingConfigs.release` (keystore `podroid-release.jks`), fed by the `PODROID_RELEASE_STORE_FILE` / `_PASSWORD` / `_KEY_ALIAS` / `_KEY_PASSWORD` Gradle properties. Release `applicationId = com.excp.podroid`; debug gets `applicationIdSuffix = ".debug"` + `versionNameSuffix = "-debug"`. Any code comparing the local version against an upstream release tag must strip an optional `-debug` suffix (see `UpdateRepository.checkForUpdate`).-Native binaries require 16KB page alignment (`-Wl,-z,max-page-size=16384`) — mandatory on Android 13+.+Native binaries require **16KB page alignment** (`-Wl,-z,max-page-size=16384`) - mandatory on Android 13+; verified by an ELF parser in `build-all.sh`.## Architecture-### Data Flow+### Engine abstraction (the most important thing to understand)++Everything VM-related goes through `engine/VmEngine.kt`, a single interface implemented by two backends and one router:++- **`QemuEngine.kt`** - QEMU/TCG. Software emulation, SLIRP user-mode networking, control via QMP and virtio-console Unix sockets. No special permission.+- **`engine/avf/AvfEngine.kt`** - AVF/pKVM. Uses the Android Virtualization Framework (reached by reflection in `AvfReflect.kt`); networking and control ride **vsock**. Hardware-accelerated; needs `MANAGE_VIRTUAL_MACHINE` + `USE_CUSTOM_VIRTUAL_MACHINE` granted via `pm grant`.+- **`EngineHolder.kt`** - the single Hilt binding for `VmEngine`. Picks the concrete engine at startup based on `EngineSelection` (Auto / AVF / QEMU), watches Settings for backend changes, and routes imperative calls + flow access to whichever is current. Also owns the live diff that applies `PortForwardRepository` changes to the running VM.++When you touch VM behavior, decide whether it is backend-neutral (put it behind `VmEngine` / `EngineHolder`) or backend-specific (inside `QemuEngine` or `AvfEngine`).++### Data flow```Terminal UI (Compose)- ↕ TerminalSession (Termux JNI)-libpodroid-bridge.so ←→ terminal.sock + ctrl.sock ←→ QEMU ←→ hvc0 + hvc1 (Alpine)--PodroidQemu (boot monitor) ←→ serial.sock ←→ QEMU ←→ ttyAMA0 (boot log only)+ | TerminalSession (vendored Termux JNI)+libpodroid-bridge.so <-> terminal.sock + ctrl.sock <-> VM <-> hvc0 + hvc1+boot monitor <-> serial.sock (QEMU) / console stream (AVF) -> console.log + boot-stage detector+QmpClient <-> qmp.sock (QEMU only) -> runtime port forwards (netdev_add/remove)+HostRequestServer <-> host.sock/hvc2 (QEMU) | vsock:9101 (AVF) <- podroid-notify / podroid-forward```-The terminal layer uses three QEMU Unix sockets, each with a single role:+QEMU exposes these Unix sockets under `context.filesDir`, each with one role:++- **`terminal.sock`** ↔ virtio-console `/dev/hvc0` - primary terminal I/O. getty runs on hvc0; `libpodroid-bridge.so` relays it to a Termux PTY.+- **`ctrl.sock`** ↔ virtio-console `/dev/hvc1` - resize channel. The bridge debounces SIGWINCH bursts and writes one `RESIZE rows cols\n`; a guest resize daemon `stty`s hvc0.+- **`serial.sock`** ↔ PL011 `/dev/ttyAMA0` - boot-log sink only. The boot monitor streams kernel + init output into `console.log` and the boot-stage detector.+- **`qmp.sock`** - QEMU Machine Protocol for runtime port forwarding and USB hot-plug.+- **`host.sock`** ↔ virtio-console `/dev/hvc2` - the guest→Android host bridge (see below).-- **`terminal.sock`** ↔ virtio-console `/dev/hvc0` — primary terminal I/O. getty runs on hvc0; `libpodroid-bridge.so` relays it to a Termux PTY.-- **`ctrl.sock`** ↔ virtio-console `/dev/hvc1` — resize signal channel. Bridge debounces SIGWINCH bursts (~25 per keyboard slide) and writes a single `RESIZE rows cols\n`; a resize daemon (started by `podroid-bootstrap`) stty's hvc0.-- **`serial.sock`** ↔ PL011 `/dev/ttyAMA0` — boot log sink. `PodroidQemu.monitorBootSerial` connects for the lifetime of the VM, streaming kernel + init output into `console.log` and the boot-stage detector. No bridge handoff.-- **`qmp.sock`** — runtime control for port forwarding (`QmpClient` sends `netdev_add` / `netdev_remove`).+On **AVF** there is no QMP and no PL011: the console is captured via `ConsoleFanout.kt`, control/resize go over `VsockControlChannel.kt`, port forwards over `VsockPortForwarder.kt`, and the host bridge over vsock port 9101.-### Key Components+### Boot pipeline-**`engine/PodroidQemu.kt`** — the core singleton. Builds and launches the QEMU process, monitors boot output from serial, manages `TerminalSession` lifecycle, and auto-starts `podroid-bridge` after boot. State machine: `Idle → Starting → Running → Stopped` (see `VmState.kt`). `detectBootStage()` scans the last 1024 chars of the rolling `consoleBuilder` rather than each `read()` chunk — required because fast devices (Pixel 10 Pro XL) split markers like `Ready!` across reads and the old per-chunk match silently fell through to the 60 s boot-timeout fallback.+1. The engine launches the VM and starts the boot monitor (`QemuBootMonitor.kt` for QEMU; the console stream for AVF). `BootStageDetector.kt` scans the rolling console buffer (last ~1KB, not per-`read()` chunk - fast devices split markers like `Ready!` across reads).+2. **`init-podroid`** (initramfs, ~45 lines): mounts the persistent ext4 (`/dev/vda` → upper) and the read-only squashfs (`/dev/vdb` → lower), stacks an overlayfs, moves the mounts into the new root, and `switch_root`s into `/sbin/init` (busybox).+3. Busybox `/sbin/init` reads `/etc/inittab` and starts **OpenRC** (runlevels are pre-symlinked at build time - chroot-into-aarch64 doesn't work on an x86_64 builder).+4. OpenRC services on the squashfs do all system bringup:+ - `podroid-bootstrap` - kernel modules, cgroup v2, devpts/shm/mqueue, sysctl, ZRAM swap, `mount --make-rshared /`, container dirs.+ - `podroid-network` - eth0 up, addressing, default route, `/etc/resolv.conf`.+ - `podroid-resize` - reads `RESIZE rows cols` from `/dev/hvc1`, `stty`s `/dev/hvc0`.+ - `podroid-hostd` - the host-bridge daemon (both backends).+ - `podroid-vsock` - the AVF control/forward agent (AVF boots only).+ - `dropbear` - SSH, when enabled.+ - `podroid-ready` - emits `Starting SSH...` / `Almost ready...` / `Ready!`, the markers `BootStageDetector` matches; `Ready!` flips state to `Running` and auto-starts the terminal bridge.-**`service/PodroidService.kt`** — foreground service that owns the QEMU process. Holds a `WakeLock`, updates the persistent notification with boot stages, and handles graceful stop when the app is swiped from recents.+**Why `switch_root`, not `chroot`:** an earlier version `chroot`ed into the overlay, which broke `podman exec -it` - `setns(MNT)` in `crun exec` resets `fs->root`, so the exec'd process saw raw kernel paths (`/mnt/overlay/proc`) instead of `/proc`. `switch_root` reorganizes the kernel mount tree itself, so namespace forks see a clean `/`.-**`engine/usb/UsbPassthroughManager.kt`** — runtime USB device passthrough into the QEMU guest. An unprivileged Android app cannot open the `/dev/bus/usb` device nodes, so it takes the already-open fd from `UsbManager` / `UsbDeviceConnection.getFileDescriptor()` and streams it to QEMU over `qmp.sock` as SCM_RIGHTS ancillary data (`add-fd`), then hot-plugs it with `device_add usb-host,hostdevice=/dev/fdset/N`. A code-registered `BroadcastReceiver` (no manifest `device_filter.xml`) is live only while the VM is `Running` — `PodroidService` drives `start()`/`stop()` off the VM state. Gated by the `usb_passthrough_enabled` setting, which also makes `buildCommand()` emit `-device qemu-xhci` at boot. Needs a libusb-enabled QEMU build — the `Dockerfile` cross-compiles libusb and configures QEMU `--enable-libusb`.+### Guest → Android host bridge-**`podroid-bridge.c`** — native C binary (compiled to `libpodroid-bridge.so`) that Termux runs as a subprocess. Bidirectionally relays PTY ↔ `terminal.sock`, and writes `RESIZE rows cols\n` to `ctrl.sock` after a 200 ms-debounced SIGWINCH burst (so a single keyboard-slide animation produces one shell prompt redraw, not 25).+Lets guest processes call back to Android. Guest side: `podroid-hostd` (multi-call C binary, `build-rootfs/host-bridge/podroid-hostd.c`) owns a guest-local `AF_UNIX` socket `/run/podroid-host.sock`; `argv[0]` dispatch also exposes it as `podroid-notify` and `podroid-forward` (symlinks). The daemon relays one request line / one response line to Android over a backend transport: `/dev/hvc2` on QEMU, `AF_VSOCK:9101` on AVF (chosen by the `podroid.backend=avf` cmdline marker). Android side: `engine/hostbridge/` - `HostRequestServer` reads requests over a `HostTransport` (`QemuHostTransport` via `LocalSocket` to `host.sock`, or `AvfHostTransport` via `connectVsock`), `HostRequestDispatcher` parses them, and routes to `NotificationPoster` (posts via `NotificationManagerCompat`) or `PortForwardRepository` (rules persist and `EngineHolder` applies them live). `PodroidService` starts/stops the server over the VM lifecycle. Free-text fields are base64 (`HostProtocol.kt`) so UTF-8 survives.-**`init-podroid`** — minimal initramfs bootstrap (~45 lines). Mounts persistent ext4 (`/dev/vda` → `/mnt/persist`) and read-only Alpine squashfs (`/dev/vdb` → `/mnt/lower`), stacks an overlayfs (lower=squashfs, upper=persist), and `switch_root`s into `/sbin/init` (busybox, which reads `/etc/inittab` and starts OpenRC). All system bringup (cgroup v2, SLIRP networking, devpts/shm/mqueue mounts, ZRAM, sysctl, Podman dirs) lives in three OpenRC services on the squashfs:-- `/etc/init.d/podroid-bootstrap` — modules, cgroup v2, ZRAM, devpts/shm/mqueue, sysctl, hostname-- `/etc/init.d/podroid-network` — eth0 up, 10.0.2.15/24, default route, /etc/resolv.conf-- `/etc/init.d/podroid-ready` — emits the `Starting SSH...` / `Almost ready...` / `Ready!` markers consumed by `PodroidQemu.detectBootStage()`+> **Gotcha:** `/dev/hvc2` is a virtio-console **TTY** that defaults to echo on. The daemon must `cfmakeraw()` it, or the TTY echoes Android's responses back and the protocol desyncs after the first request. AVF (a raw vsock socket) is unaffected.-**Why not chroot?** A previous version used `chroot /mnt/overlay` to pivot into the persistent layer. That broke `podman exec -it` (issue #17): `setns(MNT)` in `crun exec` resets `fs->root`, and the exec'd process saw raw kernel paths (`/mnt/overlay/proc`) instead of `/proc`. `switch_root` reorganizes the kernel mount tree itself — no chroot indirection — so namespace forks see a clean `/`.+### USB passthrough (`engine/usb/UsbPassthroughManager.kt`)-**`build-rootfs/`** — Dockerized build of the Alpine squashfs. `Dockerfile.rootfs` fetches `alpine-minirootfs-3.23.4-aarch64.tar.gz`, runs `build-rootfs.sh` (apk-installs alpine-base + openrc + busybox-openrc + bash + podman + crun + fuse-overlayfs + iptables/ip6tables/nftables + bridge-utils + iproute2 + dropbear, sets root password to `podroid`, copies the OpenRC service files from `build-rootfs/files/etc/`, configures runlevels via direct symlinks since chroot-into-aarch64 doesn't work on x86_64), then `mksquashfs -comp zstd -Xcompression-level 19` (the kernel ships `CONFIG_SQUASHFS_ZSTD=y`). Result is ~41 MB at `app/src/main/assets/alpine-rootfs.squashfs`, extracted by `PodroidApplication.kt` to `filesDir` and mounted by QEMU as `/dev/vdb`.+QEMU backend only. An unprivileged app can't open `/dev/bus/usb`, so it takes the already-open fd from `UsbManager`/`UsbDeviceConnection` and streams it to QEMU over `qmp.sock` as SCM_RIGHTS (`add-fd`), then hot-plugs with `device_add usb-host,hostdevice=/dev/fdset/N`. A code-registered `BroadcastReceiver` (no manifest `device_filter.xml`) is live only while the VM is `Running`. Gated by the `usb_passthrough_enabled` setting, which also makes `buildCommand()` emit `-device qemu-xhci`. Needs a libusb-enabled QEMU build.-**`data/repository/`** — `SettingsRepository` (RAM, CPUs, storage size, theme, SSH toggle) and `PortForwardRepository` (persistent rules) both use Jetpack DataStore. No database.+### X11 viewer (`x11/` + `ui/screens/x11/`)-### Asset Extraction+In-app viewer that talks RFB to `Xvnc` in the guest, with touch→mouse, soft-keyboard, external mouse/keyboard, fullscreen, rotation lock, resolution presets, and PCM audio over PulseAudio loopback. Backed by always-on implicit VNC/audio port forwards.-`PodroidApplication.kt` copies `qemu/`, `vmlinuz-virt`, `initrd.img`, and `alpine-rootfs.squashfs` from APK assets to `filesDir` on startup (size-checked to skip if unchanged). All native binaries in `jniLibs/arm64-v8a/` are extracted automatically by Android.+### Internationalization++`data/repository/LanguageManager.kt` + `res/values/` / `res/values-zh/`. `MainActivity.attachBaseContext` wraps the context for the saved locale (read synchronously from a cache file before Hilt is available); changing the language in Settings persists it and recreates the Activity. Don't reintroduce hardcoded user-facing strings - use `stringResource` and keep `values` / `values-zh` in sync.### Navigation-Single-activity Compose app: `NavGraph.kt` routes `setup → home → terminal / settings`. The setup screen only appears until setup is marked complete in DataStore.+Single-activity Compose app: `ui/navigation/NavGraph.kt` routes `setup → home → terminal / settings / x11`. `TerminalViewModel` is scoped outside the `NavHost` so the session survives screen changes. The setup wizard shows until setup is marked complete in DataStore.++## Project Structure++```+/+├── app/ # Android module+│ └── src/main/+│ ├── java/com/excp/podroid/+│ │ ├── MainActivity.kt # single Activity, locale wrap, WindowSizeClass+│ │ ├── PodroidApplication.kt # Hilt app, asset extraction on first run+│ │ ├── engine/+│ │ │ ├── VmEngine.kt # backend interface+│ │ │ ├── EngineHolder.kt # Hilt binding; routes to current engine; port-forward diff+│ │ │ ├── EngineModule.kt, EngineSelection.kt+│ │ │ ├── QemuEngine.kt # QEMU/TCG backend, buildCommand()+│ │ │ ├── QemuBootMonitor.kt, BootStageDetector.kt+│ │ │ ├── QmpClient.kt # QMP: port forwards + USB add-fd+│ │ │ ├── ResizeNotifyingSession.kt, VmState.kt+│ │ │ ├── avf/ # AVF/pKVM backend (engine, reflection, vsock, console)+│ │ │ ├── hostbridge/ # guest->Android bridge (transport, server, dispatcher, notify)+│ │ │ └── usb/ # UsbPassthroughManager+│ │ ├── service/PodroidService.kt # foreground service; owns VM lifecycle, wakelock, notification+│ │ ├── data/repository/ # Settings, PortForward, Update, Language (all DataStore)+│ │ ├── di/ # Hilt module+│ │ ├── util/ # NetworkUtils etc.+│ │ ├── x11/ # X11/VNC viewer engine+│ │ └── ui/ # Compose: navigation, theme, screens/{setup,home,terminal,settings,x11}, components+│ ├── res/values, res/values-zh/ # strings (EN + Chinese)+│ ├── assets/ # vmlinuz-virt, initrd.img, alpine-rootfs.squashfs (all gitignored, built locally),+│ │ # qemu/, colors/ (122), fonts/ (13), ui-fonts/+│ └── jniLibs/arm64-v8a/ # native executables (see below)+├── terminal-view/, terminal-emulator/ # vendored Termux fork (local Gradle modules)+├── init-podroid # initramfs bootstrap: overlay + switch_root+├── podroid-bridge.c # PTY <-> virtio-console relay -> libpodroid-bridge.so+├── podroid-launcher.c # exec wrapper that ties QEMU's lifetime to the app -> libpodroid-launcher.so+├── Dockerfile # kernel + initramfs + QEMU build+├── build-rootfs/+│ ├── Dockerfile.rootfs, build-rootfs.sh+│ ├── vsock-agent/ # podroid-vsock-agent.c (AVF control/forward agent)+│ ├── host-bridge/ # podroid-hostd.c (guest->Android bridge daemon + CLIs)+│ └── files/etc/ # OpenRC services + configs baked into the squashfs+├── build-all.sh, gradle.properties, build.gradle.kts, settings.gradle.kts+└── README.md, CONTRIBUTING.md, CREDITS.md+```-## Native Binaries in `jniLibs/arm64-v8a/`+## Native Binaries (`app/src/main/jniLibs/arm64-v8a/`)++ELF executables renamed `.so` for APK packaging; run via `ProcessBuilder` / `TerminalSession`, not loaded as JNI libraries. All 16KB-aligned.| File | What it is ||---|---|-| `libqemu-system-aarch64.so` | QEMU TCG emulator (PIE executable, 16KB aligned) |-| `libpodroid-bridge.so` | PTY ↔ virtio-console relay (PIE executable, 16KB aligned) |-| `libtermux.so` | Termux terminal emulator JNI (rebuilt for 16KB pages) |-| `libslirp.so` | SLIRP user-mode networking (statically linked into QEMU) |--These are executed directly via `ProcessBuilder` / `TerminalSession`, not loaded as JNI libraries despite the `.so` extension.--## QEMU Command Construction--`PodroidQemu.buildCommand()` constructs the full QEMU cmdline including:-- `-serial unix:serial.sock` (boot log) + a virtio-serial-pci bus carrying two virtconsoles: `terminal.sock` (org.podroid.term, hvc0) and `ctrl.sock` (org.podroid.ctrl, hvc1)-- `-qmp unix:qmp.sock` for runtime port-forward changes-- RAM, CPU count, and user-editable extras (`-cpu`, `-accel`, RNG, etc.) from `SettingsRepository`-- **Two** virtio block devices:- - `/dev/vda` ← `storage.img` (writable ext4, persistent overlay upper, resized on first boot to configured size)- - `/dev/vdb` ← `alpine-rootfs.squashfs` (read-only, zstd squashfs, mounted at `/mnt/lower` and used as overlay's lowerdir)-- SLIRP networking with runtime port forwards via `QmpClient` (`netdev_add`/`netdev_remove` over `qmp.sock`)--All socket and image paths are under `context.filesDir`.--## Performance Tuning (TCG, no KVM)--All tuning applies under software emulation only — KVM is impossible without root.--**In `PodroidQemu.buildCommand()`:**-- `tcg,thread=multi` — one host thread per vCPU (already enabled)-- `tb-size`: 256 MB for <2 GB RAM, 512 MB for ≥2 GB — larger TB cache reduces re-translation for JIT-heavy workloads (Node, JVM in containers)-- `iothread=iothread0` on `virtio-blk-pci` — dedicated I/O thread decoupled from vCPU threads; biggest single win for container image pull/extraction-- `mitigations=off` in guest kernel cmdline — safe inside TCG VM (speculative execution attacks can't cross the emulated ISA boundary); 5–15% CPU gain-- `elevator=mq-deadline` in guest kernel cmdline — request merging for virtio-blk random writes (Podman overlay graph driver)-**In `init-podroid`:**-- ZRAM swap at half physical RAM using lz4 — gives 1.5–2× effective memory with near-zero I/O cost; swapon at priority 100 so it's preferred over any file swap--**In `Dockerfile` (QEMU build):**-- QEMU 11.0.0-rc2 cross-compiled against NDK r27c with three minimum patches:- `--disable-plugins` (uftrace.c uses `timespec_get`, absent from Bionic),- empty `contrib/ivshmem-{server,client}/meson.build` (use shm_open we don't ship),- `-include shm_shim.h` declarations + a `libshm.a` stub implementing- `shm_open`/`shm_unlink` via `memfd_create` (NDK API-28 stubs lack them).-- Custom Linux 6.6.87 kernel: arm64 defconfig + `podroid_kernel.config` (modules)- + `forced_builtin.config` (=y for IPV6 / BRIDGE / NF_TABLES / NFT_COMPAT /- MASQUERADE family / VETH / TUN / OVERLAY_FS / FUSE_FS).-- A build-time loop greps the resolved `.config` and **fails the build** if- any of those critical options isn't `=y`. This guards against silent- Kconfig demotions caused by unmet tristate deps (e.g. CONFIG_BRIDGE caps- out at IPV6's strength).--**What won't work without root:** `io_uring` (Android 12+ seccomp block), CPU affinity/taskset, KSM memory dedup, TAP networking, huge pages on the host.+| `libqemu-system-aarch64.so` | QEMU TCG emulator |+| `libpodroid-bridge.so` | PTY ↔ virtio-console relay (from `podroid-bridge.c`) |+| `libpodroid-launcher.so` | exec wrapper for QEMU process lifetime (from `podroid-launcher.c`) |+| `libslirp.so` | SLIRP user-mode networking (soname patched `.so.0`→`.so`) |++The terminal emulator JNI is built from the vendored `terminal-emulator` module (rebuilt for 16KB pages), not shipped as a prebuilt here.++## QEMU command construction (`QemuEngine.buildCommand()`)++- `-serial unix:serial.sock` (boot log) + a `virtio-serial-pci` bus carrying three virtconsoles: `terminal.sock` (hvc0), `ctrl.sock` (hvc1), `host.sock` (hvc2, the host bridge - **order matters**, the guest expects host bridge on hvc2).+- `-qmp unix:qmp.sock` for runtime port forwards + USB.+- RAM, CPU count, and user-editable extras (`-cpu`, `-accel`, RNG, etc.) from `SettingsRepository`.+- Two virtio block devices: `/dev/vda` ← `storage.img` (writable ext4 overlay upper, resized on first boot), `/dev/vdb` ← `alpine-rootfs.squashfs` (read-only zstd lower).+- SLIRP networking; `-device qemu-xhci` when USB passthrough is enabled.++## Build pipelines++- **`Dockerfile`** - custom Linux kernel (arm64 defconfig + `podroid_kernel.config` modules + `forced_builtin.config` forcing overlayfs / netfilter / bridge / veth / tun / FUSE / IPv6 etc. to `=y`) and QEMU cross-compiled against the NDK. A build-time check greps the resolved `.config` and **fails the build** if any critical option isn't `=y` (guards against silent Kconfig demotion from unmet tristate deps). QEMU needs `--enable-libusb` (for passthrough) and a few Android/Bionic patches; `build-all.sh qemu` may need `docker build --network=host`.+- **`build-rootfs/Dockerfile.rootfs`** - fetches the Alpine minirootfs, runs `build-rootfs.sh` (apk-installs alpine-base + openrc + podman + crun + fuse-overlayfs + docker + lxc + dropbear + iptables/nftables + bridge-utils, sets root password `podroid`, seals file caps on `newuidmap`/`newgidmap`, copies the OpenRC services and the cross-compiled `podroid-vsock-agent` + `podroid-hostd`, wires runlevels via direct symlinks), then `mksquashfs -comp zstd` (kernel ships `CONFIG_SQUASHFS_ZSTD=y`).++## Performance tuning (TCG path; KVM is impossible without root)++In `QemuEngine.buildCommand()`: `tcg,thread=multi`, larger `tb-size` for ≥2GB RAM, dedicated `iothread` on `virtio-blk-pci`, `-cpu max,sve=off`. Guest cmdline: `mitigations=off` (safe inside TCG), per-device `mq-deadline`. `init-podroid`/bootstrap: ZRAM lz4 swap at half RAM. `CONFIG_EXT4_FS_SECURITY=y` + `CONFIG_SQUASHFS_XATTR=y` keep `security.capability` xattrs across the overlay (rootless podman's `newuidmap` needs them). What won't work without root: `io_uring` (seccomp), CPU affinity, KSM, TAP networking, host hugepages.++## Quirks & gotchas++- **Backend asymmetry is the #1 source of bugs.** QEMU = SLIRP + QMP + virtio-console (TTY); AVF = DHCP + vsock (raw sockets). Test both. The host bridge's `cfmakeraw` on hvc2 (above) is a concrete example.+- **Boot detection** scans a rolling buffer, not per-read chunks (fast devices split markers).+- **Bridge stderr is silenced** (`dup2(/dev/null, STDERR)`): it runs as a `TerminalSession` subprocess whose stderr IS the PTY. Never add `fprintf(stderr, ...)` to `podroid-bridge.c`.+- **`forceUpdateSizeFromView` must not multiply by scaledDensity** - `TerminalView` passes the raw int textSize to `Paint`; mismatched math renders TUI apps in the wrong grid.+- **SLIRP has no ICMP** (`ping` fails in the guest) and its DNS forwarder is unreliable on Android (resolv.conf uses public DNS).+- **Privileged ports**: the app can't bind host ports < 1024 (no `CAP_NET_BIND_SERVICE`), so SSH is on 9922, not 22. Forward to a high host port.+- **Reflection into the vendored Termux fork** (`mTermSession`, `mEmulator`, `mCurrentDecSetFlags`) is kept by `app/proguard-rules.pro`.+- **Persistence is sacred**: DataStore keys and `filesDir` paths survive every release; renames need migration. Updates must install in place (same `applicationId` + signing key, monotonic `versionCode`).++## Common tasks++- **Kotlin/UI change** → `./gradlew assembleDebug && ./gradlew installDebug`.+- **OpenRC service / package list / guest CLI change** → edit under `build-rootfs/`, `./build-all.sh rootfs`, rebuild APK (the squashfs is an APK asset; a fresh install or VM reset is needed to pick it up since the overlay can shadow it).+- **`init-podroid` change** → `./build-all.sh initramfs`, rebuild APK.+- **New boot stage** → emit the marker in the right OpenRC service + match it in `BootStageDetector`.+- **New setting** → add a DataStore key + Flow in `SettingsRepository`, UI in `SettingsScreen`, setter in `SettingsViewModel`, and plumb into `VmConfig`/`buildCommand()` if it affects the VM.+- **New user-facing string** → add to `res/values` AND `res/values-zh`, use `stringResource`.+- **Verify before "done"**: compile, run `:app:testDebugUnitTest`, and for behavior changes install and walk the flow on a device (unit tests don't catch DI/graph or backend-specific issues).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d994055..f196966 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -2,7 +2,7 @@Thanks for considering a contribution. Bug reports, feature requests, and pull requests are all welcome.-Before you start, please skim [`skill.md`](skill.md). It documents the boot pipeline, every native binary, and the design quirks you need to know to make changes that don't regress.+Before you start, please skim [`CLAUDE.md`](CLAUDE.md). It documents the VM-engine abstraction and both backends, the boot pipeline, every native binary, and the design quirks you need to know to make changes that don't regress.## Getting started@@ -60,7 +60,7 @@ adb shell run-as com.excp.podroid.debug cat files/console.log1. Fork the repository and create a topic branch (`fix/issue-42`, `feature/whatever`).2. Keep pull requests focused: one fix or one feature per PR.3. Test on a real arm64 device before submitting. Emulators do not exercise the QEMU + native binary path the way real hardware does.-4. If your change is user-facing, update [`README.md`](README.md). If it changes the boot pipeline, terminal layer, or kernel options, update [`skill.md`](skill.md) and [`CLAUDE.md`](CLAUDE.md) too.+4. If your change is user-facing, update [`README.md`](README.md). If it changes the architecture, boot pipeline, terminal layer, or kernel options, update [`CLAUDE.md`](CLAUDE.md) too.5. Match the existing code style of the file you are editing.## Project layoutdiff --git a/README.md b/README.mdindex 2c554da..9bae037 100644--- a/README.md+++ b/README.md@@ -50,6 +50,10 @@ podman run -d -p 8080:80 nginx # reachable from Android at 127.0.0.1:8# GUI apps: tap the monitor icon in the terminal to open the X11 viewerapk add firefoxfirefox &++# Talk back to Android from inside the VM+podroid-notify --priority high "build finished" # posts an Android notification+podroid-forward add 8888 80 # expose the guest's :80 on the phone's :8888```Default login: **root / podroid**.@@ -81,6 +85,8 @@ Default login: **root / podroid**.- **In-app X11 viewer** (Xvnc + PulseAudio): live-resizable display (match-device, or 720p–1440p / custom presets), direct-touch and trackpad pointer modes with scroll, fullscreen, rotation lock, external-keyboard and mouse-wheel support, soft-keyboard input, and PCM audio over loopback.- **USB device passthrough** *(coming soon)*. Hot-plug a real USB device — Wi-Fi adapter, storage, serial adapter, audio interface — into the running VM straight from the Android USB stack. No root and no XML device filter: each device asks for permission when attached and is streamed to QEMU over QMP while the app runs.- **Built-in terminal** powered by the Termux engine: xterm-256color, mouse tracking, debounced resize, customizable extra-keys row.+- **Guest-to-Android bridge.** Two CLIs inside the VM talk back to the phone: `podroid-notify` posts Android notifications (title, priority, and `--id` to update one in place), and `podroid-forward` adds/lists/removes Android port-forward rules without leaving the shell. Great for long builds, cron jobs and container health alerts. Works on both the QEMU and AVF backends.+- **English and 中文 (Chinese)** interface, switchable in Settings or following the device language.- **Persistent ext4 overlay** on a read-only Alpine squashfs. Installs and configs survive every reboot.- **Adaptive Material 3 UI** for phone, tablet and landscape, with dynamic color and a foreground service that keeps the VM alive.@@ -106,7 +112,8 @@ Everything below is editable from **Settings**:- **Downloads folder sharing:** toggle on/off; mounted inside the VM at `/mnt/downloads` (virtio-9p on QEMU, AVF `SharedPath` where the backend supports it)- **USB passthrough** *(coming soon)*: opt-in toggle in Settings and at first-run setup (alongside Downloads sharing); hot-plugs attached USB devices into the running VM (QEMU backend only — adds a USB controller at boot, so set it while the VM is stopped)- **SSH** (Dropbear on host port `9922`): toggle on/off; reachable from the LAN as `ssh root@<phone-ip> -p 9922` once the VM is Ready-- **Port forwards:** add/remove host ↔ guest TCP/UDP rules live, no VM restart+- **Port forwards:** add/remove host ↔ guest TCP/UDP rules live, no VM restart — from Settings, or with `podroid-forward` inside the VM+- **Language:** System default · English · 中文 (Chinese)- **Advanced QEMU args:** full `-cpu` / `-accel` / RNG / device line, editable- **Advanced kernel cmdline:** extras appended to the boot cmdline- **Full App Reset:** wipe the persistent storage image and start over@@ -226,7 +233,7 @@ Contributions of every size are welcome: bug reports, kernel-config tweaks, new- **Pull requests:** read [CONTRIBUTING.md](CONTRIBUTING.md) first. Keep changes scoped, run `./build-all.sh test` before pushing, and explain *why* in the PR description.- **Bug reports:** [open an issue](https://github.com/ExTV/Podroid/issues/new) with your device + Android version, a short repro, and the diagnostic log (**Settings → Export Diagnostic Log** in the app).-- **Diving into the engine:** [`skill.md`](skill.md) is the deep map: boot pipeline, every native binary, every quirk. AI assistants should read it before touching anything.+- **Diving into the engine:** [`CLAUDE.md`](CLAUDE.md) is the deep map: the `VmEngine` abstraction and both VM backends, the boot pipeline, every native binary, the build pipelines, and the project's quirks. AI assistants (and humans) should read it before touching anything — it's written so you can open a PR that fits the codebase.## Creditsdiff --git a/docs/guide/backends.html b/docs/guide/backends.htmlindex fa1b13f..206f10f 100644--- a/docs/guide/backends.html+++ b/docs/guide/backends.html@@ -166,7 +166,7 @@<a class="prev" href="performance.html"><span class="dir">Previous</span>← Performance</a><a class="next" href="networking.html"><span class="dir">Next</span>Networking & ports →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/desktop.html b/docs/guide/desktop.htmlindex e7097aa..15a5759 100644--- a/docs/guide/desktop.html+++ b/docs/guide/desktop.html@@ -149,7 +149,7 @@<a class="prev" href="packages.html"><span class="dir">Previous</span>← Packages & services</a><a class="next" href="settings.html"><span class="dir">Next</span>Terminal & settings →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/getting-started.html b/docs/guide/getting-started.htmlindex 0c48707..0d5bfa3 100644--- a/docs/guide/getting-started.html+++ b/docs/guide/getting-started.html@@ -124,7 +124,7 @@<a class="prev" href="index.html"><span class="dir">Previous</span>← Overview</a><a class="next" href="how-it-works.html"><span class="dir">Next</span>How it works →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/how-it-works.html b/docs/guide/how-it-works.htmlindex 9573d0c..42aaf9a 100644--- a/docs/guide/how-it-works.html+++ b/docs/guide/how-it-works.html@@ -135,7 +135,7 @@<a class="prev" href="getting-started.html"><span class="dir">Previous</span>← Getting started</a><a class="next" href="performance.html"><span class="dir">Next</span>Performance & why it's slow →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/index.html b/docs/guide/index.htmlindex 833e71e..0467cbe 100644--- a/docs/guide/index.html+++ b/docs/guide/index.html@@ -80,7 +80,7 @@<span></span><a class="next" href="getting-started.html"><span class="dir">Next</span>Getting started →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/limitations.html b/docs/guide/limitations.htmlindex e776247..55a989e 100644--- a/docs/guide/limitations.html+++ b/docs/guide/limitations.html@@ -187,7 +187,7 @@<a class="prev" href="settings.html"><span class="dir">Previous</span>← Terminal & settings</a><a class="next" href="use-cases.html"><span class="dir">Next</span>Use cases →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/networking.html b/docs/guide/networking.htmlindex 33d1f7a..7b1bfd4 100644--- a/docs/guide/networking.html+++ b/docs/guide/networking.html@@ -122,6 +122,34 @@ podman run -d -p 8080:80 nginx# Then from your laptop on the same Wi-Fi:</span>curl http://<phone-ip>:8080</code></pre>+ <h2>Talking back to Android from the guest</h2>+ <p>Two command-line tools ship inside the VM so scripts and shell sessions can reach the Android side directly, without the in-app UI. Both work on the QEMU and AVF backends.</p>++ <h3><code>podroid-forward</code> - manage port forwards from the shell</h3>+ <pre><code><span class="c"># forward phone :8888 -> guest :80</span>+podroid-forward add 8888 80 tcp+<span class="c"># shorthand for "add ... tcp"</span>+podroid-forward 8888 80+<span class="c"># list current rules</span>+podroid-forward list+<span class="c"># drop a rule</span>+podroid-forward remove 8888 tcp</code></pre>+ <p>Rules created this way are identical to ones added in Settings: they apply live, persist across reboots, and appear in the Settings list. UDP is QEMU-only (ignored on AVF), the same as the UI.</p>++ <h3><code>podroid-notify</code> - post an Android notification</h3>+ <pre><code><span class="c"># simplest form</span>+podroid-notify "build finished"+<span class="c"># with a title and priority (low | normal | high)</span>+podroid-notify --title Podroid --priority high "container crashed"+<span class="c"># reuse --id to update the same notification in place</span>+podroid-notify --id 7 "progress 50%"</code></pre>+ <p>Handy for long builds, downloads, cron jobs and container health alerts. Tapping the notification opens Podroid. Requires the standard Android notification permission, requested at first run.</p>++ <div class="callout note">+ <span class="label">How it works</span>+ <p>A small guest daemon (<code>podroid-hostd</code>) relays each request to the Android side over the same control transport the app already uses - a virtio-console port on QEMU, vsock on AVF - which then posts the notification or writes the port-forward rule. Any process that can reach the guest socket can use these, so they work from a container too if you bind-mount <code>/run/podroid-host.sock</code> into it.</p>+ </div>+<h2>LAN reachability</h2><p>All port forward listeners bind <code>0.0.0.0</code>, not <code>127.0.0.1</code>. This means any device on the same Wi-Fi network can reach the phone by its local IP address. The phone's current IP is shown in <strong>Settings</strong>.</p>@@ -169,7 +197,7 @@ curl http://<phone-ip>:8080</code></pre><a class="prev" href="backends.html"><span class="dir">Previous</span>← Backends: QEMU & AVF</a><a class="next" href="packages.html"><span class="dir">Next</span>Packages & services →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/packages.html b/docs/guide/packages.htmlindex 40275bb..c5c8fa1 100644--- a/docs/guide/packages.html+++ b/docs/guide/packages.html@@ -194,7 +194,7 @@<a class="prev" href="networking.html"><span class="dir">Previous</span>← Networking & ports</a><a class="next" href="desktop.html"><span class="dir">Next</span>Desktops & X11 viewer →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/performance.html b/docs/guide/performance.htmlindex 9456026..910111b 100644--- a/docs/guide/performance.html+++ b/docs/guide/performance.html@@ -146,7 +146,7 @@<a class="prev" href="how-it-works.html"><span class="dir">Previous</span>← How it works</a><a class="next" href="backends.html"><span class="dir">Next</span>Backends: QEMU & AVF →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/guide/settings.html b/docs/guide/settings.htmlindex a77d3d7..531a364 100644--- a/docs/guide/settings.html+++ b/docs/guide/settings.html@@ -82,6 +82,11 @@<td>Toggle</td><td>Uses your wallpaper's colors as the app accent palette. Android 12+ only.</td></tr>+ <tr>+ <td>Language</td>+ <td>System default / English / 中文 (Chinese)</td>+ <td>App interface language. Defaults to following the device language; changing it re-renders the UI right away.</td>+ </tr></tbody></table>@@ -137,7 +142,7 @@<tr><td>Port forwards</td><td>Add / Remove</td>- <td>Add TCP, UDP, or both forwarding rules. Changes apply live via QMP without a VM restart.</td>+ <td>Add TCP, UDP, or both forwarding rules. Changes apply live via QMP without a VM restart. Can also be managed from inside the VM with <code>podroid-forward</code> (see <a href="networking.html">Networking</a>).</td></tr><tr><td>Downloads sharing</td>@@ -198,7 +203,8 @@<a class="prev" href="desktop.html"><span class="dir">Previous</span>← Desktops & X11 viewer</a><a class="next" href="limitations.html"><span class="dir">Next</span>Limitations & troubleshooting →</a></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+</main></div>diff --git a/docs/guide/use-cases.html b/docs/guide/use-cases.htmlindex 573121e..c73a16b 100644--- a/docs/guide/use-cases.html+++ b/docs/guide/use-cases.html@@ -161,7 +161,7 @@<a class="prev" href="limitations.html"><span class="dir">Previous</span>← Limitations & troubleshooting</a><span></span></div>- <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.1. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p>+ <p class="docfoot">Podroid is free software (GPL). Docs for v1.2.3. Found something inaccurate? <a href="https://github.com/ExTV/Podroid/issues">Open an issue</a>.</p></main></div>diff --git a/docs/index.html b/docs/index.htmlindex 20a0902..1935b1f 100644--- a/docs/index.html+++ b/docs/index.html@@ -610,7 +610,7 @@<svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg></div><h3>Port Forwarding</h3>- <p>Expose any VM port to your Android device at runtime via QMP control. Run a web server, database, or API and hit it from your phone's browser.</p>+ <p>Expose any VM port to your Android device at runtime. Run a web server, database, or API and hit it from your phone's browser — from Settings, or with <code>podroid-forward</code> right inside the VM.</p></div><div class="feature-card">@@ -621,6 +621,14 @@<p>Dropbear SSH server on port 9922 (configurable). Connect from your laptop, VS Code Remote, or any SSH client on the same network.</p></div>+ <div class="feature-card">+ <div class="feature-icon">+ <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>+ </div>+ <h3>Notify from the VM</h3>+ <p>Run <code>podroid-notify "build done"</code> inside the guest and it pops an Android notification — with a title, priority, and an <code>--id</code> to update one in place. Perfect for long builds, downloads, and cron jobs. Works on both backends.</p>+ </div>+<div class="feature-card"><div class="feature-icon"><svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>@@ -653,6 +661,14 @@<p>KVM needs root, so we leaned hard on TCG instead. Multi-thread TCG with a 512 MB translation cache, a dedicated I/O thread for the rootfs disk, ZRAM lz4 swap at half RAM, and <code>mitigations=off</code> in the guest combine for a 5–15% CPU win. Native 16 KB page alignment, so Pixel 8/9/10 are first-class.</p></div>+ <div class="feature-card">+ <div class="feature-icon">+ <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>+ </div>+ <h3>English & 中文</h3>+ <p>Fully localized interface in English and Chinese, switchable in Settings or following your device language.</p>+ </div>+</div></div></section>diff --git a/skill.md b/skill.mddeleted file mode 100644index 7d099b2..0000000--- a/skill.md+++ /dev/null@@ -1,660 +0,0 @@-# Podroid AI Context--> **Last updated:** 2026-04-30-> **Current version:** 1.1.8 (versionCode 20)-> **Purpose:** Complete project context for AI-assisted development. Read this before touching any file.-------## Project Overview--**Podroid** is an Android app that runs rootless Podman containers on arm64 Android devices with no root required. It spins up a headless Alpine Linux 3.23 VM using QEMU TCG and exposes a serial console terminal inside the app.--- **Package:** `com.excp.podroid` (debug: `com.excp.podroid.debug`)-- **Min SDK:** 28 (Android 9.0)-- **Target SDK:** 36-- **Architecture:** AArch64 only (no x86/x86_64)-- **Root project name in Gradle:** `Podroid`-- **GitHub:** https://github.com/ExTV/Podroid-------## Tech Stack--| Layer | Technology |-|-------|------------|-| UI | Jetpack Compose + Material 3 |-| DI | Hilt (constructor injection, no @Provides) |-| Async | Kotlin Coroutines + StateFlow |-| Persistence | DataStore Preferences |-| Terminal | Termux TerminalView v0.118.1 (JitPack AAR) |-| VM | QEMU 11.0.0-rc2 TCG (no KVM) |-| Container Runtime | Podman + crun + netavark + slirp4netns |-| VM Init | Minimal initramfs (`init-podroid`, ~45 lines) + OpenRC PID 1 |-| VM System | Standard Alpine 3.23 squashfs + ext4 overlay (persistent) |-------## Architecture--### High-Level Flow-```-Android App-├── PodroidApplication — extracts assets (vmlinuz, initrd, alpine-rootfs.squashfs, qemu/) on first run (size-checked)-├── PodroidService (foreground) — hosts QEMU, holds WakeLock, updates notification with boot stages-├── PodroidQemu (singleton)-│ ├── QEMU process (libqemu-system-aarch64.so — ELF binary renamed .so for APK)-│ ├── /dev/vda — storage.img (writable ext4, persistent overlay upper, resized on first boot)-│ ├── /dev/vdb — alpine-rootfs.squashfs (read-only, gzip squashfs, overlay lower)-│ ├── serial.sock — ttyAMA0 boot-log sink; monitor stays connected for VM lifetime-│ ├── terminal.sock — virtio-console hvc0; primary shell I/O for podroid-bridge-│ ├── ctrl.sock — virtio-console hvc1; debounced RESIZE messages from bridge-│ └── qmp.sock — QEMU Machine Protocol for runtime control (port forwarding)-└── Compose UI- └── Screens: Setup → Home → Terminal / Settings-```--### VM Boot Sequence-1. QEMU starts and binds all four sockets (`server,nowait` so it doesn't block on a connection).-2. **Boot monitor** (`PodroidQemu.monitorBootSerial`) connects to `serial.sock` and streams everything kernel + init + OpenRC writes to ttyAMA0 into `console.log` + the in-memory rolling buffer used by `detectBootStage`. Stays connected for the lifetime of the VM (no hand-off).-3. `init-podroid` (initramfs, ~45 lines): mounts `/dev/vda` (ext4, mkfs if needed) at `/mnt/persist`, mounts `/dev/vdb` (squashfs) at `/mnt/lower`, stacks `overlay -o lowerdir=/mnt/lower,upperdir=/mnt/persist/upper,workdir=/mnt/persist/work` at `/mnt/overlay`, `mount --move`s the lower/persist into the new root, then `switch_root /mnt/overlay /sbin/init` (busybox init).-4. `/sbin/init` reads `/etc/inittab` and starts OpenRC. Runlevels are pre-symlinked at build time (`/etc/runlevels/default/{podroid-bootstrap,podroid-network,podroid-resize,dropbear,podroid-ready}`).-5. **podroid-bootstrap** (OpenRC service on squashfs): cgroup v2, devpts/shm/mqueue, sysctl, ZRAM, `mount --make-rshared /`, chmod 0666 /dev/{net/tun,fuse}, hostname.-6. **podroid-network**: `ip link set eth0 up`, assign 10.0.2.15/24, default route 10.0.2.2, write `/etc/resolv.conf` (8.8.8.8, 1.1.1.1).-7. **podroid-ready**: emits `Starting SSH...`, `Almost ready...`, `Ready!` markers consumed by `detectBootStage()`.-8. `detectBootStage("Ready!")` fires → `_state = Running` → `autoStartBridge()` posts to the main thread.-9. `TerminalSession` launches `libpodroid-bridge.so` with `terminal.sock` + `ctrl.sock`. Bridge connects directly to virtio-console hvc0 (which getty owns via `podroid-login`).--### Why switch_root and not chroot-The old init-podroid did `chroot /mnt/overlay`. Inside `crun exec`, `setns(CLONE_NEWNS)` resets `fs->root` — so namespace forks saw raw kernel paths (`/mnt/overlay/proc` instead of `/proc`), which is the root cause of issue #17 (`podman exec -it` failing with `crun: open /dev/ptmx: No such device`). `switch_root` reorganizes the kernel mount tree itself, so subsequent namespace operations land on a clean `/`.--### No socket hand-off-The old PL011 path used a single-client `serial.sock` shared by the boot monitor and the bridge, which forced a `releaseSerial()` + delay dance. With the virtio-console split that constraint is gone. `releaseSerial()` only runs during `cleanup()` on VM stop now.-------## Performance Tuning (TCG, no KVM)--All tuning applies under software emulation only — KVM is impossible without root.--**In `PodroidQemu.buildCommand()`:**-- `tcg,thread=multi` — one host thread per vCPU.-- `tb-size`: 256 MB for <2 GB RAM, 512 MB for ≥2 GB — larger Translation Block cache reduces re-translation for JIT-heavy workloads (Node, JVM in containers).-- `iothread=iothread0` on `virtio-blk-pci` — dedicated I/O thread decoupled from vCPU threads; biggest win for container image pull/extraction.-- `mitigations=off` in guest kernel cmdline — safe inside TCG VM (speculative execution attacks can't cross the emulated ISA boundary); 5–15% CPU gain.-- `elevator=mq-deadline` in guest kernel cmdline — request merging for virtio-blk random writes (Podman overlay graph driver).--**In `podroid-bootstrap` (OpenRC service):**-- ZRAM swap at half physical RAM using lz4 — gives 1.5–2× effective memory with near-zero I/O cost; swapon at priority 100 so it's preferred over any file swap.-- `CONFIG_EXT4_FS_SECURITY=y` and `CONFIG_SQUASHFS_XATTR=y` are required so `security.capability` xattrs survive the overlay — without them `newuidmap`/`newgidmap` lose their `cap_setuid+ep` / `cap_setgid+ep` capabilities and rootless podman fails.--**In `Dockerfile` (QEMU build):**-- Currently `-fPIC -DANDROID` only (no LTO / -O3) — those previously caused link failures with QEMU 11.0.0-rc2 + NDK r27c. Three minimum patches make the build clean: `--disable-plugins`, empty `contrib/ivshmem-{server,client}/meson.build` stubs, and an `-include shm_shim.h` + `libshm.a` (memfd_create-backed) to satisfy `shm_open`/`shm_unlink`.-------## Project Structure--### Root Level-```-/-├── app/ # Android application module-├── init-podroid # Minimal initramfs script (~45 lines) — mounts overlay, switch_root-├── podroid-bridge.c # Native PTY↔virtio-console relay (compiled to libpodroid-bridge.so)-├── Dockerfile # Kernel + initramfs + QEMU multi-stage build-├── build-rootfs/ # Separate Docker pipeline for the Alpine squashfs-│ ├── Dockerfile.rootfs # apk-installs Alpine, mksquashfs -comp gzip-│ ├── build-rootfs.sh # apk install list, doas/sudo wheel rules, file caps, runlevel symlinks-│ └── files/ # OpenRC services + helpers baked into the squashfs-│ ├── etc/init.d/podroid-{bootstrap,network,resize,ready}-│ ├── etc/{inittab,rc.conf,conf.d/podroid}-│ └── usr/local/bin/podroid-{login,resize}-├── build-all.sh # Unified build+deploy script (kernel/initramfs/rootfs/qemu/termux/apk)-├── gradle.properties # podroidQemuVersion=11.0.0-rc2, podroidKernelVersion-├── build.gradle.kts, settings.gradle.kts-└── gradle/, gradlew-```--### app/src/main/java/com/excp/podroid/--```-├── MainActivity.kt # Single Activity, WindowSizeClass, Hilt entry point-├── PodroidApplication.kt # Hilt @HiltAndroidApp, asset extraction on first run-│-├── engine/-│ ├── PodroidQemu.kt # QEMU lifecycle, boot monitor, bridge session, resize-│ ├── QmpClient.kt # QMP socket client (runtime port forwarding)-│ └── VmState.kt # Sealed: Idle|Starting|Running|Paused|Saving|Resuming|Stopped|Error-│-├── service/-│ └── PodroidService.kt # Foreground service, WakeLock, notification with boot stages-│ └── Actions: ACTION_START, ACTION_STOP-│-├── data/repository/-│ ├── SettingsRepository.kt # DataStore Preferences (all settings)-│ ├── PortForwardRepository.kt # Port forward rules (Set<String> in DataStore)-│ └── UpdateRepository.kt # GitHub releases API checker-│-├── di/-│ └── AppModule.kt # Hilt module (minimal — constructor injection used everywhere)-│-└── ui/- ├── navigation/- │ └── NavGraph.kt # Routes: SETUP, HOME, TERMINAL, SETTINGS- │ └── TerminalViewModel scoped OUTSIDE NavHost (survives screen navigation)- │- ├── theme/- │ ├── Theme.kt # Material You dynamic colors + dark/light- │ ├── Color.kt # Purple80/Grey80/Cyan80 + status colors- │ └── Type.kt # Default Material 3 typography- │- ├── HapticManager.kt # Centralized haptics: extraKeyPress, longPressMenu, bell, error- │- └── screens/- ├── setup/- │ ├── SetupScreen.kt # 3-page HorizontalPager: Storage / VM config+SSH / Downloads- │ └── SetupViewModel.kt # completeSetup() → DataStore, notification permission request- │- ├── home/- │ ├── HomeScreen.kt # Start/Stop/Restart VM, open terminal, update dialog, AdaptiveContainer- │ ├── HomeViewModel.kt # checkForUpdate(), startPodroid(), stopVm(), restartVm()- │ └── AnimatedBootProgress.kt # Rotating arc Canvas + boot stage text (replaces CircularProgressIndicator)- │- ├── terminal/- │ ├── TerminalScreen.kt # TerminalView composable, extra keys bar, focus observer, pushSize- │ ├── TerminalViewModel.kt # Session wiring, CSI keys, focus events, font/theme, forceUpdateSizeFromView- │ ├── ExtraKey.kt # sealed KeyAction + JSON serde via ExtraKeySerde- │ ├── DefaultKeyLayouts.kt # Built-in layouts: minimal, full (nvim/shell)- │ └── QuickSettingsDrawer.kt # Bottom-sheet: font size, theme, font, extras toggle, haptics- │- ├── settings/- │ ├── SettingsScreen.kt # Sections: VM Resources / Network / Appearance / Diagnostics / About- │ │ # Terminal settings moved to QuickSettingsDrawer (NOT here)- │ └── SettingsViewModel.kt # Port forward CRUD, VM reset, console log export- │- └── components/- └── AdaptiveContainer.kt # WindowSizeClass-based max-width wrapper (tablet/foldable)-```--### Assets (app/src/main/assets/)-```-├── vmlinuz-virt # Custom Linux 6.6.87 kernel (built by Dockerfile)-├── initrd.img # Minimal initramfs (only needs to mount overlay + switch_root)-├── alpine-rootfs.squashfs # ~41 MB Alpine 3.23 squashfs (built by build-rootfs/) — mounted as /dev/vdb-├── qemu/-│ ├── efi-virtio.rom-│ └── keymaps/-├── colors/ # 114 terminal color schemes (.properties files)-└── fonts/ # 13 terminal fonts (.ttf)- └── JetBrains-Mono.ttf, Fira-Code.ttf, CascadiaCode.ttf, etc.-```--All three large blobs (vmlinuz-virt, initrd.img, alpine-rootfs.squashfs) are gitignored — built locally and extracted from APK assets into `filesDir` on first run by `PodroidApplication.copyAssetIfNeeded()`.--### Native Libs (app/src/main/jniLibs/arm64-v8a/)--**Note:** All native binaries require 16KB page alignment (`-Wl,-z,max-page-size=16384`) — mandatory on Android 13+.--| File | What it is |-|---|---|-| `libqemu-system-aarch64.so` | QEMU TCG emulator (PIE executable, 16KB aligned) |-| `libpodroid-bridge.so` | PTY ↔ virtio-console relay (PIE executable, 16KB aligned) |-| `libtermux.so` | Termux terminal emulator JNI (rebuilt for 16KB pages) |-| `libslirp.so` | SLIRP user-mode networking (statically linked into QEMU) |-------## Key Constants & Values--| Item | Value |-|------|-------|-| podroidKernelVersion | Set in `gradle.properties` (controls kernel source version) |-| QEMU binary | `libqemu-system-aarch64.so` in `nativeLibraryDir` |-| Kernel | `filesDir/vmlinuz-virt` |-| Initrd | `filesDir/initrd.img` |-| Storage image | `filesDir/storage.img` (ext4, sparse, /dev/vda — overlay upper) |-| Rootfs squashfs | `filesDir/alpine-rootfs.squashfs` (read-only, /dev/vdb — overlay lower) |-| serial.sock | `filesDir/serial.sock` — ttyAMA0, boot-log only; monitor stays connected for VM lifetime |-| terminal.sock | `filesDir/terminal.sock` — virtio-console hvc0; primary terminal for podroid-bridge |-| ctrl.sock | `filesDir/ctrl.sock` — virtio-console hvc1; bridge writes debounced `RESIZE rows cols\n` |-| qmp.sock | `filesDir/qmp.sock` |-| VM IP | 10.0.2.15/24 (SLIRP) |-| Gateway | 10.0.2.2 |-| DNS (SLIRP) | 10.0.2.3 (unreliable on Android) + 8.8.8.8, 1.1.1.1 |-| SSH host port | 9922 → VM:22 (Dropbear, password "podroid") |-| Default RAM | 512 MB (range: 512–4096) |-| Default CPUs | 1 (range: 1, 2, 4, 6, 8) |-| Default font size | 20sp |-| Default storage | 2 GB (range: 2–64 GB) |-| QEMU machine | `-M virt,gic-version=3 -smp <cpus> -m <ramMb>`; tunable extras (`-cpu`, `-accel`, RNG, etc.) come from the user-editable Settings field |-| Kernel cmdline | `console=ttyAMA0 <user-extras> androidip=<ip> [ssh=1]` (default user-extras: `loglevel=1 quiet mitigations=off elevator=mq-deadline`) |-------## Boot Stage Strings (OpenRC services → detectBootStage)--These exact strings are emitted by the boot pipeline and matched by `PodroidQemu.detectBootStage()`:--| String in serial output | Source | Android UI label |-|------------------------|--------|-----------------|-| `Mounting storage...` | PodroidQemu (pre-launch) | "Mounting storage..." |-| `Booting kernel...` | PodroidQemu (pre-launch) | "Booting kernel..." |-| `Starting SSH...` | `podroid-ready` | "Starting SSH..." |-| `Almost ready...` | `podroid-ready` | "Almost ready..." |-| `Ready!` | `podroid-ready` | "Ready" → state = Running → autoStartBridge() |--The earlier intermediate stages (`Initializing system...`, `Loading kernel modules...`, `Network found`, `Configuring containers...`) were tied to the old monolithic init-podroid; with OpenRC, the relevant init steps are short enough that only the SSH / Almost ready / Ready trio matters for UI feedback.-------## init-podroid Structure (post-OpenRC migration)--The initramfs script is now ~45 lines and does the absolute minimum: mount overlay, switch_root.--```sh-#!/bin/sh-mount -t proc proc /proc-mount -t sysfs sys /sys-mount -t devtmpfs dev /dev--# /dev/vda = persistent ext4 (writable upper); /dev/vdb = squashfs (read-only lower)-PERSIST=/dev/vda-LOWER=/dev/vdb--# mkfs.ext4 on first boot if vda is blank, then mount-mount -t ext4 $PERSIST /mnt/persist || (mkfs.ext4 -F $PERSIST && mount -t ext4 $PERSIST /mnt/persist)-mount -t squashfs -o ro $LOWER /mnt/lower--mkdir -p /mnt/persist/upper /mnt/persist/work /mnt/overlay-mount -t overlay overlay \- -o lowerdir=/mnt/lower,upperdir=/mnt/persist/upper,workdir=/mnt/persist/work \- /mnt/overlay--# Move lower + persist into the new root tree so OpenRC services can see them-mkdir -p /mnt/overlay/mnt/lower /mnt/overlay/mnt/persist-mount --move /mnt/lower /mnt/overlay/mnt/lower-mount --move /mnt/persist /mnt/overlay/mnt/persist--exec switch_root /mnt/overlay /sbin/init-```--After `switch_root`, busybox `/sbin/init` reads `/etc/inittab` and starts OpenRC. The squashfs ships pre-symlinked runlevels, so no chroot-into-aarch64 was needed at build time.--### OpenRC Services (build-rootfs/files/etc/init.d/)--| Service | Runlevel | Responsibility |-|---------|----------|----------------|-| `podroid-bootstrap` | default | cgroup v2 unified hierarchy, devpts/shm/mqueue, sysctl (net.ipv4.ip_forward=1, kernel.unprivileged_userns_clone=1), ZRAM swap, `mount --make-rshared /`, chmod 0666 /dev/{net/tun,fuse}, hostname |-| `podroid-network` | default | `ip link set eth0 up`, IP 10.0.2.15/24, default route 10.0.2.2, /etc/resolv.conf |-| `podroid-resize` | default | Daemon reading `RESIZE rows cols` lines from /dev/hvc1, running `stty rows N cols M < /dev/hvc0` |-| `podroid-ready` | default | Emits the boot-stage markers consumed by `detectBootStage` |-| `dropbear` | default | SSH (only when ssh=1 in kernel cmdline — guard logic in podroid-bootstrap) |--### podroid-login (build-rootfs/files/usr/local/bin/podroid-login)-```bash-#!/bin/bash-cat /etc/motd 2>/dev/null-exec /bin/bash --login-```-No `script` wrapper needed any more — virtio-console (`/dev/hvc0`) reports a real `TIOCGWINSZ` via the resize daemon, so nvim/btop work without a fake PTY.-------## Terminal Architecture--### Data Flow-```-Keyboard → TerminalView → TerminalSession.write() → PTY master fd- ↓- podroid-bridge stdin (PTY slave)- ↓- terminal.sock → /dev/hvc0 in VM-VM output → /dev/hvc0 → terminal.sock → bridge stdout → PTY slave → TerminalEmulator → TerminalView-Resize → TerminalView.updateSize() → TIOCSWINSZ on PTY → SIGWINCH → bridge- → bridge debounces 200 ms → TIOCGWINSZ- → writes "RESIZE rows cols\n" to ctrl.sock- → init resize daemon reads /dev/hvc1- → stty rows N cols M < /dev/hvc0- → Linux SIGWINCH to VM fg process group-Mouse → TerminalView touch handler → PTY → bridge → terminal.sock → VM-```--### PodroidQemu Key Methods--| Method | What it does |-|--------|-------------|-| `start(portForwards, ramMb, cpus, sshEnabled, androidIp)` | Launches QEMU process, starts boot monitor coroutine, 60s timeout fallback |-| `monitorBootSerial(proc)` | Reads serial.sock, appends to consoleBuilder + console.log, calls detectBootStage() |-| `detectBootStage()` | Scans the last 1024 chars of `consoleBuilder` (stateful rolling buffer) and matches boot-stage strings; sets _bootStage and _state. The rolling buffer was added in 1.1.5 to survive markers split across `read()` chunks on fast devices (e.g. Pixel 10 Pro XL was missing "Ready!" and falling back to the 60 s timeout). |-| `releaseSerial()` | shutdownInput + shutdownOutput + close on bootSocket |-| `autoStartBridge()` | Posts to MainLooper, calls releaseSerial(), 500ms delay, creates TerminalSession |-| `createTerminalSession(client)` | Returns pre-started session or creates new one; sets sessionClientDelegate |-| `replayBootOutput(sess)` | Appends post-"Ready!" serial bytes to new emulator (so first screen isn't blank) |-| `cleanup()` | Cancels ioScope, kills session, deletes socket files |--### TerminalViewModel Key Patterns--**`forceUpdateSizeFromView(view)`**: Computes cols/rows from `Paint` metrics using `currentTypeface` and raw `terminalFontSize.value.toFloat()` (NO scaledDensity multiplication — matches TerminalView's internal path exactly). Must use `currentTypeface` not `Typeface.MONOSPACE` for custom fonts.--**`pushSizeNow()`**: Fires `v.updateSize()` immediately + at 300ms + 800ms. Called after font size changes and after closing QuickSettings.--**`forceUpdateSizeFromView` via pushSize in TerminalScreen**: Fires at 0/150/600/1500ms after layout change to outlast lazy layout settling.--**Focus events**: `TerminalScreen` installs `LifecycleEventObserver`. ON_RESUME → `sendFocusEvent(true)` → `\x1b[I`. ON_PAUSE → `sendFocusEvent(false)` → `\x1b[O`. Gated on DECSET 1004 via reflection on `mCurrentDecSetFlags`.--**Proxy sessionClient** (`proxySessionClient` in PodroidQemu): Delegates to `sessionClientDelegate`. Lets session be created at boot-complete time before UI exists. TerminalViewModel sets itself as delegate via `qemu.sessionClientDelegate = sessionClient`.--### Key Sequences (TerminalViewModel.viewClient.onKeyDown)--```-mod = 1 + (shift?1:0) + (alt?2:0) + (ctrl?4:0)-arrow(final): if mod==1 → "\x1b[$final" else → "\x1b[1;$mod$final"-```--| Key | Sequence |-|-----|----------|-| Shift+Tab | `\x1b[Z` |-| Ctrl+Left/Right | `\x1b[1;5D` / `\x1b[1;5C` |-| Shift+Up/Down | `\x1b[1;2A` / `\x1b[1;2B` |-| F1–F4 | `\x1bOP` … `\x1bOS` |-| F5–F12 | `\x1b[15~` … `\x1b[24~` |--**Bracketed paste**: `onPasteTextFromClipboard` calls `emu.paste(text)` — Termux wraps in `\x1b[200~…\x1b[201~` when DECSET 2004 is active.--**Extra keys hold-to-repeat**: `KeyButton` composable uses `pointerInput + LaunchedEffect` — 400ms initial delay then 70ms → 30ms accelerating cadence. Only arrow keys flagged `repeatable = true`.--**CTRL/ALT sticky**: `extraCtrl` / `extraAlt` toggles on the extras bar. Consumed after any non-modifier key press.-------## podroid-bridge.c--- **Purpose**: Relay PTY (Termux-allocated) ↔ `terminal.sock` (QEMU virtio-console / hvc0).-- **Arguments**: `bridge_exe terminal_sock_path ctrl_sock_path`.-- **STDERR silenced** immediately via `dup2(/dev/null, STDERR_FILENO)` — bridge runs as TerminalSession subprocess so stderr IS the PTY.-- **`cfmakeraw()`** on own stdin (VM's getty handles echo/line editing).-- **terminal.sock retry**: 50 attempts × 200 ms = 10 s max.-- **ctrl.sock retry**: 50 × 100 ms = 5 s max; lazy reconnect on each SIGWINCH if not yet connected.-- **`send_resize()`**: reads new size via `TIOCGWINSZ`, writes `RESIZE rows cols\n` to ctrl.sock.-- **SIGWINCH debounce**: every signal just refreshes a `clock_gettime(CLOCK_MONOTONIC)` timestamp; the actual `send_resize()` only fires once the burst has been quiet for `RESIZE_DEBOUNCE_MS` (200 ms). Collapses the ~25 per-frame layout changes during an Android keyboard slide into a single shell prompt redraw.-- **select timeout**: 50 ms — wakes the loop frequently enough to fire the debounced resize on schedule.-- The old `filter_queries()` intercept (`ESC[18t`/`ESC[19t` xterm size queries) is gone — virtio-console reports real `TIOCGWINSZ` inside the guest, so apps don't need the workaround.-------## Build Pipelines--There are now **two** Docker pipelines:--### `Dockerfile` (kernel + initramfs + QEMU)-Custom Linux 6.6.87 (built from upstream tarball) + minimal initramfs (only `init-podroid` + a busybox + switch_root) + QEMU 11.0.0-rc2 cross-compiled against NDK r27c. Forced `=y` options include `EXT4_FS_SECURITY`, `SQUASHFS_XATTR`, `SQUASHFS_ZLIB`, `OVERLAY_FS`, `FUSE_FS`, `BRIDGE`, `IPV6`, `NF_TABLES`, `NFT_COMPAT`, MASQUERADE family, `VETH`, `TUN`. A build-time check fails the build if any go missing (silent Kconfig demotion guard).--### `build-rootfs/Dockerfile.rootfs` (Alpine squashfs)-Pulls `alpine-minirootfs-3.23.4-aarch64.tar.gz`, runs `build-rootfs.sh` to apk-install the userland (alpine-base, openrc, busybox-openrc, bash, podman, crun, fuse-overlayfs, iptables/ip6tables/nftables, slirp4netns, aardvark-dns, netavark, dropbear, shadow-uidmap, libcap-utils, doas, sudo, ca-certificates), seal the right caps on newuidmap/newgidmap, set wheel-group sudo/doas rules, copy in the OpenRC service files and /etc configs, then `mksquashfs -comp gzip -all-root -noappend` (no `-no-xattrs` so security.capability is preserved). Output: `app/src/main/assets/alpine-rootfs.squashfs` (~41 MB).--**Why gzip and not lz4/zstd**: the kernel only enables `CONFIG_SQUASHFS_ZLIB=y`. lz4 squashfs fails to mount.--### QEMU Build Details-- NDK r27c, API 28 sysroot-- Dependencies (static): pcre2, libffi, glib 2.82.5, pixman 0.44.2, libattr, libucontext-- **libucontext shim**: Android Bionic lacks `ucontext.h` → built from kaniini/libucontext; header shim remaps `getcontext/swapcontext/etc.` to libucontext functions-- **`--with-coroutine=ucontext`**: Required for ARMv9.2 PAC (Android 15+ Tensor devices) — avoids SIGILL from siglongjmp across alternate signal stacks-- **librt optional** patch: Bionic includes librt functions in libc-- **`st_*_nsec` undef** patch: Android's `sys/stat.h` macros clash with 9p struct fields-- **patchelf**: libslirp soname patched from `libslirp.so.0` → `libslirp.so`--### 16KB Page Alignment-All native libs must have `p_align >= 16384`. Enforced via `-Wl,-z,max-page-size=16384` everywhere. Required for Android devices with 16KB system pages. Verified by Python ELF parser in `build-all.sh`.--### VM Rootfs Packages (Alpine 3.23 aarch64, build-rootfs.sh)-```-alpine-base openrc busybox-openrc bash-podman crun fuse-overlayfs aardvark-dns netavark slirp4netns-iptables ip6tables nftables bridge-utils iproute2-dropbear dropbear-openrc curl ca-certificates-shadow shadow-uidmap libcap-utils doas sudo-```-Plus runtime config: root password "podroid", `/etc/doas.d/doas.conf` = `permit persist :wheel`, `/etc/sudoers.d/wheel` = `%wheel ALL=(ALL) ALL`. Users created with `adduser -G wheel <name>` can run `doas` / `sudo` after entering their password.-------## Build Commands--All components are coordinated by `build-all.sh`:--```bash-./build-all.sh kernel # Build custom kernel only (podroid_kernel.config, ~5–10 min)-./build-all.sh initramfs # Build kernel + minimal initramfs (~10–15 min)-./build-all.sh rootfs # Build Alpine squashfs (~30 s, Docker-cached)-./build-all.sh qemu # Build QEMU + podroid-bridge via Docker (~30 min first time)-./build-all.sh termux # Build libtermux.so via local NDK (16KB page alignment)-./build-all.sh apk # Build Android APK via Gradle-./build-all.sh all # Build everything-./build-all.sh deploy # Full deploy workflow-./build-all.sh test # Boot validation: deploys APK, polls console.log for "Ready!"-```--**APK only:**-```bash-./gradlew assembleDebug-./gradlew installDebug-```--**Fast bridge rebuild (without full Docker QEMU build):**-```bash-NDK=$HOME/Android/Sdk/ndk/$(ls ~/Android/Sdk/ndk/ | tail -1)-CC=$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android28-clang-$CC --sysroot=$NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot \- -target aarch64-linux-android28 -fPIE -pie -Wl,-z,max-page-size=16384 \- podroid-bridge.c -o app/src/main/jniLibs/arm64-v8a/libpodroid-bridge.so-./gradlew :app:installDebug-```--**Monitor VM boot:**-```bash-adb logcat -s PodroidQemu-adb shell run-as com.excp.podroid.debug cat files/console.log-```--**Workflow**:-- `init-podroid` changed → `./build-all.sh initramfs` → `gradlew assembleDebug` → `adb install`-- `build-rootfs/files/**` or package list → `./build-all.sh rootfs` → `gradlew assembleDebug` → `adb install`-- Kotlin/Java only → `gradlew assembleDebug` → `adb install`-- `podroid-bridge.c` changed → fast bridge rebuild above → `adb install`-- Check boot: `adb shell run-as com.excp.podroid.debug cat files/console.log`-------## DataStore Keys (SettingsRepository)--| Key | Type | Default | Description |-|-----|------|---------|-------------|-| `dark_theme` | Boolean | true | Dark mode |-| `vm_ram_mb` | Int | 512 | VM RAM (512/1024/2048/4096 MB) |-| `vm_cpus` | Int | 1 | VM CPUs (1/2/4/6/8) |-| `terminal_font_size` | Int | 20 | Font size (sp, raw — no scaledDensity) |-| `terminal_color_theme` | String | "default" | Color scheme name (maps to assets/colors/*.properties) |-| `terminal_font` | String | "default" | Font name (maps to assets/fonts/*.ttf) |-| `storage_gb` | Int | 2 | Persistent storage size (GB) |-| `storage_access_enabled` | Boolean | false | Downloads sharing via virtio-9p |-| `setup_done` | Boolean | false | Initial setup completed |-| `ssh_enabled` | Boolean | false | Dropbear SSH in VM |-| `usb_passthrough_enabled` | Boolean | false | Hot-plug USB devices into the VM (adds `-device qemu-xhci`; QEMU backend only) |-| `port_forwards` | Set\<String\> | {} | `"tcp:8080:80"` format |-| `dismissed_update_version` | String | "" | Last dismissed update version |-------## Port Forwarding--```-PortForwardRule(hostPort=8080, guestPort=80, protocol="tcp")-Serialized as: "tcp:8080:80"-```--- **At boot**: passed as QEMU `-netdev user,hostfwd=tcp::8080-:80` args-- **At runtime**: QMP `human-monitor-command hostfwd_add` / `hostfwd_remove`-- **SSH preset**: always forwarded as `tcp::9922-:22` when `sshEnabled = true`-- **Service presets** (SettingsScreen): Pi-hole (5300→53, 8080→80), Nginx (8080→80, 8443→443), Gitea (3000→3000, 2222→22), Grafana (3001→3000)-- **Pi-hole DNS**: host port 5300 used because Android blocks ports < 1024-------## Permissions--| Permission | Purpose |-|------------|---------|-| `INTERNET` | SLIRP, QMP socket, GitHub API |-| `ACCESS_NETWORK_STATE` | Get device IP for display |-| `WAKE_LOCK` | Keep CPU alive during VM |-| `VIBRATE` | Terminal bell, haptic feedback |-| `FOREGROUND_SERVICE` | Host QEMU process |-| `FOREGROUND_SERVICE_SPECIAL_USE` | QEMU "emulation" subtype |-| `POST_NOTIFICATIONS` | Android 13+ notification |-| `MANAGE_EXTERNAL_STORAGE` | Downloads sharing via virtio-9p |-------## Design Patterns & Quirks--### Architecture-- **Single Activity**: Compose Navigation with NavHost-- **TerminalViewModel scoped outside NavHost**: Survives navigation between screens; session persists-- **Proxy sessionClient**: `proxySessionClient` in PodroidQemu delegates to `sessionClientDelegate`; lets session be pre-created at boot before UI attaches-- **Reflection**: `TerminalView.mTermSession`, `mEmulator`, `TerminalEmulator.mCurrentDecSetFlags`, `mapDecSetBitToInternalBit` — all accessed reflectively (Termux AAR private fields)-- **VmState flow**: Idle → Starting → Running → Stopped/Error; service/UI observe via StateFlow--### Known Quirks-- **QEMU + bridge packaged as `.so`**: ELF executables renamed to `.so` for APK packaging; `nativeLibraryDir` extraction still works-- **libslirp soname patched**: `libslirp.so.0` → `libslirp.so` via patchelf (Android linker needs exact match)-- **libtermux.so custom-built**: Termux prebuilt uses 4KB pages; rebuilt with `-Wl,-z,max-page-size=16384`-- **Root project name is "Podroid"**: In `settings.gradle.kts`-- **Room declared but unused**: DataStore used instead-- **Downloads sharing via 9p**: `msize=1048576,cache=loose,noatime` — 128× fewer round-trips vs default 8KB msize-- **QEMU DNS forwarder (10.0.2.3) unreliable on Android**: init-podroid uses 8.8.8.8 + 1.1.1.1 directly-- **No ICMP in SLIRP**: `ping` doesn't work inside VM (QEMU SLIRP limitation)-- **forceUpdateSizeFromView must NOT multiply by scaledDensity**: TerminalView passes raw int textSize to Paint.setTextSize; our computation must match or TUI apps render in wrong grid-- **Bridge stderr silenced**: bridge runs as TerminalSession subprocess, its stderr IS the PTY; any write would bleed into the terminal. Never add `fprintf(stderr, ...)` to podroid-bridge.c-- **seenActive flag in PodroidService**: Prevents premature wakelock release on service start before VM reaches Running state-------## Common Tasks Reference--### Rebuild initramfs (init-podroid changed)-```bash-./build-all.sh initramfs && ./gradlew assembleDebug && adb uninstall com.excp.podroid.debug; adb install -r app/build/outputs/apk/debug/app-debug.apk-```--### Rebuild rootfs squashfs (OpenRC services / package list changed)-```bash-./build-all.sh rootfs && ./gradlew assembleDebug && adb install -r app/build/outputs/apk/debug/app-debug.apk-```--### Check VM console output-```bash-adb shell run-as com.excp.podroid.debug cat files/console.log-```--### Add a new boot stage-1. `echo "My stage..." > /dev/console` (or use the `boot_stage` helper) in the appropriate OpenRC service under `build-rootfs/files/etc/init.d/`-2. Add match in `PodroidQemu.detectBootStage()`-3. Rebuild rootfs (`./build-all.sh rootfs`)--### Add a setting-1. Add DataStore key + Flow in `SettingsRepository.kt`-2. Add UI in `SettingsScreen.kt` (Slider/Switch)-3. Add setter in `SettingsViewModel.kt`-4. Pass to `PodroidQemu.start()` if VM-time setting--### Add a port forward preset-1. Add to `servicePresets` list in `SettingsScreen.kt`--### Add terminal color theme-1. Add `.properties` file to `app/src/main/assets/colors/`-2. Appears automatically in QuickSettingsDrawer picker--### Add terminal font-1. Add `.ttf` to `app/src/main/assets/fonts/`-2. Appears automatically in QuickSettingsDrawer picker--### Modify QEMU arguments-1. Edit `PodroidQemu.buildCommand()`--### Add a new VM control channel message-1. Add write to `ctrl.sock` in `podroid-bridge.c`-2. Add handler in `build-rootfs/files/usr/local/bin/podroid-resize` (the daemon reading from `/dev/hvc1`)-------## Dependency Versions (gradle/libs.versions.toml)--| Library | Version |-|---------|---------|-| Android Gradle Plugin | 9.1.0 |-| Kotlin | 2.2.21 |-| KSP | 2.3.6 |-| Compose BOM | 2026.03.01 |-| Navigation Compose | 2.9.7 |-| Hilt | 2.59.2 |-| Coroutines | 1.9.0 |-| DataStore | 1.2.1 |-| Termux terminal-view | v0.118.1 (JitPack) |-| Lifecycle | 2.9.0 |-| Activity Compose | 1.10.1 |-| WindowSizeClass | material3-adaptive (Compose BOM) |-| Room | 2.8.4 (declared, NOT used) |-------## ProGuard--`app/proguard-rules.pro` keeps Termux reflection targets:-- `TerminalView.mTermSession`-- `TerminalView.mEmulator`-------## Pending Work (as of 2026-04-30)--### Next Feature: Container Hub-Full container management screen — SSH into VM at `127.0.0.1:9922`, run `podman ps`, one-tap deploy from a catalog of services (Pi-hole, Vaultwarden, code-server, Gitea, Jellyfin, Uptime Kuma, Filebrowser, Nginx, Grafana). Requires JSch dependency.--### Other TODOs-- **Pin Dockerfile packages**: Add version pins to prevent reproducibility breaks-- **DNS configurable**: Currently hardcoded 8.8.8.8 + 1.1.1.1; add settings UI-- **Overlay mount validation**: Detect and surface overlay failures with actionable error-- **Terminal title → TopAppBar**: Wire `onTitleChanged()` to update app bar from OSC sequences--### Recently shipped (1.1.8)-- **Vendored Termux fork (`MatanZ/sixel4`)**: `terminal-emulator` and `terminal-view` now live as local Gradle subprojects (not JitPack AARs), so we can patch the parser without a fork-and-publish dance. Replaces upstream Termux v0.118.1.-- **Sixel + iTerm2 image protocols**: Inline images render in the in-app terminal via `chafa`, `lsix`, `kitty +kitten icat`, lazygit thumbnails, etc.-- **Kitty graphics protocol** (minimum-viable: `a=T,f=100,t=d,m=0/1,c=,r=`): multi-chunk PNG inline rendering, used by yazi/lf/fzf preview.-- **DECSET 2026 synchronized output**: Atomic-frame mode advertised + honored — btop / nvim / lazygit no longer flicker mid-redraw.-- **OSC 8 hyperlinks**: tap-to-open URLs from `git`, `lazygit`, `gh` output. Region-list lookup avoids per-cell metadata.-- **HarfBuzz ligatures**: `'liga' on, 'calt' on` Paint feature → JetBrains Mono / FiraCode / Cascadia render `===`, `=>`, `!=` etc. as fused glyphs.-- **XTVERSION (`CSI > 0 q`) responder**: emulator answers `\eP>|Podroid <ver>\e\` so modern apps (Neovim ≥0.10) detect us correctly.-- **Sixel parser fixes** (upstream sixel4 had two bugs we patched locally): the `Pa;Pb;Pcq` intro form (chafa's default) was rejected; the multi-part flush trigger missed `$` and `-`. Both fixed.-- **Custom font import (Quick Settings → `+ Add` → SAF picker)**: drop in any `.ttf`, long-press to delete. Files live in app-private external dir; no permission prompts.-- **Custom theme import** from `terminalcolors.com` URLs: paste a theme page URL; we fetch the Alacritty TOML export, parse, and convert to our `.properties` format.-- **Top-sheet Quick Settings** (replaces sliding chip rows): drops down from header, font size slider, 4 visible chips per picker + `More` (search-aware full picker) + `+ Add` (font/theme import). Adapts portrait/landscape via height cap + scroll.-- **PAC-free QEMU coroutine** (`libqemujmp` shim): replaces Bionic's `sigsetjmp`/`siglongjmp` in `coroutine-ucontext.c` with raw aarch64 asm that doesn't use PAC. Fixes the SIGILL crash on Pixel 10 Pro XL when Downloads sharing was enabled.-- **PR_SET_PDEATHSIG launcher** (`libpodroid-launcher.so`): tiny wrapper that sets the parent-death signal before `execv`'ing QEMU, so the VM dies with the app instead of orphaning under PPID=1 across uninstalls/OOM/force-stop.-- **64 KB PTY buffers + dedup'd MSG_NEW_INPUT + reused RectF**: terminal-layer perf — fewer wakeups, less GC pressure on image-heavy frames.-- **`COLORTERM=truecolor` baked into rootfs** via `/etc/profile.d/podroid-color.sh` so apps detect 24-bit support.-- **`-cpu max,sve=off` and `tb-size=512`**: SVE's variable-length vector instructions are expensive to TCG-translate and unused by Node/Podman/etc.; disabling speeds general workloads. Bigger TB cache helps JIT-heavy guests like V8.-- **Kernel cmdline cleanups**: removed deprecated `elevator=mq-deadline` (now set per-device in `podroid-bootstrap` via sysfs); 9p `msize` lowered to virtio's actual cap (512000) to silence kernel warning.-- **Update-dialog version compare fix**: `1.1.x-debug` no longer shows up as "older than 1.1.x" in the update prompt.-- **Cursor-flicker on keyboard slide fix**: removed redundant `forceUpdateSizeFromView` call from layout listener (was racing with `tv.updateSize()` and triggering double resize).--### Recently shipped (1.1.7)-- **Zero-config Docker**: `podroid-bootstrap` bind-mounts `/var/lib/docker` to raw ext4 on every boot, sidestepping Linux's overlay-on-overlay rejection. `apk add docker; rc-service docker start; docker run` works end to end with the kernel `overlay2` driver (not the slower FUSE fallback).-- **Zero-config LXC**: `podroid-bootstrap` pre-creates `lxcbr0` (10.0.3.1/24) and the matching MASQUERADE rule. `apk add lxc lxc-templates; lxc-create -t busybox; lxc-start` works out of the box.-- **Complete container kernel features**: 36 forced `=y` Kconfig additions (BTRFS, IPVS, VXLAN, IPVLAN, MACVLAN, IPsec/XFRM, FTP/TFTP NAT helpers, AppArmor LSM stub, raw iptables, CFS bandwidth, etc.). Docker `check-config.sh` and `lxc-checkconfig` both report zero fixable complaints.-- **`/proc/config.gz` shipped**: `CONFIG_IKCONFIG=y` + `CONFIG_IKCONFIG_PROC=y` so any tool that wants to introspect the running kernel config can.-- **Terminal regression fix**: inittab now exports `TERM=xterm-256color` instead of `vt100`, restoring 256-color/mouse/italics in the in-app terminal (regressed during the OpenRC migration).--### Recently shipped (1.1.6)-- **OpenRC migration**: Real Alpine root running OpenRC as PID 1; switch_root replaces chroot pivot-- **Adaptive UI**: Phone-landscape and tablet layouts in setup / home / settings / terminal; chip-row selectors with horizontal fade indicators; Quick Settings dialog with left-edge vertical scrollbar-- **Issue #17 fix**: `podman exec -it` works rootful and rootless after switch_root replaces chroot