Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
fix(termux): harden pull_from_termux and package-manager guards per review
Jalebi98350d0ee76d
diff --git a/app/src/main/assets/skills/termux_background.json b/app/src/main/assets/skills/termux_background.jsonindex 5d7896a..cbd0faa 100644--- a/app/src/main/assets/skills/termux_background.json+++ b/app/src/main/assets/skills/termux_background.json@@ -29,5 +29,5 @@"dpkg --configure","prompt"],- "instructions": "1. A foreground process started by run_termux_command is bound to the lifecycle of that one call. The moment Gotcha returns from awaited completion, the process is orphaned and at the mercy of Android's lmkd, Doze, and OEM battery managers.\n2. Persistence pattern (the safe one):\n - `nohup myserver > /sdcard/Download/myserver.log 2>&1 < /dev/null & echo $! > /sdcard/Download/myserver.pid; disown`\n - Then `exit 0` immediately so the call returns success.\n - Next call: read the pid with `cat /sdcard/Download/myserver.pid`, then `kill $(cat /sdcard/Download/myserver.pid)` to stop it.\n - The `< /dev/null` is mandatory — without it, the process inherits the pipe and gets a SIGPIPE the moment the wrapping shell exits.\n3. Wake lock: `termux-wake-lock` (Termux-side; auto-grants WAKE_LOCK on first use). `termux-wake-unlock` to release. Required for any task longer than ~30s that does not write its own progress to disk.\n4. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, runs fail with `Not allowed to start service` because Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n5. Doze / battery saver: long-running `npm install`, `cargo build`, `pip install -r requirements.txt`, or `pkg install` of a large package can be suspended mid-flight. There is no in-Termux workaround beyond asking the user to add Gotcha to the battery-saver whitelist in Android Settings.\n6. Do not promise scheduled tasks. termux-cron / termux-job-scheduler exist but run inside Termux's own alarms, which Android's job scheduler can throttle. They are best-effort, not real cron.\n7. What you CANNOT do in Termux: run a process as a system service (no systemd), have it auto-restart on boot, or have it survive `force-stop` of Termux. The model should not promise any of these.\n8. Health probe pattern: when waiting for a server to come up, prefer `until curl -sSf http://127.0.0.1:PORT/healthz >/dev/null 2>&1; do sleep 1; done` inside a single run_termux_command call, with a tight timeout, rather than polling from Gotcha.\n9. Process hygiene: before starting a new long-running service, check `ps -ef | grep <name>` and offer to kill the existing one via the notification-shade Exit — a run_termux_command cannot kill another call's process; only tapping Exit on the Termux notification (global_action or press_key 'notifications' + tap the Exit action, which ends every Termux session) reliably stops it. If you cannot reach Exit, ask the user to tap it. Do not try `pkill`, `fuser` or `dpkg --configure -a` via another run_termux_command to kill it — that will hang until timeout and not release the lock.\n9b. Wake-lock wrapping for long tasks: for any task >30s (pkg install of large package, npm/pip/cargo build), wrap with `termux-wake-lock && { <cmd>; } ; termux-wake-unlock` inside the same run_termux_command payload. This prevents Doze CPU throttling that turns a 30s task into a 10-minute hang.\n10. Consequence: when the assistive ball is on, Gotcha holds a foreground service that exempts it from the Android 12+ backgrounded-start restriction. Without the ball, the same call fails with the \"Not allowed to start service\" error.\n9c. A `pkg install` that times out keeps running under Termux's uid and holds the dpkg lock (the `lock-frontend` / `Could not get lock` shape). Never `rm` the lock files or `kill -9` the package manager; the only safe stop is the notification-shade Exit above. pkg-like commands are now wake-lock wrapped automatically, but still wrap long non-pkg tasks yourself.\n9d. A `dpkg --configure` on a half-configured package is the same long-task class as a pkg install and is now run non-interactively, but a conffile it cannot answer (Configuration file ... Y/I/N/O/D/Z) is why it stalls holding the dpkg lock. If you must run it, supply the answer through the stdin param (`echo N | dpkg --configure <pkg>`) — the notification-shade Exit is the only stop if it ever hangs."+ "instructions": "1. A foreground process started by run_termux_command is bound to the lifecycle of that one call. The moment Gotcha returns from awaited completion, the process is orphaned and at the mercy of Android's lmkd, Doze, and OEM battery managers.\n2. Persistence pattern (the safe one):\n - `nohup myserver > /sdcard/Download/myserver.log 2>&1 < /dev/null & echo $! > /sdcard/Download/myserver.pid; disown`\n - Then `exit 0` immediately so the call returns success.\n - Next call: read the pid with `cat /sdcard/Download/myserver.pid`, then `kill $(cat /sdcard/Download/myserver.pid)` to stop it.\n - The `< /dev/null` is mandatory — without it, the process inherits the pipe and gets a SIGPIPE the moment the wrapping shell exits.\n3. Wake lock: `termux-wake-lock` (Termux-side; auto-grants WAKE_LOCK on first use). `termux-wake-unlock` to release. Required for any task longer than ~30s that does not write its own progress to disk.\n4. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, runs fail with `Not allowed to start service` because Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n5. Doze / battery saver: long-running `npm install`, `cargo build`, `pip install -r requirements.txt`, or `pkg install` of a large package can be suspended mid-flight. There is no in-Termux workaround beyond asking the user to add Gotcha to the battery-saver whitelist in Android Settings.\n6. Do not promise scheduled tasks. termux-cron / termux-job-scheduler exist but run inside Termux's own alarms, which Android's job scheduler can throttle. They are best-effort, not real cron.\n7. What you CANNOT do in Termux: run a process as a system service (no systemd), have it auto-restart on boot, or have it survive `force-stop` of Termux. The model should not promise any of these.\n8. Health probe pattern: when waiting for a server to come up, prefer `until curl -sSf http://127.0.0.1:PORT/healthz >/dev/null 2>&1; do sleep 1; done` inside a single run_termux_command call, with a tight timeout, rather than polling from Gotcha.\n9. Process hygiene: before starting a new long-running service, check `ps -ef | grep <name>` and offer to kill the existing one via the notification-shade Exit — a run_termux_command cannot kill another call's process; only tapping Exit on the Termux notification (global_action or press_key 'notifications' + tap the Exit action, which ends every Termux session) reliably stops it. If you cannot reach Exit, ask the user to tap it. Do not try `pkill`, `fuser` or `dpkg --configure -a` via another run_termux_command to kill it — that will hang until timeout and not release the lock.\n9b. Wake-lock wrapping for long tasks: for any NON-pkg task >30s (npm/pip/cargo build, ffmpeg), wrap with `termux-wake-lock; { <cmd>; rc=$?; termux-wake-unlock; exit $rc; }` inside the same run_termux_command payload — `rc=$?; exit $rc` preserves the command's real exit code. pkg/apt/dpkg commands are already wake-lock wrapped automatically, so do NOT wrap those yourself.\n11. Consequence: when the assistive ball is on, Gotcha holds a foreground service that exempts it from the Android 12+ backgrounded-start restriction. Without the ball, the same call fails with the \"Not allowed to start service\" error.\n12. A `pkg install` that times out keeps running under Termux's uid and holds the dpkg lock (the `lock-frontend` / `Could not get lock` shape). Never `rm` the lock files or `kill -9` the package manager; the only safe stop is the notification-shade Exit above. pkg-like commands are now wake-lock wrapped automatically, but still wrap long non-pkg tasks yourself. The auto-wrap is best-effort for ONE long command: if two pkg installs run at once, the first to finish releases the shared wake-lock while the second is still going — avoid running two at the same time.\n13. A `dpkg --configure` on a half-configured package is the same long-task class as a pkg install and is now run non-interactively, but a conffile it cannot answer (Configuration file ... Y/I/N/O/D/Z) is why it stalls holding the dpkg lock. If you must run it, supply the answer through the stdin param (`echo N | dpkg --configure <pkg>`) — the notification-shade Exit is the only stop if it ever hangs."}diff --git a/app/src/main/assets/skills/termux_filesystem.json b/app/src/main/assets/skills/termux_filesystem.jsonindex 634c246..27a0f11 100644--- a/app/src/main/assets/skills/termux_filesystem.json+++ b/app/src/main/assets/skills/termux_filesystem.json@@ -28,5 +28,5 @@"storage not linked","grant"],- "instructions": "Three filesystem worlds — keep them separate:\n1. Gotcha's working dir (default cwd for `run_command`, `read_file`, `write_file`, `edit`, `glob`, `grep`): `/storage/emulated/0/Gotcha/chats/<slug_id>/`. INVISIBLE to Termux (different UID).\n2. Termux's home (default `working_dir` for `run_termux_command`): `/data/data/com.termux/files/home`. INVISIBLE to Gotcha.\n3. Shared storage: `/storage/emulated/0/Download`, `/storage/emulated/0/Pictures`, `/storage/emulated/0/Music`. Readable by both UIDs, but ONLY AFTER the user has run `termux-setup-storage` in Termux once. Before that, Termux sees `/sdcard/` as empty.\n\nThe only safe bridge between the two worlds is `/sdcard/Download/`:\n1. Gotcha: write_file('/storage/emulated/0/Download/foo.txt', ...). Termux reads: cat /sdcard/Download/foo.txt.\n2. Termux writes /sdcard/Download/result.txt. Gotcha reads: read_file('/storage/emulated/0/Download/result.txt').\n\nInside Termux, use `/sdcard` (which symlinks to `/storage/emulated/0`). Do NOT use `/storage/emulated/0` directly inside Termux for write paths — go through `/sdcard`.\n\n`$PREFIX` is `/data/data/com.termux/files/usr`. The model should not guess `/usr/bin` for Termux — that path is empty.\n\nIf a Gotcha `read_file` on a path that exists in `/sdcard/Download/` fails inside Termux's view, the user has likely not run `termux-setup-storage`. Ask the user to open Termux once and run `termux-setup-storage`, then retry.\n\nTermux's `/data/data/com.termux/files/home` is a real directory, but writing to it from Gotcha via `run_command` would fail with Permission denied — that is a different UID. Stick to the /sdcard bridge.\n\nFor small-to-medium scripts and payloads <100KB, prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the run_termux_command stdin param) over the /sdcard bridge — it avoids FUSE overhead and does not require termux-setup-storage. For temporary files inside Termux, prefer $TMPDIR — private to Termux and survives a single call; use /data/data/com.termux/files/home/.tmp/ as fallback.\n\ncross-uid file sizes above 100MB are slow across the /sdcard bridge (FUSE + sdcardfs). When transferring large files, prefer streaming via `dd` or `tar` straight through a pipe.\n`$PREFIX` is not always `/data/data/com.termux/files/usr`: Gotcha resolves the real path from the installed package, and under a secondary user or work profile it is `/data/user/<id>/com.termux/files/usr`. Prefer `$PREFIX` over a hardcoded `/data/data/...` prefix in commands.\nMoving a file OUT of Termux (yt-dlp output, script results, server files): first probe whether the shared-storage bridge exists with `ls -ld ~/storage/downloads` — if it lists, `cp 'src' /sdcard/Download/name` is the normal, debuggable path. If it reports `No such file` or `Operation not permitted`, `termux-setup-storage` was run but the Android grant was never confirmed — do NOT loop on `cp`. Use the pull_from_termux tool instead, which falls back to a loopback transfer over 127.0.0.1 (Termux python3 sender -> Gotcha receiver) that crosses the uid boundary without needing the storage grant at all, and works even before `termux-setup-storage`."+ "instructions": "Three filesystem worlds — keep them separate:\n1. Gotcha's working dir (default cwd for `run_command`, `read_file`, `write_file`, `edit`, `glob`, `grep`): `/storage/emulated/0/Gotcha/chats/<slug_id>/`. INVISIBLE to Termux (different UID).\n2. Termux's home (default `working_dir` for `run_termux_command`): `/data/data/com.termux/files/home`. INVISIBLE to Gotcha.\n3. Shared storage: `/storage/emulated/0/Download`, `/storage/emulated/0/Pictures`, `/storage/emulated/0/Music`. Readable by both UIDs, but ONLY AFTER the user has run `termux-setup-storage` in Termux once. Before that, Termux sees `/sdcard/` as empty.\n\nThe only safe bridge between the two worlds is `/sdcard/Download/`:\n1. Gotcha: write_file('/storage/emulated/0/Download/foo.txt', ...). Termux reads: cat /sdcard/Download/foo.txt.\n2. Termux writes /sdcard/Download/result.txt. Gotcha reads: read_file('/storage/emulated/0/Download/result.txt').\n\nInside Termux, use `/sdcard` (which symlinks to `/storage/emulated/0`). Do NOT use `/storage/emulated/0` directly inside Termux for write paths — go through `/sdcard`.\n\n`$PREFIX` is `/data/data/com.termux/files/usr`. The model should not guess `/usr/bin` for Termux — that path is empty.\n\nIf a Gotcha `read_file` on a path that exists in `/sdcard/Download/` fails inside Termux's view, the user has likely not run `termux-setup-storage`. Ask the user to open Termux once and run `termux-setup-storage`, then retry.\n\nTermux's `/data/data/com.termux/files/home` is a real directory, but writing to it from Gotcha via `run_command` would fail with Permission denied — that is a different UID. Stick to the /sdcard bridge.\n\nFor small-to-medium scripts and payloads <100KB, prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the run_termux_command stdin param) over the /sdcard bridge — it avoids FUSE overhead and does not require termux-setup-storage. For temporary files inside Termux, prefer $TMPDIR — private to Termux and survives a single call; use /data/data/com.termux/files/home/.tmp/ as fallback.\n\ncross-uid file sizes above 100MB are slow across the /sdcard bridge (FUSE + sdcardfs). pull_from_termux routes files above 100MB through its loopback stream for this reason; for a manual transfer of a large file, prefer streaming via `dd` or `tar` straight through a pipe.\n`$PREFIX` is not always `/data/data/com.termux/files/usr`: Gotcha resolves the real path from the installed package, and under a secondary user or work profile it is `/data/user/<id>/com.termux/files/usr`. Prefer `$PREFIX` over a hardcoded `/data/data/...` prefix in commands.\nMoving a file OUT of Termux (yt-dlp output, script results, server files): first probe whether the shared-storage bridge exists with `ls -ld ~/storage/downloads` — if it lists, `cp 'src' /sdcard/Download/name` is the normal, debuggable path. If it reports `No such file` or `Operation not permitted`, `termux-setup-storage` was run but the Android grant was never confirmed — do NOT loop on `cp`. Use the pull_from_termux tool instead, which falls back to a loopback transfer over 127.0.0.1 (Termux python3 sender -> Gotcha receiver) that crosses the uid boundary without needing the storage grant at all, and works even before `termux-setup-storage`."}diff --git a/app/src/main/java/com/gotcha/tools/TermuxFileBridge.kt b/app/src/main/java/com/gotcha/tools/TermuxFileBridge.ktindex 93e5263..b65d164 100644--- a/app/src/main/java/com/gotcha/tools/TermuxFileBridge.kt+++ b/app/src/main/java/com/gotcha/tools/TermuxFileBridge.kt@@ -7,8 +7,10 @@ import kotlinx.coroutines.asyncimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeout+import java.io.ByteArrayOutputStreamimport java.io.Fileimport java.io.FileOutputStream+import java.io.IOExceptionimport java.io.InputStreamimport java.net.InetAddressimport java.net.ServerSocket@@ -34,9 +36,10 @@ import java.util.UUID** The `python3` sender is wrapped in a wake-lock so Doze cannot stall a slow transfer; the values* it needs (port, nonce, source path) are passed as argv so no quoting or interpolation can break- * a path with newlines or quotes; a single-use nonce scopes the socket to one sender; the body is- * streamed to a temp file and atomically renamed on success so a failed transfer never leaves a- * corrupt file behind.+ * a path with newlines or quotes; a single-use nonce scopes the socket to one sender; the sender+ * announces the file size up front and the receiver verifies the byte count on arrival; the body+ * is streamed to a temp file that is renamed over the destination only after the sender has+ * exited 0 AND the full size has arrived, so a failed transfer never leaves a corrupt file behind.*/class TermuxFileBridge(private val context: Context,@@ -49,6 +52,9 @@ class TermuxFileBridge(/** Below this size the `/sdcard` bridge is fine; above it FUSE starts to matter. */const val SHARED_STORAGE_MAX_BYTES = 100L * 1024 * 1024+ /** How long the storage-link probe result is trusted before re-probing. */+ private const val STORAGE_PROBE_CACHE_MS = 30_000L+/** The probe that decides whether `termux-setup-storage` actually linked the bridge. */const val PROBE_STORAGE_COMMAND ="ls -ld ~/storage/downloads >/dev/null 2>&1 && echo STORAGE_LINKED || echo STORAGE_UNLINKED"@@ -69,18 +75,33 @@ class TermuxFileBridge(private const val DENIED_ACK = "DENIED\n"}- /** Whether Termux's `/sdcard` bridge (`~/storage`) is actually usable, not merely requested. */+ /**+ * Whether Termux's `/sdcard` bridge (`~/storage`) is actually usable, not merely requested.+ *+ * The probe is cached briefly: the linked state only changes when the user runs+ * `termux-setup-storage` and grants the dialog, so a pull that fails and is retried should not+ * re-probe on every attempt.+ */suspend fun isStorageLinked(): Boolean {+ val now = System.currentTimeMillis()+ if (now - storageProbedAt < STORAGE_PROBE_CACHE_MS) return storageLinked ?: falseval result = termux.runCommand(PROBE_STORAGE_COMMAND, timeoutSeconds = 15)- return result.success && linksStorage(result.message)+ val linked = result.success && linksStorage(result.message)+ storageLinked = linked+ storageProbedAt = now+ return linked}+ private var storageLinked: Boolean? = null+ private var storageProbedAt: Long = Long.MIN_VALUE+/*** Pulls [termuxPath] out of Termux into [destination].*- * Tries the `/sdcard` bridge when it is genuinely linked; falls back to a loopback transfer- * when it is not (or when a `cp` through FUSE fails), so the outcome never depends on whether- * the user granted the storage dialog.+ * Tries the `/sdcard` bridge when it is genuinely linked and the file is small enough that+ * FUSE is not the bottleneck; falls back to a loopback transfer when it is not linked, when the+ * file is above [SHARED_STORAGE_MAX_BYTES], or when a `cp` through FUSE fails, so the outcome+ * never depends on whether the user granted the storage dialog.*/suspend fun pull(termuxPath: String, destination: File): ToolResult {val source = expandHome(termuxPath)@@ -90,12 +111,42 @@ class TermuxFileBridge(return ToolResult.error("Could not create the destination directory '${parent.canonicalPath}'.")}}- if (usesSharedStorage(isStorageLinked(), destination.canonicalPath)) {- val viaShared = copyViaSharedStorage(source, destination)- if (viaShared.success) return viaShared- // Fall through: FUSE refused us; loopback can still reach the destination directly.+ val destinationCanonical = destination.canonicalPath+ var sharedError: String? = null+ // Short-circuit before probing Termux at all: a destination inside Gotcha's sandbox is+ // unreachable from Termux, so only the loopback path can serve it.+ if (FfmpegCommand.isReachableFromTermux(destinationCanonical)) {+ val storageLinked = isStorageLinked()+ // Only stat the source when the bridge is actually usable — the size gate is about+ // choosing a transport, not about files we are not going to move this way.+ val sourceBytes = if (storageLinked) sourceSizeBytes(source) else null+ if (usesSharedStorage(storageLinked, destinationCanonical, sourceBytes)) {+ val viaShared = copyViaSharedStorage(source, destination)+ if (viaShared.success) return viaShared+ sharedError = viaShared.message+ // Fall through: FUSE refused us; loopback can still reach the destination directly.+ }+ }+ val loopback = copyViaLoopback(source, destination)+ if (loopback.success) return loopback+ // The loopback failure is the actionable one, but the shared-storage refusal explains WHY we+ // fell back — dropping it would mislead a FUSE/permission debug.+ return if (sharedError == null) {+ loopback+ } else {+ ToolResult.error(+ "${loopback.message}\n(The shared-storage attempt also failed: ${sharedError.take(200)})"+ )}- return copyViaLoopback(source, destination)+ }++ /** The size of [source] as Termux sees it, or null when it cannot be determined. */+ private suspend fun sourceSizeBytes(source: String): Long? {+ val result = termux.runCommand(+ "stat -c %s -- ${FfmpegCommand.shellQuote(source)}",+ timeoutSeconds = 15+ )+ return result.message.lineSequence().lastOrNull()?.trim()?.toLongOrNull()}// ---- shared-storage path ----@@ -126,7 +177,10 @@ class TermuxFileBridge(/*** Streams [source] from Termux to [destination] over `127.0.0.1`. The Termux side is a small* `python3` client that presents a single-use nonce and then sends the file; the Gotcha side is- * a Kotlin [ServerSocket] bound to loopback. Both run concurrently.+ * a Kotlin [ServerSocket] bound to loopback. Both run concurrently, and the temp file is moved+ * over [destination] only after **both** the sender has exited 0 and the receiver has verified+ * the byte count — a sender killed mid-transfer (lmkd, force-stop, battery manager) fails one+ * of those first, so a partial body is never finalised.*/private suspend fun copyViaLoopback(source: String, destination: File): ToolResult {val nonce = UUID.randomUUID().toString().replace("-", "")@@ -164,7 +218,7 @@ class TermuxFileBridge()}- try {+ val tmp = try {receive.await()} catch (e: CancellationException) {throw e@@ -175,6 +229,13 @@ class TermuxFileBridge()}+ // Both halves succeeded; only now is the temp file finalised over the destination.+ if (!finalizeTransfer(tmp, destination)) {+ tmp.delete()+ return@coroutineScope ToolResult.error(+ "The transfer completed but could not be saved to '${destination.canonicalPath}'."+ )+ }ToolResult.ok("Pulled '$source' out of Termux to '${destination.canonicalPath}' " +"(${resolver.formatSize(destination.length())})."@@ -186,66 +247,82 @@ class TermuxFileBridge(}/**- * Listens for the sender, validates the single-use nonce, and streams the body into a temp file- * that is atomically renamed over [destination] only on success. A connection that presents the- * wrong nonce (or closes before the handshake) is refused and we keep listening for the real- * sender until [ACCEPT_TIMEOUT_MS] elapses.+ * Listens for the sender, validates the single-use nonce, and streams the body into a temp file.+ * Returns the temp file on a verified transfer; it never touches [destination] — the caller+ * finalises that only after the sender has also reported success, so a partial body cannot land+ * in place. A connection that presents the wrong nonce (or closes before the handshake) is+ * refused and we keep listening for the real sender until [ACCEPT_TIMEOUT_MS] elapses.*/- private fun receiveInto(server: ServerSocket, nonce: String, destination: File) {+ internal fun receiveInto(server: ServerSocket, nonce: String, destination: File): File {destination.parentFile?.mkdirs()val tmp = File(destination.parentFile,".${destination.name}.${UUID.randomUUID().toString().take(8)}.tmp")val deadline = System.currentTimeMillis() + ACCEPT_TIMEOUT_MS- var transferred = falsetry {- while (!transferred) {+ while (true) {if (System.currentTimeMillis() > deadline) error("no sender connected before the timeout")- transferred = handleCandidate(server.accept(), nonce, tmp)+ handleCandidate(server.accept(), nonce, tmp)?.let { return it }}- if (!tmp.renameTo(destination)) {- if (destination.exists() && !destination.delete()) {- error("could not replace the existing destination '${destination.canonicalPath}'")- }- if (!tmp.renameTo(destination)) {- error("could not finalize the transfer at '${destination.canonicalPath}'")- }- }- } finally {- // On success the temp was renamed away; on failure it must not linger.+ } catch (e: Throwable) {+ // A failed transfer must not linger as a stray temp file.tmp.delete()+ throw e}}/**- * Validates one connecting socket's nonce and, if it matches, streams its body into [tmp].- * A wrong nonce or an early close is refused and the caller keeps listening.+ * Validates one connecting socket's nonce and streams its body into [tmp], verifying the+ * sender's announced byte count. Returns [tmp] on a complete, size-checked transfer; null on a+ * wrong nonce or an early close, so the caller keeps listening for the real sender.*/- private fun handleCandidate(socket: Socket, nonce: String, tmp: File): Boolean {- var transferred = false- socket.use {- it.soTimeout = BRIDGE_TIMEOUT_SECONDS * 1000- val header = ByteArray(nonce.length)- val gotHeader = readFully(it.getInputStream(), header)- if (!gotHeader || header.decodeToString() != nonce) {- it.getOutputStream().write(DENIED_ACK.toByteArray())- it.getOutputStream().flush()- return@use+ internal fun handleCandidate(socket: Socket, nonce: String, tmp: File): File? = socket.use { s ->+ s.soTimeout = BRIDGE_TIMEOUT_SECONDS * 1000+ val header = ByteArray(nonce.length)+ val gotHeader = readFully(s.getInputStream(), header)+ if (!gotHeader || header.decodeToString() != nonce) {+ s.getOutputStream().write(DENIED_ACK.toByteArray())+ s.getOutputStream().flush()+ return@use null+ }+ s.getOutputStream().write(READY_ACK.toByteArray())+ s.getOutputStream().flush()+ val expected = readSizeLine(s.getInputStream())+ ?: throw IOException("sender closed before announcing a valid file size")+ FileOutputStream(tmp).use { out ->+ val buffer = ByteArray(CHUNK_BYTES)+ var received = 0L+ while (true) {+ val read = s.getInputStream().read(buffer)+ if (read < 0) break+ out.write(buffer, 0, read)+ received += read}- it.getOutputStream().write(READY_ACK.toByteArray())- it.getOutputStream().flush()- FileOutputStream(tmp).use { out ->- val buffer = ByteArray(CHUNK_BYTES)- while (true) {- val read = it.getInputStream().read(buffer)- if (read < 0) break- out.write(buffer, 0, read)- }+ if (received != expected) {+ throw IOException("transfer truncated: received $received of $expected bytes")}- transferred = true}- return transferred+ tmp+ }++ /** Reads a single `\n`-terminated line as a byte count; null on EOF or non-numeric text. */+ private fun readSizeLine(input: InputStream): Long? {+ val line = ByteArrayOutputStream()+ while (true) {+ val b = input.read()+ if (b < 0) return if (line.size() == 0) null else line.toString("UTF-8").trim().toLongOrNull()+ if (b == '\n'.code) break+ line.write(b)+ }+ return line.toString("UTF-8").trim().toLongOrNull()+ }++ /** Atomically moves [tmp] over [destination], replacing an existing file if needed. */+ private fun finalizeTransfer(tmp: File, destination: File): Boolean {+ if (tmp.renameTo(destination)) return true+ if (destination.exists() && !destination.delete()) return false+ return tmp.renameTo(destination)}/** Reads exactly [into].size bytes; returns false if the connection closed early. */@@ -272,9 +349,19 @@ class TermuxFileBridge(}}- /** The shared-storage path is only the primary route when the link exists AND Termux can see the destination. */- internal fun usesSharedStorage(storageLinked: Boolean, destinationCanonical: String): Boolean =- storageLinked && FfmpegCommand.isReachableFromTermux(destinationCanonical)+ /**+ * The shared-storage path is only the primary route when the link exists AND Termux can see the+ * destination AND the file is small enough that FUSE is not the bottleneck — above+ * [SHARED_STORAGE_MAX_BYTES] the loopback stream is used even on a linked bridge.+ */+ internal fun usesSharedStorage(+ storageLinked: Boolean,+ destinationCanonical: String,+ sourceBytes: Long? = null+ ): Boolean =+ storageLinked &&+ FfmpegCommand.isReachableFromTermux(destinationCanonical) &&+ (sourceBytes == null || sourceBytes < SHARED_STORAGE_MAX_BYTES)/** A probe message names the bridge as linked only when the explicit marker is present. */internal fun linksStorage(message: String): Boolean = message.contains(STORAGE_LINKED_MARKER)@@ -291,9 +378,10 @@ class TermuxFileBridge(internal fun senderCommand(port: Int, nonce: String, source: String): String =TermuxTool.withWakeLock("python3 - $port $nonce ${FfmpegCommand.shellQuote(source)}")- /** The `python3` client program, reading port/nonce/path from argv. */+ /** The `python3` client program, reading port/nonce/path from argv. It announces the file size+ * before streaming so the receiver can reject a truncated body rather than accept it. */internal fun senderScript(): String =- "import socket, sys\n" ++ "import socket, sys, os\n" +"port = int(sys.argv[1])\n" +"nonce = sys.argv[2]\n" +"path = sys.argv[3]\n" +@@ -304,6 +392,8 @@ class TermuxFileBridge("if ack != b'READY\\n':\n" +" s.close()\n" +" sys.exit(1)\n" ++ "size = os.path.getsize(path)\n" ++ "s.sendall(str(size).encode() + b'\\n')\n" +"with open(path, 'rb') as f:\n" +" while True:\n" +" chunk = f.read($CHUNK_BYTES)\n" +diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.ktindex 207239f..f06f0b8 100644--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt@@ -240,7 +240,7 @@ class TermuxTool(val bundle = withTimeoutOrNull(timeout * 1000L) { deferred.await() }?: return TermuxMessages.timedOut(trimmed, timeout, hadStdin = stdin != null)- return formatResult(bundle)+ return formatResult(bundle, trimmed)} finally {pendingResults.remove(requestCode)inFlight.release()@@ -248,7 +248,7 @@ class TermuxTool(}/** Turn Termux's result bundle into a [ToolResult]. Split out so it is testable without Termux. */- internal fun formatResult(bundle: Bundle): ToolResult {+ internal fun formatResult(bundle: Bundle, command: String = ""): ToolResult {val err = bundle.numeric(RESULT_ERR) ?: ERRNO_SUCCESSval errmsg = bundle.getString(RESULT_ERRMSG)?.trim().orEmpty()if (err != ERRNO_SUCCESS) {@@ -279,10 +279,13 @@ class TermuxTool(//// Deliberately NOT gated on `exit != 0`: a pipeline like `apt-get ... | tail` or// `apt list --upgradable` masks apt's failure behind a successful tail/echo, so the lock- // error appears in the output while the reported exit code is 0. The signature below is the- // failing-phrase set only ("Could not get lock" / "Unable to acquire ..."), so listing the- // lock files with `ls $PREFIX/var/lib/dpkg/lock*` cannot false-positive on the filename.- if (LOCK_SIGNATURE.containsMatchIn(message)) {+ // error appears in the output while the reported exit code is 0. It IS gated on the command+ // being package-manager-shaped ([PKG_LIKE_REGEX]): a successful diagnostic that merely+ // *contains* the phrase (`grep "Could not get lock" build.log`) is a successful command, not+ // a held lock. An empty [command] — the pure test seam — keeps the defensive scan.+ if ((command.isEmpty() || PKG_LIKE_REGEX.containsMatchIn(command)) &&+ LOCK_SIGNATURE.containsMatchIn(message)+ ) {return TermuxMessages.lockHeld(HOLDER_PID.find(message)?.groupValues?.get(1))}return ToolResult(success = exit == 0, message = message)@@ -466,7 +469,13 @@ class TermuxTool(private const val WAKE_UNLOCK = "termux-wake-unlock"/**- * The Debian frontend env var that tells dpkg/apt to take default actions instead of asking+ * An actual `DEBIAN_FRONTEND=<value>` assignment. A bare substring would match a package+ * name or a path containing the literal (e.g. `apt-get install lib-DEBIAN_FRONTEND-1`),+ * silently skipping the non-interactive injection and letting a conffile prompt hang.+ */+ private val DEBIAN_FRONTEND_ASSIGNMENT = Regex("""(^|\s)DEBIAN_FRONTEND=\S+""")++ /** The Debian frontend env var that tells dpkg/apt to take default actions instead of asking* conffile questions. It is safe for every package-manager command and skipped when the user* already set it explicitly.*/@@ -510,16 +519,27 @@ class TermuxTool(* default action (keep the current version), which is what the user's own edit implies.*/internal fun withNonInteractive(command: String): String =- if (DEBIAN_FRONTEND in command) command else "$DEBIAN_FRONTEND=noninteractive $command"+ if (DEBIAN_FRONTEND_ASSIGNMENT.containsMatchIn(command)) {+ command+ } else {+ "$DEBIAN_FRONTEND=noninteractive $command"+ }/*** Wraps [command] in `termux-wake-lock`/`termux-wake-unlock`, preserving its exit code (a naive* `cmd; termux-wake-unlock` would swallow failures) and skipping the wrap entirely when the* lock tools are not installed. Split out so the shape can be asserted without Termux.+ *+ * Best-effort for a single long command: Termux's wake-lock is one global marker, so two+ * concurrent pkg calls each lock and the first to finish unlocks while the other still runs.+ * The skill notes this; it is not a reason to leave slow installs unwrapped.*/internal fun withWakeLock(command: String): String {if (WAKE_LOCK in command) return command- val wrapped = "$WAKE_LOCK; { $command; rc=\$?; $WAKE_UNLOCK; exit \$rc; }"+ // The EXIT trap (rather than a trailing `termux-wake-unlock`) also releases the lock when+ // the inner command itself exits early — e.g. the skill's persistence pattern ends with a+ // bare `exit 0`, which would skip a trailing sequence and leak the wake-lock.+ val wrapped = "$WAKE_LOCK; trap '$WAKE_UNLOCK' EXIT; { $command; rc=\$?; exit \$rc; }"return "if command -v $WAKE_LOCK >/dev/null 2>&1; then $wrapped; else $command; fi"}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 88854bf..5ac97ac 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -73,6 +73,7 @@ class ToolExecutor(private val mediaEditTool = MediaEditTool(appContext)private val mediaConvertTool = MediaConvertTool(appContext)private val termuxFileBridge = TermuxFileBridge(appContext)+ private val fileResolver = FileResolver(appContext)private val podcastTool = PodcastTool(appContext,onUnauthorized = { runCatching { com.gotcha.data.SettingsRepository(appContext).clearSamosaSession() } }@@ -270,8 +271,10 @@ class ToolExecutor()"pull_from_termux" -> termuxFileBridge.pull(termuxPath = args.requireString("termux_path") ?: return missing("termux_path"),+ // Resolve relative paths against the session working dir like every other file+ // tool; a raw string would resolve against the JVM process CWD instead.destination = java.io.File(- args.requireString("destination") ?: return missing("destination")+ fileResolver.canonicalPath(args.requireString("destination") ?: return missing("destination"))))"synthesize_podcast_dialogue" -> podcastTool.synthesizeDialogue(diff --git a/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.kt b/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.ktindex f912a9a..ba4356c 100644--- a/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.kt+++ b/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.kt@@ -2,6 +2,10 @@ package com.gotcha.toolsimport android.content.Contextimport androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertArrayEqualsimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrue@@ -9,12 +13,20 @@ import org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.annotation.Config+import java.io.File+import java.io.IOException+import java.net.InetAddress+import java.net.ServerSocket+import java.net.Socket+import java.nio.file.Files/*** `pull_from_termux`'s `TermuxFileBridge`. The live transfer (a real `cp` through `/sdcard`, or a* loopback `python3` send) needs a real Termux install and is verified by hand — what is covered* here is everything that decides the outcome without Termux: `~`/`$HOME` expansion, the exact- * `python3` sender command and program, and the shared-storage-vs-loopback selection.+ * `python3` sender command and program, the shared-storage-vs-loopback selection, and the socket+ * machinery of the loopback receiver driven over a real `127.0.0.1` `ServerSocket`/`Socket` pair+ * (nonce handshake, wrong-nonce refusal, size verification, and the no-partial-file guarantee).*/@RunWith(RobolectricTestRunner::class)@Config(sdk = [30, 34])@@ -90,10 +102,163 @@ class TermuxFileBridgeTest {assertFalse(bridge.usesSharedStorage(false, private))}+ @Test+ fun `files at or above the shared-storage size threshold route to loopback`() {+ val reachable = "/storage/emulated/0/Download/out.mp4"+ assertTrue(+ "a small file uses the linked bridge",+ bridge.usesSharedStorage(true, reachable, sourceBytes = 64L * 1024 * 1024)+ )+ assertFalse(+ "a file at the 100MB FUSE threshold routes to loopback",+ bridge.usesSharedStorage(true, reachable, sourceBytes = TermuxFileBridge.SHARED_STORAGE_MAX_BYTES)+ )+ assertFalse(+ "a file above the 100MB FUSE threshold routes to loopback",+ bridge.usesSharedStorage(true, reachable, sourceBytes = 1024L * 1024 * 1024)+ )+ assertFalse(+ "an unknown size still refuses an unlinked bridge",+ bridge.usesSharedStorage(false, reachable, sourceBytes = null)+ )+ }+@Testfun `the storage probe only reports linked on an explicit marker`() {assertTrue(bridge.linksStorage("exit code: 0\nstdout:\nSTORAGE_LINKED"))assertFalse(bridge.linksStorage("exit code: 0\nstdout:\nSTORAGE_UNLINKED"))assertFalse("a probe that never ran must not read as linked", bridge.linksStorage("Termux is not installed"))}++ // ---- the loopback receiver, driven over a real 127.0.0.1 socket pair ----++ @Test+ fun `a matching sender streams into the temp and the destination stays untouched`() = runBlocking {+ val nonce = "deadbeef"+ val destination = File(tempDir(), "out.bin")+ val server = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))+ val receiver = async(Dispatchers.IO) { bridge.receiveInto(server, nonce, destination) }+ val payload = "streamed body with spaces".toByteArray()++ Socket("127.0.0.1", server.localPort).use { socket ->+ socket.getOutputStream().write(nonce.toByteArray())+ socket.getOutputStream().flush()+ assertEquals("READY\n", readExactly(socket.getInputStream(), 6).decodeToString())+ socket.getOutputStream().write("${payload.size}\n".toByteArray())+ socket.getOutputStream().write(payload)+ socket.getOutputStream().flush()+ socket.shutdownOutput()+ }++ val tmp = receiver.await()+ try {+ assertTrue("receiveInto must return a file, not finalise the destination", tmp.exists())+ assertArrayEquals(payload, tmp.readBytes())+ assertFalse("the destination must not exist until copyViaLoopback renames", destination.exists())+ } finally {+ tmp.delete()+ server.close()+ }+ }++ @Test+ fun `a wrong nonce is refused and the receiver keeps listening for the real sender`() = runBlocking {+ val nonce = "deadbeef"+ val destination = File(tempDir(), "out.bin")+ val server = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))+ val receiver = async(Dispatchers.IO) { bridge.receiveInto(server, nonce, destination) }+ val port = server.localPort++ Socket("127.0.0.1", port).use { socket ->+ socket.getOutputStream().write("wrongone".toByteArray())+ socket.getOutputStream().flush()+ assertEquals("DENIED\n", readExactly(socket.getInputStream(), 7).decodeToString())+ }++ val payload = "real".toByteArray()+ Socket("127.0.0.1", port).use { socket ->+ socket.getOutputStream().write(nonce.toByteArray())+ socket.getOutputStream().flush()+ assertEquals("READY\n", readExactly(socket.getInputStream(), 6).decodeToString())+ socket.getOutputStream().write("${payload.size}\n".toByteArray())+ socket.getOutputStream().write(payload)+ socket.getOutputStream().flush()+ socket.shutdownOutput()+ }++ val tmp = receiver.await()+ try {+ assertArrayEquals(payload, tmp.readBytes())+ } finally {+ tmp.delete()+ server.close()+ }+ }++ @Test+ fun `a sender that closes early after declaring a larger size fails and leaves nothing behind`() = runBlocking {+ // The regression behind the no-partial-file guarantee: a sender killed mid-transfer (lmkd,+ // force-stop, battery manager) closes the socket early; the receiver must reject the body+ // rather than treat EOF as success, and leave neither a destination nor a stray temp.+ val nonce = "deadbeef"+ val dir = tempDir()+ val destination = File(dir, "out.bin")+ val server = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))+ val receiver = async(Dispatchers.IO) { runCatching { bridge.receiveInto(server, nonce, destination) } }++ Socket("127.0.0.1", server.localPort).use { socket ->+ socket.getOutputStream().write(nonce.toByteArray())+ socket.getOutputStream().flush()+ assertEquals("READY\n", readExactly(socket.getInputStream(), 6).decodeToString())+ socket.getOutputStream().write("100000\n".toByteArray())+ socket.getOutputStream().write("partial".toByteArray())+ socket.getOutputStream().flush()+ socket.shutdownOutput()+ }++ val outcome = receiver.await()+ assertTrue("a truncated transfer must fail, not silently succeed: $outcome", outcome.isFailure)+ assertFalse("no corrupt file may land at the destination", destination.exists())+ assertFalse("no stray temp file may linger", dir.listFiles()!!.any { it.name.endsWith(".tmp") })+ server.close()+ }++ @Test+ fun `an empty file with a matching size header transfers cleanly`() = runBlocking {+ val nonce = "deadbeef"+ val destination = File(tempDir(), "empty.bin")+ val server = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))+ val receiver = async(Dispatchers.IO) { bridge.receiveInto(server, nonce, destination) }++ Socket("127.0.0.1", server.localPort).use { socket ->+ socket.getOutputStream().write(nonce.toByteArray())+ socket.getOutputStream().flush()+ assertEquals("READY\n", readExactly(socket.getInputStream(), 6).decodeToString())+ socket.getOutputStream().write("0\n".toByteArray())+ socket.getOutputStream().flush()+ socket.shutdownOutput()+ }++ val tmp = receiver.await()+ try {+ assertEquals(0, tmp.length())+ assertFalse(destination.exists())+ } finally {+ tmp.delete()+ server.close()+ }+ }++ private fun tempDir(): File = Files.createTempDirectory("termux-bridge-test").toFile()++ private fun readExactly(input: java.io.InputStream, n: Int): ByteArray {+ val out = ByteArray(n)+ var offset = 0+ while (offset < n) {+ val read = input.read(out, offset, n - offset)+ if (read < 0) throw IOException("connection closed after $offset of $n bytes")+ offset += read+ }+ return out+ }}diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.ktindex 62d4585..167fe8f 100644--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt@@ -390,6 +390,38 @@ class TermuxToolTest {assertTrue(result.message.contains("process 15138"))}+ @Test+ fun `a pkg-like command masking a lock behind a pipe is still lock contention`() {+ // Same masking shape, but with the actual command named: `apt` is package-manager-shaped,+ // so the scan must stay enabled.+ val bundle = resultBundle(+ exitCode = 0,+ stdout = "Hit:1 https://packages.termux.dev/termux-main stable InRelease\n" ++ "E: Could not get lock ... It is held by process 15138 (apt)."+ )++ val result = tool.formatResult(bundle, command = "apt list --upgradable | tail -n 5")++ assertFalse(result.success)+ assertTrue(result.message.contains("process 15138"))+ }++ @Test+ fun `a successful non-pkg command that merely mentions lock text is not lock contention`() {+ // The detector is scoped to package-manager-shaped commands: a `grep` of a build log that+ // happens to contain the phrase is a successful command, not a held lock.+ val bundle = resultBundle(+ exitCode = 0,+ stdout = "grep hit: E: Could not get lock " ++ "/data/data/com.termux/files/usr/var/lib/dpkg/lock-frontend. It is held by process 24247 (dpkg)."+ )++ val result = tool.formatResult(bundle, command = "grep -r 'Could not get lock' \$TMPDIR/build.log")++ assertTrue("a grep of a log is not lock contention: ${result.message}", result.success)+ assertFalse(result.message.contains("Do NOT delete the lock files"))+ }+@Testfun `listing the lock files does not read as lock contention`() {// `ls -l $PREFIX/var/lib/dpkg/lock*` prints filenames that contain "lock-frontend"; the@@ -433,6 +465,17 @@ class TermuxToolTest {assertTrue("an already-wrapped command is not double-wrapped", wrapped == TermuxTool.withWakeLock(wrapped))}+ @Test+ fun `the wake-lock wrap uses an EXIT trap so a bare exit cannot leak the lock`() {+ // The skill's persistence pattern ends with a bare `exit 0`; a trailing+ // `termux-wake-unlock` sequence would never run and the wake-lock would leak.+ val wrapped = TermuxTool.withWakeLock("pkg install ffmpeg -y && exit 0")++ assertTrue("must trap EXIT for the unlock: $wrapped", wrapped.contains("trap 'termux-wake-unlock' EXIT"))+ assertTrue(wrapped.contains("termux-wake-unlock"))+ assertTrue(wrapped.contains("rc=\$?"))+ }+@Testfun `pkg-like commands are made non-interactive and wake-locked`() {val run = TermuxTool.commandToRun("pkg install ffmpeg -y")@@ -454,6 +497,16 @@ class TermuxToolTest {)}+ @Test+ fun `a bare DEBIAN_FRONTEND substring in a package name does not suppress injection`() {+ // The old `DEBIAN_FRONTEND in command` substring check skipped the injection for a package+ // whose name merely contains the literal, silently leaving the conffile prompt in place.+ assertTrue(+ TermuxTool.withNonInteractive("apt-get install -y lib-DEBIAN_FRONTEND-1")+ .startsWith("DEBIAN_FRONTEND=noninteractive")+ )+ }+@Testfun `a non-pkg command is not wake-lock wrapped`() {// withWakeLock/withNonInteractive themselves wrap anything; the package-manager gate lives in commandToRun.diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex a5fce0d..4cb3f27 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -440,7 +440,7 @@"tests": ["com.gotcha.tools.TermuxFileBridgeTest"],- "notes": "TermuxFileBridgeTest — the deterministic bridge that moves a file out of Termux: ~/ and $HOME expansion to Termux's home, the exact python3 loopback sender script (ephemeral port, single-use nonce, READY handshake, 64KiB chunked stream, nonce mismatch rejection, python-quoting of the path), and the shared-storage-vs-loopback selection (only /sdcard when the ~/storage link exists AND the destination is reachable from Termux). The live transfer — a real cp through /sdcard or a loopback python3 send on a device with Termux — must be verified by hand"+ "notes": "the deterministic bridge that moves a file out of Termux: ~/ and $HOME expansion to Termux's home, the exact python3 loopback sender script (ephemeral port, single-use nonce, READY handshake, size header, 64KiB chunked stream), the socket machinery driven over a real 127.0.0.1 ServerSocket pair (nonce-accept, wrong-nonce refusal then keep-listening, exact-size success, and a sender that closes early failing WITHOUT leaving a destination or stray temp file), and the shared-storage-vs-loopback selection (only /sdcard when the ~/storage link exists AND the destination is reachable from Termux AND the file is below the 100MB FUSE threshold). The live transfer — a real cp through /sdcard or a loopback python3 send on a device with Termux — must be verified by hand"},{"tool": "synthesize_podcast",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 3f78c83..07eaacb 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -72,7 +72,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `notion_create_page` | `UNIT` | `NotionToolsTest` — parent/title handling and request shape || `pause_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `pdf_edit` | `ROBOLECTRIC` | `PdfToolTest`, `PdfPageSpecTest`, `PdfEncryptionTest` — every operation round-tripped through pdfbox (merge order, split naming, extract/delete page identity, cumulative rotation), password-protected files at 40/128/256-bit, and the guards: overwrite refusal, safe write-back over the input, delete-all refusal, non-PDF signature rejection and page-range arithmetic |-| `pull_from_termux` | `ROBOLECTRIC` | `TermuxFileBridgeTest` — TermuxFileBridgeTest — the deterministic bridge that moves a file out of Termux: ~/ and $HOME expansion to Termux's home, the exact python3 loopback sender script (ephemeral port, single-use nonce, READY handshake, 64KiB chunked stream, nonce mismatch rejection, python-quoting of the path), and the shared-storage-vs-loopback selection (only /sdcard when the ~/storage link exists AND the destination is reachable from Termux). The live transfer — a real cp through /sdcard or a loopback python3 send on a device with Termux — must be verified by hand |+| `pull_from_termux` | `ROBOLECTRIC` | `TermuxFileBridgeTest` — the deterministic bridge that moves a file out of Termux: ~/ and $HOME expansion to Termux's home, the exact python3 loopback sender script (ephemeral port, single-use nonce, READY handshake, size header, 64KiB chunked stream), the socket machinery driven over a real 127.0.0.1 ServerSocket pair (nonce-accept, wrong-nonce refusal then keep-listening, exact-size success, and a sender that closes early failing WITHOUT leaving a destination or stray temp file), and the shared-storage-vs-loopback selection (only /sdcard when the ~/storage link exists AND the destination is reachable from Termux AND the file is below the 100MB FUSE threshold). The live transfer — a real cp through /sdcard or a loopback python3 send on a device with Termux — must be verified by hand || `resume_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `run_command` | `UNIT` | `TerminalToolTest` — argument splitting, timeout, exit codes, output truncation || `run_root_command` | `MANUAL_ONLY` | Requires a rooted device and an interactive superuser grant. |