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.
feat: implement TermuxFileBridge to support secure loopback-based file transfers from Termux
Gotcha Contributoreed2471c32e2
diff --git a/app/src/main/assets/skills/termux_filesystem.json b/app/src/main/assets/skills/termux_filesystem.jsonindex 8f5c181..634c246 100644--- a/app/src/main/assets/skills/termux_filesystem.json+++ b/app/src/main/assets/skills/termux_filesystem.json@@ -21,7 +21,12 @@"download","profile","secondary user",- "prefix"+ "prefix",+ "nc",+ "loopback",+ "pull_from_termux",+ "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."+ "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`."}diff --git a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.ktindex 226d3df..cd5b6b6 100644--- a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt+++ b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt@@ -57,7 +57,7 @@ enum class Capability(// run_termux_command. Hiding it without Termux is the point: it is the only route to// MP3, and a model that could see it on a device that cannot run it would promise a// conversion it has no way to perform.- setOf("run_termux_command", "media_convert")+ setOf("run_termux_command", "media_convert", "pull_from_termux")),HEALTH_CONNECT(diff --git a/app/src/main/java/com/gotcha/tools/TermuxFileBridge.kt b/app/src/main/java/com/gotcha/tools/TermuxFileBridge.ktnew file mode 100644index 0000000..93e5263--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/TermuxFileBridge.kt@@ -0,0 +1,314 @@+package com.gotcha.tools++import android.content.Context+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeout+import java.io.File+import java.io.FileOutputStream+import java.io.InputStream+import java.net.InetAddress+import java.net.ServerSocket+import java.net.Socket+import java.util.UUID++/**+ * Moves a file from Termux's private filesystem into a location Gotcha (and the user) can reach.+ *+ * Gotcha runs at `/storage/emulated/0/Gotcha/...` under its own uid, Termux at+ * `/data/data/com.termux/files/home` under another — the two cannot see each other's files. The+ * documented bridge is shared storage (`/sdcard`) via `termux-setup-storage`, but that only exists+ * after the user has run the command AND granted Android's dialog, and `run_termux_command` always+ * reports `exit 0` whether or not the grant happened. So the bridge here is chosen+ * deterministically, not left to the model:+ *+ * 1. **Shared storage** when Termux's `~/storage` link actually exists and the destination is+ * reachable from Termux — the documented, debuggable path, a plain `cp`.+ * 2. **Loopback TCP** otherwise: Termux streams the file with `python3` over `127.0.0.1` and+ * Gotcha receives it with a Kotlin `ServerSocket`. Loopback crosses the uid boundary without+ * touching scoped-storage permissions at all, which is exactly what a fresh Termux (or a user+ * who never granted `termux-setup-storage`) needs.+ *+ * 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.+ */+class TermuxFileBridge(+ private val context: Context,+ private val termux: TermuxTool = TermuxTool(context)+) {++ private val resolver = FileResolver(context)++ companion object {+ /** Below this size the `/sdcard` bridge is fine; above it FUSE starts to matter. */+ const val SHARED_STORAGE_MAX_BYTES = 100L * 1024 * 1024++ /** 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"++ private const val STORAGE_LINKED_MARKER = "STORAGE_LINKED"++ /** Upper bound for one transfer; the socket also guards with its own read timeout. */+ const val BRIDGE_TIMEOUT_SECONDS = 300++ /** How long we wait for the sender to connect at all. */+ private const val ACCEPT_TIMEOUT_MS = 30_000L++ private const val CHUNK_BYTES = 64 * 1024++ /** Handshake the receiver sends once the sender presents the right nonce. */+ private const val READY_ACK = "READY\n"++ private const val DENIED_ACK = "DENIED\n"+ }++ /** Whether Termux's `/sdcard` bridge (`~/storage`) is actually usable, not merely requested. */+ suspend fun isStorageLinked(): Boolean {+ val result = termux.runCommand(PROBE_STORAGE_COMMAND, timeoutSeconds = 15)+ return result.success && linksStorage(result.message)+ }++ /**+ * 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.+ */+ suspend fun pull(termuxPath: String, destination: File): ToolResult {+ val source = expandHome(termuxPath)+ resolver.checkWritePermission(destination)?.let { return it }+ destination.parentFile?.let { parent ->+ if (!parent.exists() && !parent.mkdirs()) {+ 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.+ }+ return copyViaLoopback(source, destination)+ }++ // ---- shared-storage path ----++ private suspend fun copyViaSharedStorage(source: String, destination: File): ToolResult {+ val termuxDest = FfmpegCommand.termuxPath(destination.canonicalPath)+ val command = "cp -- ${FfmpegCommand.shellQuote(source)} ${FfmpegCommand.shellQuote(termuxDest)} " ++ "&& test -f ${FfmpegCommand.shellQuote(termuxDest)} && echo COPIED"+ val result = termux.runCommand(command, timeoutSeconds = BRIDGE_TIMEOUT_SECONDS)+ if (!result.success) {+ return ToolResult.error(+ "Could not copy through shared storage: ${result.message.take(200)}"+ )+ }+ if (!result.message.contains("COPIED")) {+ return ToolResult.error(+ "The copy reported success but '$termuxDest' is missing or empty."+ )+ }+ return ToolResult.ok(+ "Copied '$source' to '${destination.canonicalPath}' through shared storage. " ++ "File size on arrival: ${resolver.formatSize(destination.length())}."+ )+ }++ // ---- loopback path ----++ /**+ * 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.+ */+ private suspend fun copyViaLoopback(source: String, destination: File): ToolResult {+ val nonce = UUID.randomUUID().toString().replace("-", "")+ val server = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))+ try {+ server.reuseAddress = true+ server.soTimeout = ACCEPT_TIMEOUT_MS.toInt()+ val port = server.localPort++ return coroutineScope {+ val send = async {+ termux.runCommand(+ command = senderCommand(port, nonce, source),+ stdin = senderScript(),+ timeoutSeconds = BRIDGE_TIMEOUT_SECONDS+ )+ }+ val receive = async {+ withContext(Dispatchers.IO) {+ withTimeout(BRIDGE_TIMEOUT_SECONDS * 1000L) { receiveInto(server, nonce, destination) }+ }+ }++ val sendResult = send.await()+ if (!sendResult.success) {+ // The sender never ran (python3 missing, permission missing, bad path). Close the+ // socket so the blocking accept() in `receive` throws immediately and the scope can+ // finish without waiting out the accept timeout.+ server.close()+ receive.cancel()+ return@coroutineScope ToolResult.error(+ "Termux failed to start the file transfer sender: ${sendResult.message.take(200)}. " ++ "Ensure Termux has python3 ('pkg install python -y') and that the source " ++ "path '$source' exists."+ )+ }++ try {+ receive.await()+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ return@coroutineScope ToolResult.error(+ "The loopback transfer from Termux failed (${e.message ?: "no detail"}). " ++ "Termux said: ${sendResult.message.take(200)}."+ )+ }++ ToolResult.ok(+ "Pulled '$source' out of Termux to '${destination.canonicalPath}' " ++ "(${resolver.formatSize(destination.length())})."+ )+ }+ } finally {+ server.close()+ }+ }++ /**+ * 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.+ */+ private fun receiveInto(server: ServerSocket, nonce: String, destination: 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 = false+ try {+ while (!transferred) {+ if (System.currentTimeMillis() > deadline) error("no sender connected before the timeout")+ transferred = handleCandidate(server.accept(), nonce, tmp)+ }+ 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.+ tmp.delete()+ }+ }++ /**+ * 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.+ */+ 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+ }+ 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)+ }+ }+ transferred = true+ }+ return transferred+ }++ /** Reads exactly [into].size bytes; returns false if the connection closed early. */+ private fun readFully(input: InputStream, into: ByteArray): Boolean {+ var offset = 0+ while (offset < into.size) {+ val read = input.read(into, offset, into.size - offset)+ if (read < 0) return false+ offset += read+ }+ return true+ }++ // ---- pure helpers, split out for tests ----++ /** Expands a leading `~/` or a literal `$HOME` to Termux's home directory. */+ internal fun expandHome(path: String): String {+ val home = termux.termuxHome()+ return when {+ path == "~" -> home+ path.startsWith("~/") -> home + path.removePrefix("~")+ path.startsWith("\$HOME") -> home + path.removePrefix("\$HOME")+ else -> path+ }+ }++ /** 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)++ /** 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)++ /** Test seam: Termux's home without needing a live Termux install. */+ internal fun termuxHomeForTest(): String = termux.termuxHome()++ /**+ * The command that runs the sender in Termux. The python program is piped via stdin+ * (`python3 -`); the port, nonce and source path ride as argv so nothing is interpolated into+ * the program text — a path with newlines or quotes cannot break it. Wake-lock so Doze cannot+ * stall the transfer.+ */+ 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. */+ internal fun senderScript(): String =+ "import socket, sys\n" ++ "port = int(sys.argv[1])\n" ++ "nonce = sys.argv[2]\n" ++ "path = sys.argv[3]\n" ++ "s = socket.socket()\n" ++ "s.connect(('127.0.0.1', port))\n" ++ "s.sendall(nonce.encode())\n" ++ "ack = s.recv(64)\n" ++ "if ack != b'READY\\n':\n" ++ " s.close()\n" ++ " sys.exit(1)\n" ++ "with open(path, 'rb') as f:\n" ++ " while True:\n" ++ " chunk = f.read($CHUNK_BYTES)\n" ++ " if not chunk:\n" ++ " break\n" ++ " s.sendall(chunk)\n" ++ "s.close()\n"+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex ecbf979..e99eb0a 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -31,7 +31,7 @@ object ToolCategories {"take_photo","start_audio_recording", "stop_audio_recording","pause_audio_recording", "resume_audio_recording",- "run_command", "run_root_command", "run_termux_command",+ "run_command", "run_root_command", "run_termux_command", "pull_from_termux","show_overlay", "hide_overlay","lock_screen", "disable_camera", "set_password_policy","dismiss_notifications", "media_control",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex cd368c2..4048daa 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1699,6 +1699,41 @@ object ToolDefinitions {})+ val pullFromTermux = tool(+ "pull_from_termux",+ "Copy a file that currently lives inside Termux (its Linux user-space) out to a path Gotcha " ++ "and the user can reach, e.g. '/storage/emulated/0/Download/name.mp4'. Uses the shared-storage " ++ "bridge when Termux's storage is linked, and a loopback transfer otherwise, so it works even " ++ "before 'termux-setup-storage' is granted. This is how a file produced inside Termux " ++ "(yt-dlp downloads, script output, server files) gets into the user's Downloads/Gotcha " ++ "folder — run the producing command first with run_termux_command, then pull the result. " ++ "Needs Termux installed.",+ schema {+ putJsonObject("properties") {+ putJsonObject("termux_path") {+ put("type", "string")+ put(+ "description",+ "Absolute path of the file inside Termux, e.g. " ++ "'/data/data/com.termux/files/home/gotcha_guide.mp4' or '~/gotcha_guide.mp4'."+ )+ }+ putJsonObject("destination") {+ put("type", "string")+ put(+ "description",+ "Absolute destination path Gotcha writes to, e.g. " ++ "'/storage/emulated/0/Download/gotcha_guide.mp4'. A parent folder it can write."+ )+ }+ }+ putJsonArray("required") {+ add("termux_path")+ add("destination")+ }+ }+ )+val edit = tool("edit","Replace exact text in a file, for surgical edits without rewriting it. oldString " +@@ -2942,6 +2977,8 @@ object ToolDefinitions {mediaEdit,// Audio format conversion via Termux ffmpeg (Operator only)mediaConvert,+ // Pull a file produced inside Termux out to Gotcha-accessible storage (Operator only)+ pullFromTermux,// Script-to-speech podcast synthesis (Operator only)synthesizePodcast, synthesizePodcastDialogue, sharePodcast,// Audio-file transcription via the STT API (Operator only)diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 2193db7..88854bf 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -72,6 +72,7 @@ class ToolExecutor(private val pdfTool = PdfTool(appContext)private val mediaEditTool = MediaEditTool(appContext)private val mediaConvertTool = MediaConvertTool(appContext)+ private val termuxFileBridge = TermuxFileBridge(appContext)private val podcastTool = PodcastTool(appContext,onUnauthorized = { runCatching { com.gotcha.data.SettingsRepository(appContext).clearSamosaSession() } }@@ -267,6 +268,12 @@ class ToolExecutor(bitrate = args.requireString("bitrate"),overwrite = args.requireBoolean("overwrite") ?: false)+ "pull_from_termux" -> termuxFileBridge.pull(+ termuxPath = args.requireString("termux_path") ?: return missing("termux_path"),+ destination = java.io.File(+ args.requireString("destination") ?: return missing("destination")+ )+ )"synthesize_podcast_dialogue" -> podcastTool.synthesizeDialogue(lines = parseDialogueLines(args["lines"]) ?: return ToolResult.error("Missing or invalid required parameter 'lines' — it must be a non-empty array of " +diff --git a/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.kt b/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.ktnew file mode 100644index 0000000..f912a9a--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/TermuxFileBridgeTest.kt@@ -0,0 +1,99 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * `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.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34])+class TermuxFileBridgeTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val bridge = TermuxFileBridge(context)++ @Test+ fun `a leading tilde expands to termux home`() {+ val home = bridge.termuxHomeForTest()+ assertEquals(home, bridge.expandHome("~"))+ assertEquals("$home/gotcha_guide.mp4", bridge.expandHome("~/gotcha_guide.mp4"))+ }++ @Test+ fun `a dollar HOME expands to termux home`() {+ val home = bridge.termuxHomeForTest()+ assertEquals("$home/out.mp4", bridge.expandHome("\$HOME/out.mp4"))+ }++ @Test+ fun `an absolute termux path is left alone`() {+ val absolute = "/data/data/com.termux/files/home/gotcha_guide.mp4"+ assertEquals(absolute, bridge.expandHome(absolute))+ }++ @Test+ fun `the sender command passes port nonce and path as argv and wake-locks`() {+ val command = bridge.senderCommand(8192, "deadbeef", "/data/.../home/gotcha_guide.mp4")++ assertTrue("must wake-lock the sender", command.contains("termux-wake-lock"))+ assertTrue("must stream python from stdin", command.contains("python3 - 8192 deadbeef"))+ assertTrue(+ "the path must be shell-quoted, not interpolated",+ command.contains("'/data/.../home/gotcha_guide.mp4'")+ )+ }++ @Test+ fun `a hostile path with quotes is shell-quoted rather than breaking the command`() {+ val command = bridge.senderCommand(1, "a", "/data/.../home/it's.mp4")+ assertTrue(command.contains("'/data/.../home/it'\\''s.mp4'"))+ }++ @Test+ fun `the sender program reads its inputs from argv and streams in chunks`() {+ val script = bridge.senderScript()++ assertTrue("must take the port from argv", script.contains("port = int(sys.argv[1])"))+ assertTrue("must take the nonce from argv", script.contains("nonce = sys.argv[2]"))+ assertTrue("must take the path from argv", script.contains("path = sys.argv[3]"))+ assertTrue("must connect to the loopback port", script.contains("s.connect(('127.0.0.1', port))"))+ assertTrue("must present the single-use nonce", script.contains("s.sendall(nonce.encode())"))+ assertTrue("must wait for the READY ack before sending", script.contains("ack != b'READY\\n'"))+ assertTrue("must stream in chunks rather than read the whole file", script.contains("f.read(65536)"))+ assertTrue("must close on a refused handshake", script.contains("sys.exit(1)"))+ }++ @Test+ fun `shared storage is used only when linked and the destination is reachable from termux`() {+ val reachable = "/storage/emulated/0/Download/out.mp4"+ val private = "/data/data/com.gotcha/files/chats/x/out.mp4"+ assertTrue(bridge.usesSharedStorage(true, reachable))+ assertFalse(+ "an app-sandbox path is not reachable from Termux",+ bridge.usesSharedStorage(true, private)+ )+ assertFalse(+ "an unlinked bridge must not be used even for reachable destinations",+ bridge.usesSharedStorage(false, reachable)+ )+ assertFalse(bridge.usesSharedStorage(false, private))+ }++ @Test+ fun `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"))+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 0e1b6ea..a5fce0d 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -434,6 +434,14 @@],"notes": "exhaustive coverage of the generated ffmpeg command on the JVM — POSIX shell quoting against spaces, embedded quotes and metacharacters, /storage/emulated/0 to /sdcard translation including secondary-user roots and near-miss prefixes, bitrate validation, and every audio target's codec arguments — plus the guards that run before Termux is invoked: unsupported and video output formats, nonsense bitrates, paths inside Gotcha's private storage that Termux cannot see, missing input, same-file conversion, existing-output refusal and directory outputs. The conversion itself is device-only and additionally needs Termux with the ffmpeg package installed, so a real MP3 round trip must be verified by hand"},+ {+ "tool": "pull_from_termux",+ "tier": "ROBOLECTRIC",+ "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"+ },{"tool": "synthesize_podcast","tier": "ROBOLECTRIC",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex fce1594..3f78c83 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 26 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 27 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **114** | |+| **Total** | **115** | |-**50 of 114** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**51 of 115** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -72,6 +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 || `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. |diff --git a/docs/termux-setup.md b/docs/termux-setup.mdindex 981e0e1..7aa974e 100644--- a/docs/termux-setup.md+++ b/docs/termux-setup.md@@ -162,7 +162,12 @@ should know these so the user does not have to:MP3 once ffmpeg is installed.- **Shared storage (`/sdcard`).** `/sdcard/Download` is the only safecross-uid bridge between Gotcha and Termux. It is empty inside Termux- until the user runs `termux-setup-storage` once in Termux.+ until the user runs `termux-setup-storage` once in Termux. When that grant+ is missing or a `cp` through FUSE is refused, the `pull_from_termux` tool+ falls back to a loopback transfer over `127.0.0.1` (Termux `python3`+ sender → Gotcha receiver) that crosses the uid boundary without the+ storage grant at all — so a file produced inside Termux always reaches the+ user, whichever bridge works.- **Long-running processes.** A foreground process started by`run_termux_command` is orphaned the moment Gotcha returns. Thepersistence pattern is