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: cap concurrent Termux commands so timed-out ones cannot pile up
Durganshu Mishrac6db9d823717
diff --git a/app/src/main/java/com/gotcha/tools/TermuxMessages.kt b/app/src/main/java/com/gotcha/tools/TermuxMessages.ktnew file mode 100644index 0000000..2cc9dd9--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/TermuxMessages.kt@@ -0,0 +1,90 @@+package com.gotcha.tools++/**+ * What the model is told when a Termux command cannot run, or ran but told us little.+ *+ * Kept apart from [TermuxTool] because these are the product of the work rather than the+ * mechanics of it: every one of them is the model's only clue about a device state it cannot+ * otherwise see, and several describe situations we genuinely cannot distinguish. Composing them+ * next to the intent plumbing made both harder to read.+ */+internal object TermuxMessages {++ fun notInstalled() = ToolResult.error(+ "Termux is not installed, so there is no Linux user-space to run this in. You may ask the user to install " ++ "Termux from F-Droid (the Play Store build is unmaintained), or use run_command for the plain " ++ "unprivileged shell available inside Gotcha's own sandbox."+ )++ /**+ * Termux is installed but has no RunCommandService. In practice this means the Google Play+ * build, which removes the plugin API wholesale to satisfy Play policy — no amount of+ * permission granting or property setting will make it work.+ */+ fun pluginApiMissing(versionName: String?) = ToolResult.error(+ "Termux is installed (version ${versionName ?: "unknown"}) but this build has no RUN_COMMAND " ++ "service, so it cannot run commands for other apps. The Google Play build of Termux removes " ++ "that API. Tell the user to replace it with the F-Droid or GitHub build of Termux if they want " ++ "this; nothing can be granted to fix the Play build. Meanwhile use run_command for the plain " ++ "unprivileged shell. Do not retry."+ )++ fun permissionNeeded() = ToolResult.permissionNeeded(+ ToolResult.TERMUX_ACCESS,+ "Running commands in Termux needs Termux's \"Run commands\" permission, which has not been granted. " ++ "I have asked for it — please allow it, then in Termux add the line `allow-external-apps=true` to " ++ "`~/.termux/termux.properties` and restart Termux, and ask again. (If no permission dialog appeared, " ++ "Termux was installed after Gotcha — reinstall or update Gotcha so Android can grant it.)"+ )++ fun startFailed(cause: Throwable) = ToolResult.error(+ "Could not reach Termux's RUN_COMMAND service: ${cause.message}. Termux may have been disabled or stopped " ++ "by the system. You may open Termux once and ask again, or use run_command for the app's own sandbox."+ )++ fun tooManyInFlight(limit: Int) = ToolResult.error(+ "$limit Termux commands are already running and none has finished yet. Earlier commands keep running " ++ "even after they time out — I cannot kill them. Wait for them to finish (use the sleep tool), or " ++ "check Termux directly, rather than starting another."+ )++ /**+ * The causes are indistinguishable from here — Termux sends nothing until a command finishes+ * — so this lists them rather than picking one and sounding certain.+ */+ 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.")+ }+ )++ fun emptyCommand() = ToolResult.error(+ "Empty command. Provide a shell command to run in Termux (e.g. 'pkg install python -y')."+ )++ fun tooLarge(total: Int, limitChars: Int) = ToolResult.error(+ "Command plus stdin is $total characters, over Termux's ~${limitChars / 1024}KB limit for a single " ++ "request. You may write the script to a file with write_file and run that file instead."+ )++ fun blocked(command: String) = ToolResult.error(+ "Command blocked by safety policy (irreversible/device-destroying): $command. You may use available " ++ "tools (list_files, read_file, grep) instead for safer operations."+ )++ /** Termux's errno is not a plain "0 means fine" code, so spell it out. */+ fun errnoLabel(err: Int): String = when (err) {+ TermuxTool.ERRNO_CANCELLED -> "cancelled"+ TermuxTool.ERRNO_MINOR_FAILURES -> "completed with minor failures"+ TermuxTool.ERRNO_FAILED -> "failed"+ else -> "error code $err"+ }+}diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.ktindex 37f4a4f..22db5d0 100644--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt@@ -8,6 +8,7 @@ import android.os.Buildimport android.os.Bundleimport androidx.core.content.ContextCompatimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.sync.Semaphoreimport kotlinx.coroutines.withTimeoutOrNullimport java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.atomic.AtomicInteger@@ -125,11 +126,15 @@ class TermuxTool(validate(trimmed, stdin)?.let { return it }val status = status()- if (!status.installed) return notInstalled()- if (!status.pluginApiAvailable) return pluginApiMissing(status.versionName)- if (!status.permissionGranted) return permissionNeeded()+ if (!status.installed) return TermuxMessages.notInstalled()+ if (!status.pluginApiAvailable) return TermuxMessages.pluginApiMissing(status.versionName)+ if (!status.permissionGranted) return TermuxMessages.permissionNeeded()val timeout = (timeoutSeconds ?: defaultTimeoutSeconds).coerceIn(1, MAX_TIMEOUT_SECONDS)+ // A timed-out command is not cancelled — it keeps running under Termux's uid, out of our+ // reach. Without a ceiling, a model that retries a slow `pkg` a few times would leave a+ // growing pile of live processes behind it, each still holding Termux's package lock.+ if (!inFlight.tryAcquire()) return TermuxMessages.tooManyInFlight(MAX_CONCURRENT_COMMANDS)val requestCode = nextRequestCode.getAndIncrement()val deferred = CompletableDeferred<Bundle>()pendingResults[requestCode] = deferred@@ -142,13 +147,14 @@ class TermuxTool()runCatching { context.startService(commandIntent(trimmed, workingDir, stdin, pendingIntent)) }.exceptionOrNull()- ?.let { return startFailed(it) }+ ?.let { return TermuxMessages.startFailed(it) }val bundle = withTimeoutOrNull(timeout * 1000L) { deferred.await() }- ?: return timedOut(trimmed, timeout, hadStdin = stdin != null)+ ?: return TermuxMessages.timedOut(trimmed, timeout, hadStdin = stdin != null)return formatResult(bundle)} finally {pendingResults.remove(requestCode)+ inFlight.release()}}@@ -158,7 +164,7 @@ class TermuxTool(val errmsg = bundle.getString(RESULT_ERRMSG)?.trim().orEmpty()if (err != ERRNO_SUCCESS) {return ToolResult.error(- "Termux refused or could not run the command (${errnoLabel(err)})" ++ "Termux refused or could not run the command (${TermuxMessages.errnoLabel(err)})" +if (errmsg.isEmpty()) "." else ": ${cap(errmsg)}")}@@ -180,34 +186,14 @@ class TermuxTool(return ToolResult(success = exit == 0, message = message)}- /** Human-readable form of Termux's errno, which is not a plain "0 means fine" code. */- private fun errnoLabel(err: Int): String = when (err) {- ERRNO_CANCELLED -> "cancelled"- ERRNO_MINOR_FAILURES -> "completed with minor failures"- ERRNO_FAILED -> "failed"- else -> "error code $err"- }-/** Cheap checks that need neither Termux nor a permission, so they report the real problem first. */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.isEmpty()) return TermuxMessages.emptyCommand()// 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 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."- )- }+ if (total > MAX_COMMAND_CHARS) return TermuxMessages.tooLarge(total, MAX_COMMAND_CHARS)denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {- return ToolResult.error(- "Command blocked by safety policy (irreversible/device-destroying): $trimmed. You may use available " +- "tools (list_files, read_file, grep) instead for safer operations."- )+ return TermuxMessages.blocked(trimmed)}return null}@@ -273,29 +259,6 @@ class TermuxTool("Termux was installed after Gotcha — reinstall or update Gotcha so Android can grant it.)")- private fun startFailed(cause: Throwable) = ToolResult.error(- "Could not reach Termux's RUN_COMMAND service: ${cause.message}. Termux may have been disabled or stopped " +- "by the system. You may open Termux once and ask again, or use run_command for the app's own sandbox."- )-- /**- * 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 =if (text.length <= maxOutputBytes) text else text.take(maxOutputBytes) + "\n…(output capped)"@@ -355,9 +318,9 @@ class TermuxTool(* with `err = -1`. Reading these as ordinary error codes silently inverts every result.*/internal const val ERRNO_SUCCESS = -1 // Activity.RESULT_OK- private const val ERRNO_CANCELLED = 0 // Activity.RESULT_CANCELED- private const val ERRNO_MINOR_FAILURES = 1 // Activity.RESULT_FIRST_USER- private const val ERRNO_FAILED = 2 // Activity.RESULT_FIRST_USER + 1+ internal const val ERRNO_CANCELLED = 0 // Activity.RESULT_CANCELED+ internal const val ERRNO_MINOR_FAILURES = 1 // Activity.RESULT_FIRST_USER+ internal const val ERRNO_FAILED = 2 // Activity.RESULT_FIRST_USER + 1/** Termux caps a single command near 128KB; leave headroom for the rest of the intent. */private const val MAX_COMMAND_CHARS = 100 * 1024@@ -365,6 +328,27 @@ class TermuxTool(/** `pkg install` is slow, so this is far above [TerminalTool]'s 120s ceiling. */private const val MAX_TIMEOUT_SECONDS = 600+ /**+ * Ceiling on commands running at once. Deliberately process-wide rather than per+ * instance: sub-agents build their own [ToolExecutor], and Termux is a single shared+ * resource regardless of who asked.+ */+ private const val MAX_CONCURRENT_COMMANDS = 4++ /** Test seam: lets the cap be saturated without hardcoding the number twice. */+ internal const val MAX_CONCURRENT_FOR_TEST = MAX_CONCURRENT_COMMANDS++ /**+ * Test seams for the concurrency cap. Occupying slots directly beats racing real+ * commands: `runTest` runs on virtual time, so a command that "blocks" for its timeout+ * actually returns instantly and hands its slot straight back.+ */+ internal fun acquireSlotForTest(): Boolean = inFlight.tryAcquire()++ internal fun releaseSlotForTest() = inFlight.release()++ private val inFlight = Semaphore(MAX_CONCURRENT_COMMANDS)+private val nextRequestCode = AtomicInteger(1)/**diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.ktindex a0b8be5..975f07e 100644--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt@@ -182,6 +182,41 @@ class TermuxToolTest {assertTrue(result.message.contains("write_file"))}+ @Test+ fun `commands are refused once the concurrency cap is saturated`() = runTest {+ installTermux()+ grantRunCommand()+ repeat(TermuxTool.MAX_CONCURRENT_FOR_TEST) {+ assertTrue("slot $it should be free", TermuxTool.acquireSlotForTest())+ }+ try {+ val refused = tool.runCommand("echo hello", timeoutSeconds = 1)++ assertFalse(refused.success)+ assertTrue(+ "should refuse rather than queue: ${refused.message}",+ refused.message.contains("already running")+ )+ assertTrue("must explain why waiting is the fix", refused.message.contains("cannot kill"))+ } finally {+ repeat(TermuxTool.MAX_CONCURRENT_FOR_TEST) { TermuxTool.releaseSlotForTest() }+ }+ }++ @Test+ fun `a finished command hands its slot back`() = runTest {+ // Without the release, four timeouts would disable the tool for the rest of the session.+ installTermux()+ grantRunCommand()++ tool.runCommand("echo hello", timeoutSeconds = 1)++ repeat(TermuxTool.MAX_CONCURRENT_FOR_TEST) {+ assertTrue("slot $it should have been returned", TermuxTool.acquireSlotForTest())+ }+ repeat(TermuxTool.MAX_CONCURRENT_FOR_TEST) { TermuxTool.releaseSlotForTest() }+ }+@Testfun `termux paths come from the installed package, not a hardcoded primary-user path`() {// /data/data/com.termux is only the primary user's path; a secondary user or work