Skip to content

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: correct Termux errno polarity and detect the Play build (#7)

Durganshu Mishra97f9b0de3a61
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 0ac305e..1e1f586 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -1170,11 +1170,17 @@ class AgentEngine(
// RUN_COMMAND permission is granted, so this line is how the model knows to say
// "install Termux" or "allow the permission" rather than just failing.
appendLine(
- if (termux.installed) {
- " Termux installed: yes (version ${termux.versionName ?: "unknown"}, " +
- "RUN_COMMAND granted: ${if (termux.permissionGranted) "yes" else "no"})"
- } else {
- " Termux installed: no (so run_termux_command is unavailable — no Linux user-space)"
+ when {
+ !termux.installed ->
+ " Termux installed: no (so run_termux_command is unavailable — no Linux user-space)"
+ !termux.pluginApiAvailable ->
+ " Termux installed: yes (version ${termux.versionName ?: "unknown"}) but this build " +
+ "has no RUN_COMMAND service — it is the Google Play build, which removes the API. " +
+ "run_termux_command is unavailable and no permission can fix it; only replacing " +
+ "Termux with the F-Droid or GitHub build would."
+ else ->
+ " Termux installed: yes (version ${termux.versionName ?: "unknown"}, " +
+ "RUN_COMMAND granted: ${if (termux.permissionGranted) "yes" else "no"})"
}
)
// Tools depending on a capability that is "no" here are withheld from
diff --git a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt
index f0704ae..bd547c5 100644
--- a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt
+++ b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt
@@ -34,7 +34,7 @@ object DeviceCapabilities {
if (notificationListenerEnabled(context)) add(Capability.NOTIFICATION_LISTENER)
if (deviceAdminActive(context)) add(Capability.DEVICE_ADMIN)
if (rootAvailable()) add(Capability.ROOT)
- if (termuxInstalled(context)) add(Capability.TERMUX)
+ if (termuxUsable(context)) add(Capability.TERMUX)
if (healthConnectPresent(context)) add(Capability.HEALTH_CONNECT)
if (overlayAllowed(context)) add(Capability.OVERLAY)
}
@@ -83,16 +83,16 @@ object DeviceCapabilities {
}.getOrDefault(false)
/**
- * Whether Termux is installed — deliberately *not* whether its `RUN_COMMAND` permission is
- * granted, for the same reason [healthConnectPresent] ignores its grants: the permission is
- * requested on demand by [TermuxTool], so gating on the grant would hide the only tool that
- * can ever raise the prompt. Needs `<package android:name="com.termux"/>` in the manifest's
+ * Whether Termux is installed *and* exposes the RUN_COMMAND plugin API — deliberately not
+ * whether the permission is granted, for the same reason [healthConnectPresent] ignores its
+ * grants: the permission is requested on demand by [TermuxTool], so gating on it would hide
+ * the only tool that can ever raise the prompt. The plugin API has no such cycle; it is a
+ * fixed property of which Termux build is installed, and the Google Play build ships without
+ * it, so gating on it keeps the tool out of the model's hands on devices where no grant could
+ * ever make it work. Needs `<package android:name="com.termux"/>` in the manifest's
* `<queries>` block to see past targetSdk 30+ package visibility.
*/
- fun termuxInstalled(context: Context): Boolean =
- runCatching {
- context.packageManager.getPackageInfo(TermuxTool.TERMUX_PACKAGE, 0)
- }.isSuccess
+ fun termuxUsable(context: Context): Boolean = TermuxTool(context).status().usable
/**
* Presence of a `su` binary, cached for the process.
diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
index 5457cc1..d666772 100644
--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
@@ -47,9 +47,20 @@ class TermuxTool(
/** What the model needs to know about Termux, rendered into the `<env>` block each turn. */
data class TermuxStatus(
val installed: Boolean,
+ /**
+ * Whether this Termux build actually exposes `RunCommandService`. The Google Play build
+ * strips the whole plugin API — Play policy forbids arbitrary command execution — so it
+ * declares no `RUN_COMMAND` permission and registers no services at all. Without this
+ * check we would ask for a permission the device cannot define, and the user would face
+ * a dialog that never appears.
+ */
+ val pluginApiAvailable: Boolean,
val permissionGranted: Boolean,
val versionName: String?
- )
+ ) {
+ /** Termux can actually run something for us (modulo the grant). */
+ val usable: Boolean get() = installed && pluginApiAvailable
+ }
/**
* Irreversible, device-destroying operations we refuse even here. Deliberately
@@ -70,9 +81,21 @@ class TermuxTool(
ContextCompat.checkSelfPermission(context, PERMISSION_RUN_COMMAND) ==
PackageManager.PERMISSION_GRANTED
}.getOrDefault(false)
- return TermuxStatus(installed = info != null, permissionGranted = granted, versionName = info?.versionName)
+ return TermuxStatus(
+ installed = info != null,
+ pluginApiAvailable = info != null && runCatching { runCommandServiceExists() }.getOrDefault(false),
+ permissionGranted = granted,
+ versionName = info?.versionName
+ )
}
+ /** Whether `com.termux.RUN_COMMAND` resolves to a service — false on the Play build. */
+ private fun runCommandServiceExists(): Boolean =
+ context.packageManager.resolveService(
+ Intent(ACTION_RUN_COMMAND).setPackage(TERMUX_PACKAGE),
+ 0
+ ) != null
+
/** Run [command] through Termux's `sh`, returning stdout/stderr/exit code. */
suspend fun runCommand(
command: String,
@@ -84,6 +107,7 @@ class TermuxTool(
val status = status()
if (!status.installed) return notInstalled()
+ if (!status.pluginApiAvailable) return pluginApiMissing(status.versionName)
if (!status.permissionGranted) return permissionNeeded()
val timeout = (timeoutSeconds ?: defaultTimeoutSeconds).coerceIn(1, MAX_TIMEOUT_SECONDS)
@@ -111,11 +135,11 @@ class TermuxTool(
/** Turn Termux's result bundle into a [ToolResult]. Split out so it is testable without Termux. */
internal fun formatResult(bundle: Bundle): ToolResult {
- val err = bundle.numeric(RESULT_ERR) ?: 0
+ val err = bundle.numeric(RESULT_ERR) ?: ERRNO_SUCCESS
val errmsg = bundle.getString(RESULT_ERRMSG)?.trim().orEmpty()
- if (err != 0) {
+ if (err != ERRNO_SUCCESS) {
return ToolResult.error(
- "Termux refused or could not run the command (error code $err)" +
+ "Termux refused or could not run the command (${errnoLabel(err)})" +
if (errmsg.isEmpty()) "." else ": ${cap(errmsg)}"
)
}
@@ -137,6 +161,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): ToolResult? {
if (trimmed.isEmpty()) {
@@ -187,6 +219,19 @@ class TermuxTool(
"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.
+ */
+ private 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."
+ )
+
private fun permissionNeeded() = ToolResult.permissionNeeded(
ToolResult.TERMUX_ACCESS,
"Running commands in Termux needs Termux's \"Run commands\" permission, which has not been granted. " +
@@ -213,11 +258,20 @@ class TermuxTool(
private fun wasTruncatedByTermux(bundle: Bundle, lengthKey: String, received: String): Boolean =
(bundle.numeric(lengthKey) ?: received.length) > received.length
- /** Termux sends lengths as strings and codes as ints; tolerate either for every numeric field. */
- private fun Bundle.numeric(key: String): Int? {
- if (!containsKey(key)) return null
- runCatching { getString(key) }.getOrNull()?.let { return it.trim().toIntOrNull() }
- return runCatching { getInt(key) }.getOrNull()
+ /**
+ * Termux sends lengths as strings and codes as ints; tolerate either for every numeric field.
+ *
+ * Reads the raw value rather than probing with `getString`/`getInt`, because a typed getter
+ * on the wrong type logs a `ClassCastException` stack trace to logcat on every single call —
+ * noise that made a real bug harder to see. `get` is deprecated precisely because it is
+ * untyped, which is exactly what is wanted here.
+ */
+ @Suppress("DEPRECATION")
+ private fun Bundle.numeric(key: String): Int? = when (val value = get(key)) {
+ is Int -> value
+ is Long -> value.toInt()
+ is String -> value.trim().toIntOrNull()
+ else -> null
}
companion object {
@@ -246,6 +300,17 @@ class TermuxTool(
internal const val RESULT_ERR = "err"
internal const val RESULT_ERRMSG = "errmsg"
+ /**
+ * Termux's `Errno` codes are built on `android.app.Activity`'s result constants, so
+ * success is **-1** (`RESULT_OK`) and zero means *cancelled* — the opposite of the usual
+ * "0 is fine" shell convention. Verified on-device: a successful `uname -a` comes back
+ * 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
+
/** Termux caps a single command near 128KB; leave headroom for the rest of the intent. */
private const val MAX_COMMAND_CHARS = 100 * 1024
diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
index 16f31c5..de44642 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
@@ -210,7 +210,7 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf(
com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND,
null,
{ c -> checkPerm(c, com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND) },
- isRelevant = { c -> com.gotcha.tools.DeviceCapabilities.termuxInstalled(c) }
+ isRelevant = { c -> com.gotcha.tools.DeviceCapabilities.termuxUsable(c) }
),
PermissionItem(
"Device Admin (Optional)",
diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
index 8d485b8..f492d0a 100644
--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
@@ -1,6 +1,8 @@
package com.gotcha.tools
+import android.content.ComponentName
import android.content.Context
+import android.content.IntentFilter
import android.content.pm.PackageInfo
import android.os.Bundle
import androidx.test.core.app.ApplicationProvider
@@ -31,7 +33,25 @@ class TermuxToolTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val tool = TermuxTool(context)
+ /**
+ * The F-Droid/GitHub build: the package plus a resolvable RunCommandService.
+ *
+ * [playStoreTermux] is the other real-world shape — verified on a Nothing Phone 3a running
+ * the Play build, which registers no services at all.
+ */
private fun installTermux() {
+ playStoreTermux()
+ shadowOf(context.packageManager).addServiceIfNotPresent(
+ ComponentName(TermuxTool.TERMUX_PACKAGE, "com.termux.app.RunCommandService")
+ )
+ shadowOf(context.packageManager).addIntentFilterForService(
+ ComponentName(TermuxTool.TERMUX_PACKAGE, "com.termux.app.RunCommandService"),
+ IntentFilter("com.termux.RUN_COMMAND")
+ )
+ }
+
+ /** Termux installed, but the plugin API stripped — the Google Play build. */
+ private fun playStoreTermux() {
shadowOf(context.packageManager).installPackage(
PackageInfo().apply {
packageName = TermuxTool.TERMUX_PACKAGE
@@ -51,6 +71,7 @@ class TermuxToolTest {
fun `status reports termux absent on a clean device`() {
val status = tool.status()
assertFalse(status.installed)
+ assertFalse(status.usable)
assertNull(status.versionName)
}
@@ -61,10 +82,38 @@ class TermuxToolTest {
val status = tool.status()
assertTrue(status.installed)
+ assertTrue(status.pluginApiAvailable)
+ assertTrue(status.usable)
assertTrue(status.permissionGranted)
assertEquals("0.118.0", status.versionName)
}
+ @Test
+ fun `the play store build is installed but not usable`() {
+ playStoreTermux()
+
+ val status = tool.status()
+ assertTrue(status.installed)
+ assertFalse("Play build registers no RunCommandService", status.pluginApiAvailable)
+ assertFalse("must not be gated in as usable", status.usable)
+ }
+
+ @Test
+ fun `the play store build is called out rather than asking for a permission that cannot exist`() = runTest {
+ // Verified against a real device: the Play build declares no RUN_COMMAND permission at
+ // all, so `pm grant` fails with "Unknown permission". Prompting would be a dead end.
+ playStoreTermux()
+ grantRunCommand()
+
+ val result = tool.runCommand("echo hello")
+
+ assertFalse(result.success)
+ assertNull("a permission prompt could never be satisfied here", result.needsPermission)
+ assertTrue(result.message.contains("Google Play build"))
+ assertTrue(result.message.contains("F-Droid"))
+ assertTrue(result.message.contains("Do not retry"))
+ }
+
@Test
fun `without termux the tool points at run_command instead`() = runTest {
val result = tool.runCommand("echo hello")
@@ -172,16 +221,42 @@ class TermuxToolTest {
}
@Test
- fun `a termux-side error surfaces its message and fails`() {
+ fun `errno -1 is success, not an error`() {
+ // Regression test for a real inversion. Termux's Errno is built on Activity's result
+ // constants: RESULT_OK is -1, so ERRNO_SUCCESS is -1 and 0 means *cancelled* — the
+ // opposite of the shell convention. Reading `err != 0` as failure discarded every
+ // successful run. Caught on a Nothing Phone 3a: `uname -a` returned err = -1 and its
+ // output was thrown away as "Termux refused or could not run the command".
+ val bundle = resultBundle(exitCode = 0, stdout = "Linux localhost 5.15.0 aarch64 Android\n")
+ .apply { putInt(TermuxTool.RESULT_ERR, TermuxTool.ERRNO_SUCCESS) }
+
+ val result = tool.formatResult(bundle)
+
+ assertTrue("errno -1 means success: ${result.message}", result.success)
+ assertTrue(result.message.contains("aarch64"))
+ }
+
+ @Test
+ fun `errno 0 is cancelled, not success`() {
+ val bundle = resultBundle(exitCode = 0).apply { putInt(TermuxTool.RESULT_ERR, 0) }
+
+ val result = tool.formatResult(bundle)
+
+ assertFalse(result.success)
+ assertTrue(result.message.contains("cancelled"))
+ }
+
+ @Test
+ fun `a termux-side failure surfaces its message and fails`() {
val bundle = resultBundle(exitCode = 0).apply {
- putInt(TermuxTool.RESULT_ERR, -101)
+ putInt(TermuxTool.RESULT_ERR, 2) // ERRNO_FAILED
putString(TermuxTool.RESULT_ERRMSG, "allow-external-apps is false")
}
val result = tool.formatResult(bundle)
assertFalse(result.success)
- assertTrue(result.message.contains("error code -101"))
+ assertTrue(result.message.contains("failed"))
assertTrue(result.message.contains("allow-external-apps is false"))
}