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: pipe stdin to Termux commands so interactive prompts stop hanging
Durganshu Mishraf7d80d6d63fb
diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.ktindex a178e36..37f4a4f 100644--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt@@ -118,10 +118,11 @@ class TermuxTool(suspend fun runCommand(command: String,workingDir: String? = null,- timeoutSeconds: Int? = null+ timeoutSeconds: Int? = null,+ stdin: String? = null): ToolResult {val trimmed = command.trim()- validate(trimmed)?.let { return it }+ validate(trimmed, stdin)?.let { return it }val status = status()if (!status.installed) return notInstalled()@@ -139,12 +140,12 @@ class TermuxTool(TermuxResultReceiver.resultIntent(context, requestCode),pendingIntentFlags())- runCatching { context.startService(commandIntent(trimmed, workingDir, pendingIntent)) }+ runCatching { context.startService(commandIntent(trimmed, workingDir, stdin, pendingIntent)) }.exceptionOrNull()?.let { return startFailed(it) }val bundle = withTimeoutOrNull(timeout * 1000L) { deferred.await() }- ?: return timedOut(trimmed, timeout)+ ?: return timedOut(trimmed, timeout, hadStdin = stdin != null)return formatResult(bundle)} finally {pendingResults.remove(requestCode)@@ -188,16 +189,18 @@ class TermuxTool(}/** Cheap checks that need neither Termux nor a permission, so they report the real problem first. */- private fun validate(trimmed: String): ToolResult? {+ private fun validate(trimmed: String, stdin: String? = null): ToolResult? {if (trimmed.isEmpty()) {return ToolResult.error("Empty command. Provide a shell command to run in Termux (e.g. 'pkg install python -y').")}- if (trimmed.length > MAX_COMMAND_CHARS) {+ // Command and stdin ride in the same binder transaction, so they share the budget.+ val total = trimmed.length + (stdin?.length ?: 0)+ if (total > MAX_COMMAND_CHARS) {return ToolResult.error(- "Command is ${trimmed.length} characters, over Termux's ~${MAX_COMMAND_CHARS / 1024}KB limit for a " +- "single command. You may write the script to a file with write_file and run that file instead."+ "Command plus stdin is $total characters, over Termux's ~${MAX_COMMAND_CHARS / 1024}KB limit for a " ++ "single request. You may write the script to a file with write_file and run that file instead.")}denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {@@ -209,7 +212,16 @@ class TermuxTool(return null}- private fun commandIntent(command: String, workingDir: String?, result: PendingIntent): Intent =+ /** Builds the intent without sending it, so the extras can be asserted without Termux. */+ internal fun buildCommandIntentForTest(command: String, workingDir: String?, stdin: String?): Intent =+ commandIntent(command, workingDir, stdin, result = null)++ private fun commandIntent(+ command: String,+ workingDir: String?,+ stdin: String?,+ result: PendingIntent?+ ): Intent =Intent(ACTION_RUN_COMMAND).apply {setClassName(TERMUX_PACKAGE, RUN_COMMAND_SERVICE)putExtra(EXTRA_COMMAND_PATH, "${termuxFiles()}/usr/bin/sh")@@ -217,7 +229,10 @@ class TermuxTool(putExtra(EXTRA_WORKDIR, workingDir?.trim()?.takeIf { it.isNotEmpty() } ?: termuxHome())// Headless: run without opening a terminal session in front of the user.putExtra(EXTRA_BACKGROUND, true)- putExtra(EXTRA_PENDING_INTENT, result)+ // Without this, anything that reads stdin blocks until our timeout and reports a+ // hang rather than the prompt it is actually stuck on. Termux 0.109+.+ if (stdin != null) putExtra(EXTRA_STDIN, stdin)+ if (result != null) putExtra(EXTRA_PENDING_INTENT, result)}/**@@ -263,11 +278,22 @@ class TermuxTool("by the system. You may open Termux once and ask again, or use run_command for the app's own sandbox.")- private fun timedOut(command: String, timeout: Int) = ToolResult.error(- "No result from Termux after ${timeout}s for: $command. Two things cause this and I cannot tell them " +- "apart: the command may still be running in Termux (I cannot kill another app's process, so check " +- "Termux itself), or `allow-external-apps=true` is missing from `~/.termux/termux.properties`, in which " +- "case Termux silently ignored the request. You may retry with a larger timeout_seconds."+ /**+ * The causes are indistinguishable from here — Termux gives us nothing until the command+ * finishes — so the message lists them rather than guessing at one.+ */+ private fun timedOut(command: String, timeout: Int, hadStdin: Boolean) = ToolResult.error(+ buildString {+ append("No result from Termux after ${timeout}s for: $command. I cannot tell these apart:")+ if (!hadStdin) {+ append("\n- the command may be waiting for typed input that will never come — there is no ")+ append("terminal here. Retry with a non-interactive flag (e.g. -y) or pass the answer in stdin.")+ }+ append("\n- it may simply still be running. I cannot kill another app's process, so it keeps going; ")+ append("check Termux itself, and retry with a larger timeout_seconds if it was just slow.")+ append("\n- `allow-external-apps=true` may be missing from `~/.termux/termux.properties`, in which ")+ append("case Termux silently ignored the request and no command ever ran.")+ })private fun cap(text: String): String =@@ -298,10 +324,11 @@ class TermuxTool(private const val RUN_COMMAND_SERVICE = "com.termux.app.RunCommandService"private const val ACTION_RUN_COMMAND = "com.termux.RUN_COMMAND"- private const val EXTRA_COMMAND_PATH = "com.termux.RUN_COMMAND_PATH"- private const val EXTRA_ARGUMENTS = "com.termux.RUN_COMMAND_ARGUMENTS"- private const val EXTRA_WORKDIR = "com.termux.RUN_COMMAND_WORKDIR"- private const val EXTRA_BACKGROUND = "com.termux.RUN_COMMAND_BACKGROUND"+ internal const val EXTRA_COMMAND_PATH = "com.termux.RUN_COMMAND_PATH"+ internal const val EXTRA_ARGUMENTS = "com.termux.RUN_COMMAND_ARGUMENTS"+ internal const val EXTRA_WORKDIR = "com.termux.RUN_COMMAND_WORKDIR"+ internal const val EXTRA_STDIN = "com.termux.RUN_COMMAND_STDIN"+ internal const val EXTRA_BACKGROUND = "com.termux.RUN_COMMAND_BACKGROUND"private const val EXTRA_PENDING_INTENT = "com.termux.RUN_COMMAND_PENDING_INTENT"/**diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 0267433..b54ee9b 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1897,6 +1897,16 @@ object ToolDefinitions {"Timeout in seconds (1-600). Default 60 — raise it for package installs and builds.")}+ putJsonObject("stdin") {+ put("type", "string")+ put(+ "description",+ "Text piped to the command's standard input. Supply this for anything that would " ++ "otherwise wait for typed input — there is no terminal to type into, so an " ++ "unanswered prompt just runs until the timeout. Prefer non-interactive flags " ++ "(e.g. 'pkg install -y') where they exist."+ )+ }}putJsonArray("required") { add("command") }}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex bb682be..5624b63 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -519,7 +519,8 @@ class ToolExecutor("run_termux_command" -> termuxTool.runCommand(command = args.requireString("command") ?: return missing("command"),workingDir = args.requireString("working_dir"),- timeoutSeconds = args.requireInt("timeout_seconds")+ timeoutSeconds = args.requireInt("timeout_seconds"),+ stdin = args.requireString("stdin"))"write_secure_settings" -> rootTool.writeSecureSetting(namespace = args.requireString("namespace") ?: return missing("namespace"),diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.ktindex e824f8a..a0b8be5 100644--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt@@ -7,6 +7,7 @@ import android.content.pm.PackageInfoimport android.os.Bundleimport androidx.test.core.app.ApplicationProviderimport kotlinx.coroutines.test.runTest+import org.junit.Assert.assertArrayEqualsimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNull@@ -151,6 +152,34 @@ class TermuxToolTest {assertNull(result.needsPermission)assertTrue(result.message.contains("still be running"))assertTrue(result.message.contains("allow-external-apps"))+ assertTrue("must name the interactive-prompt cause too", result.message.contains("waiting for typed input"))+ }++ @Test+ fun `the interactive-prompt cause is dropped once stdin was supplied`() = runTest {+ installTermux()+ grantRunCommand()++ val result = tool.runCommand("cat", timeoutSeconds = 1, stdin = "hello")++ assertFalse(result.success)+ assertFalse(+ "stdin was given, so a missing prompt answer cannot be the cause",+ result.message.contains("waiting for typed input")+ )+ assertTrue(result.message.contains("still be running"))+ }++ @Test+ fun `command and stdin share the size budget`() = runTest {+ installTermux()+ grantRunCommand()++ val result = tool.runCommand("cat", stdin = "x".repeat(200 * 1024))++ assertFalse(result.success)+ assertTrue("must name the combined total: ${result.message}", result.message.contains("plus stdin"))+ assertTrue(result.message.contains("write_file"))}@Test@@ -211,6 +240,40 @@ class TermuxToolTest {assertTrue(result.message.contains("write_file"))}+ @Test+ fun `stdin is only attached when supplied`() {+ // A null stdin must not become the string "null" or an empty pipe that makes `read`+ // return EOF when the caller never asked for that.+ installTermux()++ assertFalse(tool.buildCommandIntentForTest("cat", null, null).hasExtra(TermuxTool.EXTRA_STDIN))+ assertEquals(+ "hello",+ tool.buildCommandIntentForTest("cat", null, "hello").getStringExtra(TermuxTool.EXTRA_STDIN)+ )+ }++ @Test+ fun `the command intent targets termux's shell with -c and runs headless`() {+ installTermux()++ val intent = tool.buildCommandIntentForTest("echo hi", null, null)++ assertEquals("${tool.termuxFiles()}/usr/bin/sh", intent.getStringExtra(TermuxTool.EXTRA_COMMAND_PATH))+ assertArrayEquals(arrayOf("-c", "echo hi"), intent.getStringArrayExtra(TermuxTool.EXTRA_ARGUMENTS))+ assertEquals(tool.termuxHome(), intent.getStringExtra(TermuxTool.EXTRA_WORKDIR))+ assertTrue("must stay headless", intent.getBooleanExtra(TermuxTool.EXTRA_BACKGROUND, false))+ }++ @Test+ fun `an explicit working_dir overrides termux home`() {+ installTermux()++ val intent = tool.buildCommandIntentForTest("ls", "/data/data/com.termux/files/usr", null)++ assertEquals("/data/data/com.termux/files/usr", intent.getStringExtra(TermuxTool.EXTRA_WORKDIR))+ }+// ---- result-bundle parsing ----@Test