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.

feat: add a guided Termux setup page that checks install and configuration state

Rishabh Bajpai4f9624225db2
diff --git a/app/src/androidTest/java/com/gotcha/TermuxSetupFlowTest.kt b/app/src/androidTest/java/com/gotcha/TermuxSetupFlowTest.kt
new file mode 100644
index 0000000..a201d6c
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/TermuxSetupFlowTest.kt
@@ -0,0 +1,61 @@
+package com.gotcha
+
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performScrollTo
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.gotcha.testutil.MockLlm
+import com.gotcha.testutil.TestSeed
+import org.junit.After
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * The Termux guided-setup page, smoke-tested on the CI emulator where Termux is
+ * never installed: the checklist must render and offer the install action. The
+ * installed / configured branches need a real Termux and are QA'd by hand (see
+ * docs/termux-setup.md).
+ */
+@RunWith(AndroidJUnit4::class)
+class TermuxSetupFlowTest {
+
+ @get:Rule
+ val composeRule = createEmptyComposeRule()
+
+ private var scenario: ActivityScenario<MainActivity>? = null
+ private val mockLlm = MockLlm()
+
+ @After
+ fun tearDown() {
+ scenario?.close()
+ mockLlm.shutdown()
+ }
+
+ @Test
+ fun termuxPage_guidesInstallWhenTermuxIsAbsent() {
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl)
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ // Chat home → drawer → Settings → Termux (Linux shell).
+ composeRule.onNodeWithContentDescription("Open menu").performClick()
+ composeRule.onNodeWithText("Settings").performClick()
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("settings_termux_row").performScrollTo().performClick()
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithText("Install Termux").assertExists()
+ composeRule.onNodeWithText("Termux is not installed.").assertExists()
+ composeRule.onNodeWithText("Install Termux from F-Droid").assertExists()
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
index 050c066..44223e3 100644
--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
@@ -65,6 +65,62 @@ class TermuxTool(
val usable: Boolean get() = installed && pluginApiAvailable
}
+ /** How far Termux's `allow-external-apps` setup has been verified. */
+ enum class TermuxConfigProbe {
+ CONFIGURED,
+ NOT_CONFIGURED,
+ UNKNOWN
+ }
+
+ /** The guided-setup view of Termux: everything the Settings page needs to show. */
+ data class TermuxSetupState(
+ val installed: Boolean,
+ val pluginApiAvailable: Boolean,
+ val permissionGranted: Boolean,
+ val versionName: String?,
+ val externalAppsEnabled: TermuxConfigProbe = TermuxConfigProbe.UNKNOWN
+ ) {
+ /** Every step of the setup is done. */
+ val ready: Boolean
+ get() = installed && pluginApiAvailable && permissionGranted &&
+ externalAppsEnabled == TermuxConfigProbe.CONFIGURED
+
+ companion object {
+ fun from(status: TermuxStatus): TermuxSetupState = TermuxSetupState(
+ installed = status.installed,
+ pluginApiAvailable = status.pluginApiAvailable,
+ permissionGranted = status.permissionGranted,
+ versionName = status.versionName
+ )
+ }
+ }
+
+ /**
+ * Probes whether Termux accepts external commands — i.e. `allow-external-apps=true`.
+ *
+ * That property lives in Termux's private storage, so it cannot be read from here. It can
+ * only be discovered by running a command: with the property unset, Termux answers
+ * immediately with an errno whose message names the property; with it set, the command
+ * succeeds. Anything that prevents probing at all (Termux absent, Play build, permission
+ * not granted, Termux stopped, timeout) is [TermuxConfigProbe.UNKNOWN] rather than a guess.
+ */
+ suspend fun probeExternalApps(): TermuxConfigProbe =
+ classifyProbe(runCommand(PROBE_COMMAND, timeoutSeconds = PROBE_TIMEOUT_SECONDS))
+
+ /**
+ * The decision half of [probeExternalApps], split out so it is testable without Termux.
+ *
+ * The `needsPermission` guard matters: [TermuxMessages.permissionNeeded] also mentions
+ * `allow-external-apps`, but it is a guard path — we never got a real answer — so it must
+ * read as [TermuxConfigProbe.UNKNOWN], not [TermuxConfigProbe.NOT_CONFIGURED].
+ */
+ internal fun classifyProbe(result: ToolResult): TermuxConfigProbe = when {
+ result.success -> TermuxConfigProbe.CONFIGURED
+ result.needsPermission == null && result.message.contains("allow-external-apps") ->
+ TermuxConfigProbe.NOT_CONFIGURED
+ else -> TermuxConfigProbe.UNKNOWN
+ }
+
/**
* Irreversible, device-destroying operations we refuse even here. Deliberately
* [RootTool]'s narrow list rather than [TerminalTool]'s: `rm -r` inside Termux's own
@@ -310,6 +366,18 @@ class TermuxTool(
const val TERMUX_PACKAGE = "com.termux"
const val PERMISSION_RUN_COMMAND = "com.termux.permission.RUN_COMMAND"
+ /**
+ * Play-store-free source for Termux. The Play build is unmaintained and strips the
+ * RUN_COMMAND plugin API wholesale, so it can never be made to work with Gotcha.
+ */
+ const val TERMUX_FDROID_URL = "https://f-droid.org/en/packages/com.termux/"
+
+ /** An `allow-external-apps` failure returns within a second; this is a generous ceiling. */
+ private const val PROBE_TIMEOUT_SECONDS = 5
+
+ /** Trivial command used to probe whether Termux accepts external commands. */
+ private const val PROBE_COMMAND = "echo gotcha-probe"
+
private const val RUN_COMMAND_SERVICE = "com.termux.app.RunCommandService"
private const val ACTION_RUN_COMMAND = "com.termux.RUN_COMMAND"
internal const val EXTRA_COMMAND_PATH = "com.termux.RUN_COMMAND_PATH"
diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
index de44642..47fca3e 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
@@ -202,11 +202,13 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf(
),
// A runtime permission rather than a special marker, so the standard toggle can
// request it. Termux declares it, so it only exists once Termux is installed — hence
- // isRelevant. The allow-external-apps half has to be done inside Termux either way.
+ // isRelevant. The allow-external-apps half has to be done inside Termux either way;
+ // the Guided setup link (PermissionsScreen → PermissionsSection) walks through it.
PermissionItem(
"Termux Commands (Optional)",
"Run shell commands and install packages in Termux. Also needs " +
- "`allow-external-apps=true` in Termux's ~/.termux/termux.properties.",
+ "`allow-external-apps=true` in Termux's ~/.termux/termux.properties — use the " +
+ "Guided setup link for step-by-step help.",
com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND,
null,
{ c -> checkPerm(c, com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND) },
diff --git a/app/src/main/java/com/gotcha/ui/PermissionsScreen.kt b/app/src/main/java/com/gotcha/ui/PermissionsScreen.kt
index b818fc6..60706c4 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionsScreen.kt
@@ -8,9 +8,14 @@ import androidx.compose.runtime.Composable
* page frame around it.
*/
@Composable
-fun PermissionsScreen(packageName: String, onBack: () -> Unit) {
+fun PermissionsScreen(
+ packageName: String,
+ onBack: () -> Unit,
+ /** Offered on the Termux row as a shortcut to its guided setup page. */
+ onOpenTermuxSetup: (() -> Unit)? = null
+) {
val overlay = rememberSettingsOverlayState()
SettingsScaffold(title = SettingsPage.PERMISSIONS.title, onBack = onBack, overlay = overlay) {
- PermissionsSection(packageName = packageName)
+ PermissionsSection(packageName = packageName, onOpenTermuxSetup = onOpenTermuxSetup)
}
}
diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
index 46dfe7a..ae6ab8b 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
@@ -12,12 +12,14 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
@@ -42,7 +44,11 @@ import com.gotcha.tools.ToolResult
import android.provider.Settings as AndroidSettings
@Composable
-fun PermissionsSection(packageName: String) {
+fun PermissionsSection(
+ packageName: String,
+ /** Offered on the Termux row as a shortcut to its guided setup page. */
+ onOpenTermuxSetup: (() -> Unit)? = null
+) {
val context = LocalContext.current
val groups = remember { allPermissionGroups() }
var userToggledGroups by remember { mutableStateOf<Map<String, Boolean>>(emptyMap()) }
@@ -124,6 +130,11 @@ fun PermissionsSection(packageName: String) {
packageName = packageName,
onRequestRuntime = { perms ->
runtimeLauncher.launch(perms)
+ },
+ onOpenDetails = if (item.specialMarker == ToolResult.TERMUX_ACCESS) {
+ onOpenTermuxSetup
+ } else {
+ null
}
)
}
@@ -137,7 +148,9 @@ private fun PermissionRow(
item: PermissionItem,
granted: Boolean,
packageName: String,
- onRequestRuntime: (Array<String>) -> Unit
+ onRequestRuntime: (Array<String>) -> Unit,
+ /** Rendered as a secondary "Guided setup" link under the row's description. */
+ onOpenDetails: (() -> Unit)? = null
) {
val context = LocalContext.current
@@ -155,6 +168,17 @@ private fun PermissionRow(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
+ if (onOpenDetails != null) {
+ TextButton(
+ onClick = onOpenDetails,
+ contentPadding = PaddingValues(0.dp)
+ ) {
+ Text(
+ "Guided setup ›",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
}
Switch(
checked = granted,
diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
index b68fb8a..24d0f04 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
@@ -102,6 +102,11 @@ enum class SettingsPage(
"What the assistant is allowed to do",
"settings_permissions_row"
),
+ TERMUX(
+ "Termux (Linux shell)",
+ "Run commands in a real Linux shell",
+ "settings_termux_row"
+ ),
SKILLS(
"Skills / Plugins",
"Built-in and community skills",
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index c50d5e7..fb0c83d 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -148,8 +148,10 @@ fun SettingsScreen(
)
SettingsPage.PERMISSIONS -> PermissionsScreen(
packageName = packageName,
- onBack = backToHome
+ onBack = backToHome,
+ onOpenTermuxSetup = { onPageChange(SettingsPage.TERMUX) }
)
+ SettingsPage.TERMUX -> TermuxSetupScreen(onBack = backToHome)
SettingsPage.SKILLS -> SkillsScreen(
load = load,
onSave = onSave,
diff --git a/app/src/main/java/com/gotcha/ui/TermuxSetupScreen.kt b/app/src/main/java/com/gotcha/ui/TermuxSetupScreen.kt
new file mode 100644
index 0000000..9dcef6f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/TermuxSetupScreen.kt
@@ -0,0 +1,270 @@
+package com.gotcha.ui
+
+import android.content.Intent
+import android.net.Uri
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalLifecycleOwner
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import com.gotcha.tools.TermuxTool
+import com.gotcha.tools.ToolResult
+import com.gotcha.ui.theme.GotchaMono
+import kotlinx.coroutines.launch
+
+/**
+ * Guided Termux setup: a live checklist of the four things that must be true for
+ * `run_termux_command` to work, each with the action to fix it. The cheap checks
+ * (installed / build / permission) are re-read on every resume; the
+ * `allow-external-apps` probe runs a real command, so it only happens on demand.
+ */
+@Composable
+fun TermuxSetupScreen(onBack: () -> Unit) {
+ val context = LocalContext.current
+ val tool = remember(context) { TermuxTool(context) }
+ val overlay = rememberSettingsOverlayState()
+ val scope = rememberCoroutineScope()
+
+ var state by remember { mutableStateOf(TermuxTool.TermuxSetupState.from(tool.status())) }
+ var probing by remember { mutableStateOf(false) }
+ var probeFeedback by remember { mutableStateOf<String?>(null) }
+
+ // Re-read the cheap checks on every resume — a permission grant or a return from Termux
+ // changes them, and the screen cannot know without asking.
+ val lifecycleOwner = LocalLifecycleOwner.current
+ var resumeSignal by remember { mutableStateOf(0) }
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) resumeSignal++
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+ LaunchedEffect(resumeSignal) {
+ state = TermuxTool.TermuxSetupState.from(tool.status())
+ }
+
+ val permissionLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.RequestPermission()
+ ) { granted ->
+ state = TermuxTool.TermuxSetupState.from(tool.status())
+ overlay.show(
+ if (granted) {
+ "Permission granted — next, enable external apps in Termux."
+ } else {
+ "Permission denied. If no dialog appeared, Termux was installed after Gotcha — " +
+ "update or reinstall Gotcha so Android can grant it."
+ }
+ )
+ }
+
+ fun checkConfiguration() {
+ if (probing) return
+ probing = true
+ scope.launch {
+ val probe = tool.probeExternalApps()
+ state = state.copy(externalAppsEnabled = probe)
+ probeFeedback = when (probe) {
+ TermuxTool.TermuxConfigProbe.CONFIGURED ->
+ "Termux answered — allow-external-apps is enabled."
+ TermuxTool.TermuxConfigProbe.NOT_CONFIGURED ->
+ "Termux answered, but allow-external-apps is not enabled yet."
+ TermuxTool.TermuxConfigProbe.UNKNOWN ->
+ "Could not confirm. Open Termux once, set the property, then check again."
+ }
+ probing = false
+ }
+ }
+
+ SettingsScaffold(title = "Termux (Linux shell)", onBack = onBack, overlay = overlay) {
+ Text(
+ "Termux gives the assistant a full Linux shell — installing packages, running " +
+ "scripts and tools no phone ships with. This page walks you through the one-time " +
+ "setup so you don't have to look anything up.",
+ style = MaterialTheme.typography.bodySmall
+ )
+
+ SetupCheck(
+ title = "Install Termux",
+ done = state.installed,
+ detail = if (state.installed) {
+ "Termux ${state.versionName.orEmpty().trim()} is installed."
+ } else {
+ "Termux is not installed."
+ },
+ action = if (state.installed) {
+ null
+ } else {
+ SetupAction("Install Termux from F-Droid") {
+ runCatching {
+ context.startActivity(
+ Intent(Intent.ACTION_VIEW, Uri.parse(TermuxTool.TERMUX_FDROID_URL))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ )
+ }
+ }
+ }
+ )
+
+ SetupCheck(
+ title = "Check the Termux build",
+ done = state.pluginApiAvailable,
+ detail = when {
+ !state.installed -> "Install Termux first."
+ state.pluginApiAvailable -> "This build exposes the Run Commands API Gotcha needs."
+ else ->
+ "This build has no Run Commands API — that is the Google Play build, which " +
+ "removed it. Install the F-Droid or GitHub build instead."
+ }
+ )
+
+ SetupCheck(
+ title = "Grant the Run Commands permission",
+ done = state.permissionGranted,
+ detail = when {
+ !state.installed -> "Install Termux first."
+ state.permissionGranted -> "Gotcha may run commands in Termux."
+ else ->
+ "Termux must let Gotcha run commands. If no permission dialog appears, " +
+ "Termux was installed after Gotcha — update or reinstall Gotcha."
+ },
+ action = if (state.permissionGranted) {
+ null
+ } else {
+ SetupAction("Grant permission") {
+ permissionLauncher.launch(TermuxTool.PERMISSION_RUN_COMMAND)
+ }
+ }
+ )
+
+ SetupCheck(
+ title = "Allow external apps",
+ done = state.externalAppsEnabled == TermuxTool.TermuxConfigProbe.CONFIGURED,
+ detail = when {
+ !state.installed -> "Install Termux first."
+ !state.pluginApiAvailable -> "This build cannot run commands — see step 2."
+ state.externalAppsEnabled == TermuxTool.TermuxConfigProbe.CONFIGURED ->
+ "allow-external-apps is enabled — Gotcha can reach Termux."
+ state.externalAppsEnabled == TermuxTool.TermuxConfigProbe.NOT_CONFIGURED ->
+ "allow-external-apps is not enabled. Open Termux and run the two lines below."
+ else -> "Not confirmed yet. Open Termux, run the two lines below, then check again."
+ },
+ action = if (state.installed) {
+ SetupAction("Open Termux") {
+ openSpecialAccess(context, ToolResult.TERMUX_ACCESS, context.packageName)
+ }
+ } else {
+ null
+ }
+ )
+
+ if (state.installed && state.pluginApiAvailable && !state.ready) {
+ Surface(
+ shape = MaterialTheme.shapes.medium,
+ color = MaterialTheme.colorScheme.surfaceVariant,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ "echo 'allow-external-apps=true' >> ~/.termux/termux.properties\n" +
+ "termux-reload-settings",
+ style = MaterialTheme.typography.bodySmall.copy(fontFamily = GotchaMono),
+ modifier = Modifier.padding(12.dp)
+ )
+ }
+ OutlinedButton(
+ onClick = { checkConfiguration() },
+ enabled = !probing,
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (probing) "Checking…" else "Check configuration") }
+ }
+
+ probeFeedback?.let { feedback ->
+ Text(feedback, style = MaterialTheme.typography.bodySmall)
+ }
+
+ if (state.ready) {
+ Surface(
+ shape = MaterialTheme.shapes.medium,
+ color = MaterialTheme.colorScheme.primaryContainer,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ "Termux is set up. Try asking the assistant to run a command in Termux.",
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium,
+ modifier = Modifier.padding(12.dp)
+ )
+ }
+ }
+ }
+}
+
+/** A named action for a setup step, kept small so the checklist reads top-down. */
+private data class SetupAction(val label: String, val onClick: () -> Unit)
+
+/**
+ * One row of the checklist: a ✓/○ status marker, title, detail line, and an
+ * optional action button that is only offered while the step is incomplete.
+ */
+@Composable
+private fun SetupCheck(
+ title: String,
+ done: Boolean,
+ detail: String,
+ action: SetupAction? = null
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ text = if (done) "✓" else "○",
+ color = if (done) {
+ MaterialTheme.colorScheme.primary
+ } else {
+ MaterialTheme.colorScheme.onSurfaceVariant
+ },
+ style = MaterialTheme.typography.bodyMedium
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(
+ title,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium
+ )
+ }
+ Text(
+ detail,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ if (action != null) {
+ Button(onClick = action.onClick, modifier = Modifier.fillMaxWidth()) {
+ Text(action.label)
+ }
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
index 340ccf0..4f96e91 100644
--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
@@ -478,6 +478,72 @@ class TermuxToolTest {
assertTrue(result.message.contains("exit code: -1"))
}
+ // ---- allow-external-apps probe ----
+
+ @Test
+ fun `a success classifies the probe as configured`() {
+ val result = tool.formatResult(
+ resultBundle(exitCode = 0).apply { putInt(TermuxTool.RESULT_ERR, TermuxTool.ERRNO_SUCCESS) }
+ )
+
+ assertEquals(TermuxTool.TermuxConfigProbe.CONFIGURED, tool.classifyProbe(result))
+ }
+
+ @Test
+ fun `an errno naming allow-external-apps classifies as not configured`() {
+ // The bundle Termux sends when the property is unset; the message must survive into
+ // the probe decision, exactly as it survives formatResult.
+ val result = tool.formatResult(
+ Bundle().apply {
+ putInt(TermuxTool.RESULT_ERR, 2)
+ putString(
+ TermuxTool.RESULT_ERRMSG,
+ "RunCommandService requires `allow-external-apps` property to be set to `true`"
+ )
+ }
+ )
+
+ assertEquals(TermuxTool.TermuxConfigProbe.NOT_CONFIGURED, tool.classifyProbe(result))
+ }
+
+ @Test
+ fun `a missing permission is unknown, not not-configured`() {
+ // TermuxMessages.permissionNeeded mentions allow-external-apps too, but it is a guard
+ // path — we never got a real answer — so it must read as UNKNOWN, not NOT_CONFIGURED.
+ assertEquals(
+ TermuxTool.TermuxConfigProbe.UNKNOWN,
+ tool.classifyProbe(TermuxMessages.permissionNeeded())
+ )
+ }
+
+ @Test
+ fun `a generic failure is unknown`() {
+ assertEquals(
+ TermuxTool.TermuxConfigProbe.UNKNOWN,
+ tool.classifyProbe(ToolResult.error("some unrelated failure"))
+ )
+ }
+
+ @Test
+ fun `probe reports unknown when termux is absent`() = runTest {
+ assertEquals(TermuxTool.TermuxConfigProbe.UNKNOWN, tool.probeExternalApps())
+ }
+
+ @Test
+ fun `probe reports unknown before the permission is granted`() = runTest {
+ installTermux()
+
+ assertEquals(TermuxTool.TermuxConfigProbe.UNKNOWN, tool.probeExternalApps())
+ }
+
+ @Test
+ fun `probe reports unknown when termux never answers`() = runTest {
+ installTermux()
+ grantRunCommand()
+ // No real Termux answers the PendingIntent, so the probe hits its timeout.
+ assertEquals(TermuxTool.TermuxConfigProbe.UNKNOWN, tool.probeExternalApps())
+ }
+
// ---- receiver hand-off ----
@Test
diff --git a/docs/termux-setup.md b/docs/termux-setup.md
new file mode 100644
index 0000000..998a003
--- /dev/null
+++ b/docs/termux-setup.md
@@ -0,0 +1,71 @@
+# Termux
+
+Termux gives the assistant a full Linux user-space — `pkg`/`apt`, Python, and the
+long tail of tools no phone ships with. Gotcha talks to it through Termux's official
+`RUN_COMMAND` plugin API: a command is sent, Termux runs it in the background (no
+terminal pops up), and returns stdout/stderr/exit code.
+
+The assistant reads the status every turn (`TermuxStatus`) and the **Settings →
+Termux (Linux shell)** page is the guided setup that makes it work.
+
+## What has to be true
+
+Four things, in order. The Settings page shows each as a checklist item with an
+action button.
+
+1. **Termux is installed** — from the **F-Droid** or **GitHub** build. The Google
+ Play build is unmaintained and strips the entire RUN_COMMAND API, so it can never
+ work with Gotcha — the page calls that out rather than asking for a permission
+ that cannot exist.
+2. **The build exposes the Run Commands API** — true for F-Droid/GitHub builds,
+ false for the Play build.
+3. **The Run Commands permission is granted** — `com.termux.permission.RUN_COMMAND`,
+ a dangerous permission Termux itself declares. The page's "Grant permission"
+ button requests it. Caveat: if Termux was installed *after* Gotcha, Android may
+ not be able to grant it until Gotcha is updated or reinstalled.
+4. **`allow-external-apps=true`** — set in `~/.termux/termux.properties`. The file
+ lives in Termux's private storage, so Gotcha cannot read it; the page probes it
+ by running a trivial command (`echo gotcha-probe`):
+ - with the property set → the command succeeds → **configured**;
+ - with it unset → Termux answers an errno naming the property → **not configured**;
+ - permission missing, Termux stopped, or no answer at all → **unknown**.
+
+## Guided setup (Settings → Termux)
+
+Open **Settings → Termux (Linux shell)**. It re-reads the first three checks on
+every resume and offers:
+
+- **Install Termux from F-Droid** when Termux is missing.
+- **Grant permission** when the RUN_COMMAND grant is missing.
+- **Open Termux** plus copy-paste lines when `allow-external-apps` is not confirmed:
+ ```
+ echo 'allow-external-apps=true' >> ~/.termux/termux.properties
+ termux-reload-settings
+ ```
+- **Check configuration** re-runs the probe and reports configured / not-configured /
+ unknown.
+
+The Settings → Permissions → *Termux Commands (Optional)* row links to the same page.
+
+## Tools
+
+| Tool | Use for |
+|---|---|
+| `run_termux_command(command, workdir, timeout_seconds, stdin)` | Run a shell command in Termux's user-space. `run_command` is the unprivileged shell inside Gotcha's own sandbox; Termux is the full one. |
+
+## Manual end-to-end check
+
+1. **No Termux**: open Settings → Termux → "Install Termux" step is unchecked, the
+ F-Droid button is present; "Check configuration" is not offered.
+2. **Install the F-Droid build**: the page now shows the version under step 1 and the
+ Run Commands permission step becomes actionable.
+3. **Play build**: the build step is red with the "Google Play build" message, and no
+ permission button appears.
+4. **Grant the permission**: the step ticks off; if no dialog appears, Termux was
+ installed after Gotcha (reinstall Gotcha).
+5. **Open Termux**, run the two copy-paste lines, restart Termux, tap **Check
+ configuration** → "Termux answered — allow-external-apps is enabled."
+6. All four steps are checked and the "Termux is set up" banner shows. Ask the
+ assistant to run something: `pkg install python -y` and `python3 --version`.
+7. Revoke the permission in system Settings → the page's permission step unchecks on
+ the next resume.