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: automatically wrap pkg commands with wake-locks and non-interactive flags, and improve dpkg lock detection logic.
Gotcha Contributord1bb27ef6690
diff --git a/app/src/main/assets/skills/termux_background.json b/app/src/main/assets/skills/termux_background.jsonindex 83cd00e..5d7896a 100644--- a/app/src/main/assets/skills/termux_background.json+++ b/app/src/main/assets/skills/termux_background.json@@ -24,7 +24,10 @@"exit 100","stuck","waiting",- "taking long"+ "taking long",+ "conffile",+ "dpkg --configure",+ "prompt"],- "instructions": "1. A foreground process started by run_termux_command is bound to the lifecycle of that one call. The moment Gotcha returns from awaited completion, the process is orphaned and at the mercy of Android's lmkd, Doze, and OEM battery managers.\n2. Persistence pattern (the safe one):\n - `nohup myserver > /sdcard/Download/myserver.log 2>&1 < /dev/null & echo $! > /sdcard/Download/myserver.pid; disown`\n - Then `exit 0` immediately so the call returns success.\n - Next call: read the pid with `cat /sdcard/Download/myserver.pid`, then `kill $(cat /sdcard/Download/myserver.pid)` to stop it.\n - The `< /dev/null` is mandatory — without it, the process inherits the pipe and gets a SIGPIPE the moment the wrapping shell exits.\n3. Wake lock: `termux-wake-lock` (Termux-side; auto-grants WAKE_LOCK on first use). `termux-wake-unlock` to release. Required for any task longer than ~30s that does not write its own progress to disk.\n4. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, runs fail with `Not allowed to start service` because Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n5. Doze / battery saver: long-running `npm install`, `cargo build`, `pip install -r requirements.txt`, or `pkg install` of a large package can be suspended mid-flight. There is no in-Termux workaround beyond asking the user to add Gotcha to the battery-saver whitelist in Android Settings.\n6. Do not promise scheduled tasks. termux-cron / termux-job-scheduler exist but run inside Termux's own alarms, which Android's job scheduler can throttle. They are best-effort, not real cron.\n7. What you CANNOT do in Termux: run a process as a system service (no systemd), have it auto-restart on boot, or have it survive `force-stop` of Termux. The model should not promise any of these.\n8. Health probe pattern: when waiting for a server to come up, prefer `until curl -sSf http://127.0.0.1:PORT/healthz >/dev/null 2>&1; do sleep 1; done` inside a single run_termux_command call, with a tight timeout, rather than polling from Gotcha.\n9. Process hygiene: before starting a new long-running service, check `ps -ef | grep <name>` and offer to kill the existing one via the notification-shade Exit — a run_termux_command cannot kill another call's process; only tapping Exit on the Termux notification (global_action or press_key 'notifications' + tap the Exit action, which ends every Termux session) reliably stops it. If you cannot reach Exit, ask the user to tap it. Do not try `pkill`, `fuser` or `dpkg --configure -a` via another run_termux_command to kill it — that will hang until timeout and not release the lock.\n9b. Wake-lock wrapping for long tasks: for any task >30s (pkg install of large package, npm/pip/cargo build), wrap with `termux-wake-lock && { <cmd>; } ; termux-wake-unlock` inside the same run_termux_command payload. This prevents Doze CPU throttling that turns a 30s task into a 10-minute hang.\n10. Consequence: when the assistive ball is on, Gotcha holds a foreground service that exempts it from the Android 12+ backgrounded-start restriction. Without the ball, the same call fails with the \"Not allowed to start service\" error.\n9c. A `pkg install` that times out keeps running under Termux's uid and holds the dpkg lock (the `lock-frontend` / `Could not get lock` shape). Never `rm` the lock files or `kill -9` the package manager; the only safe stop is the notification-shade Exit above. pkg-like commands are now wake-lock wrapped automatically, but still wrap long non-pkg tasks yourself."+ "instructions": "1. A foreground process started by run_termux_command is bound to the lifecycle of that one call. The moment Gotcha returns from awaited completion, the process is orphaned and at the mercy of Android's lmkd, Doze, and OEM battery managers.\n2. Persistence pattern (the safe one):\n - `nohup myserver > /sdcard/Download/myserver.log 2>&1 < /dev/null & echo $! > /sdcard/Download/myserver.pid; disown`\n - Then `exit 0` immediately so the call returns success.\n - Next call: read the pid with `cat /sdcard/Download/myserver.pid`, then `kill $(cat /sdcard/Download/myserver.pid)` to stop it.\n - The `< /dev/null` is mandatory — without it, the process inherits the pipe and gets a SIGPIPE the moment the wrapping shell exits.\n3. Wake lock: `termux-wake-lock` (Termux-side; auto-grants WAKE_LOCK on first use). `termux-wake-unlock` to release. Required for any task longer than ~30s that does not write its own progress to disk.\n4. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, runs fail with `Not allowed to start service` because Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n5. Doze / battery saver: long-running `npm install`, `cargo build`, `pip install -r requirements.txt`, or `pkg install` of a large package can be suspended mid-flight. There is no in-Termux workaround beyond asking the user to add Gotcha to the battery-saver whitelist in Android Settings.\n6. Do not promise scheduled tasks. termux-cron / termux-job-scheduler exist but run inside Termux's own alarms, which Android's job scheduler can throttle. They are best-effort, not real cron.\n7. What you CANNOT do in Termux: run a process as a system service (no systemd), have it auto-restart on boot, or have it survive `force-stop` of Termux. The model should not promise any of these.\n8. Health probe pattern: when waiting for a server to come up, prefer `until curl -sSf http://127.0.0.1:PORT/healthz >/dev/null 2>&1; do sleep 1; done` inside a single run_termux_command call, with a tight timeout, rather than polling from Gotcha.\n9. Process hygiene: before starting a new long-running service, check `ps -ef | grep <name>` and offer to kill the existing one via the notification-shade Exit — a run_termux_command cannot kill another call's process; only tapping Exit on the Termux notification (global_action or press_key 'notifications' + tap the Exit action, which ends every Termux session) reliably stops it. If you cannot reach Exit, ask the user to tap it. Do not try `pkill`, `fuser` or `dpkg --configure -a` via another run_termux_command to kill it — that will hang until timeout and not release the lock.\n9b. Wake-lock wrapping for long tasks: for any task >30s (pkg install of large package, npm/pip/cargo build), wrap with `termux-wake-lock && { <cmd>; } ; termux-wake-unlock` inside the same run_termux_command payload. This prevents Doze CPU throttling that turns a 30s task into a 10-minute hang.\n10. Consequence: when the assistive ball is on, Gotcha holds a foreground service that exempts it from the Android 12+ backgrounded-start restriction. Without the ball, the same call fails with the \"Not allowed to start service\" error.\n9c. A `pkg install` that times out keeps running under Termux's uid and holds the dpkg lock (the `lock-frontend` / `Could not get lock` shape). Never `rm` the lock files or `kill -9` the package manager; the only safe stop is the notification-shade Exit above. pkg-like commands are now wake-lock wrapped automatically, but still wrap long non-pkg tasks yourself.\n9d. A `dpkg --configure` on a half-configured package is the same long-task class as a pkg install and is now run non-interactively, but a conffile it cannot answer (Configuration file ... Y/I/N/O/D/Z) is why it stalls holding the dpkg lock. If you must run it, supply the answer through the stdin param (`echo N | dpkg --configure <pkg>`) — the notification-shade Exit is the only stop if it ever hangs."}diff --git a/app/src/main/assets/skills/termux_operations.json b/app/src/main/assets/skills/termux_operations.jsonindex efcf5fc..6ea514f 100644--- a/app/src/main/assets/skills/termux_operations.json+++ b/app/src/main/assets/skills/termux_operations.json@@ -22,7 +22,11 @@"exit 100","stuck","waiting",- "taking long"+ "taking long",+ "conffile",+ "configuration file",+ "prompt",+ "noninteractive"],- "instructions": "1. run_termux_command runs under Termux's UID, not Gotcha's. Gotcha's working directory is invisible to Termux, and Termux's home is invisible to Gotcha. The only cross-uid bridge is /sdcard/Download (after `termux-setup-storage` has been run in Termux once).\n2. Each call is a fresh /bin/sh -c. `cd`, `export`, activated virtualenvs, and `source` do NOT carry over. Chain dependent steps with `&&` in one command, never split across calls.\n3. There is no interactive terminal. Anything that waits for typed input (pkg install without -y, ssh password prompt, read, mysql>) blocks until the 600s timeout. Always pass -y / --yes / -q where the tool supports them. Prefer quiet flags for installs (pkg install -y -q, pip install -q, git clone --depth 1 -q) to stay under the output cap and speed up inference.\n4. Output is capped at 32KB by Gotcha and ~100KB by Termux. For larger output, redirect inside Termux to $TMPDIR (e.g. `cmd > $TMPDIR/build.log 2>&1 || tail -n 40 $TMPDIR/build.log`) and only surface the tail; for payloads <100KB prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the stdin param) over write_file to /sdcard/Download which goes through FUSE. Use /sdcard/Download only when a file must persist across calls or termux-setup-storage is missing.\n5. You cannot kill a command after submission. A timed-out command keeps running under Termux's UID. Before launching anything long, warn the user and check existing processes with `ps -ef` before starting a new one.\n6. Hard ceiling: timeout_seconds <= 600; adaptive default is 120s (300s for pkg/apt/pip/npm/cargo/proot-distro when no timeout_seconds is passed). `pkg install` of ffmpeg, chromium, rust, golang, or texlive can still hit this. If it does, split into smaller packages or warn the user.\n7. Concurrency cap: 4 commands in flight, process-wide. Sub-agents share the same semaphore. A 5th call returns an error.\n8. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, run_termux_command fails with \"Not allowed to start service\" — Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n9. The Play-Store build of Termux has no RUN_COMMAND API and can never work. Only F-Droid or GitHub builds are usable.\n10. The four setup steps are: install Termux from F-Droid, confirm the build exposes Run Commands API, grant com.termux.permission.RUN_COMMAND, and set `allow-external-apps=true` in ~/.termux/termux.properties. Walk the user through Settings -> Termux (Linux shell) if any check fails.\n11. Package-lock contention: an `exit 100` naming `lock-frontend` / `Could not get lock` / `held by process <pid>` means ANOTHER pkg/apt operation is already running and holds the package lock - NOT a mirror or network problem. Do NOT delete `$PREFIX/var/lib/dpkg/lock*` and do NOT `kill -9` the holder: that corrupts the package database and a run_termux_command cannot stop the process anyway. Check with `ps -ef | grep -E '[d]pkg|[a]pt'`; if it never finishes, open the notifications shade and tap Exit on the Termux notification (ends every session, releases the lock), then retry. For large installs that keep failing mid-flight, split the network step from the install step (`pkg download <pkg>` then `dpkg -i $PREFIX/var/cache/apt/archives/*.deb`) and wrap long tasks in `termux-wake-lock && { ...; }; termux-wake-unlock`."+ "instructions": "1. run_termux_command runs under Termux's UID, not Gotcha's. Gotcha's working directory is invisible to Termux, and Termux's home is invisible to Gotcha. The only cross-uid bridge is /sdcard/Download (after `termux-setup-storage` has been run in Termux once).\n2. Each call is a fresh /bin/sh -c. `cd`, `export`, activated virtualenvs, and `source` do NOT carry over. Chain dependent steps with `&&` in one command, never split across calls.\n3. There is no interactive terminal. Anything that waits for typed input (pkg install without -y, ssh password prompt, read, mysql>) blocks until the 600s timeout. Always pass -y / --yes / -q where the tool supports them. Prefer quiet flags for installs (pkg install -y -q, pip install -q, git clone --depth 1 -q) to stay under the output cap and speed up inference.\n4. Output is capped at 32KB by Gotcha and ~100KB by Termux. For larger output, redirect inside Termux to $TMPDIR (e.g. `cmd > $TMPDIR/build.log 2>&1 || tail -n 40 $TMPDIR/build.log`) and only surface the tail; for payloads <100KB prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the stdin param) over write_file to /sdcard/Download which goes through FUSE. Use /sdcard/Download only when a file must persist across calls or termux-setup-storage is missing.\n5. You cannot kill a command after submission. A timed-out command keeps running under Termux's UID. Before launching anything long, warn the user and check existing processes with `ps -ef` before starting a new one.\n6. Hard ceiling: timeout_seconds <= 600; adaptive default is 120s (300s for pkg/apt/pip/npm/cargo/proot-distro when no timeout_seconds is passed). `pkg install` of ffmpeg, chromium, rust, golang, or texlive can still hit this. If it does, split into smaller packages or warn the user.\n7. Concurrency cap: 4 commands in flight, process-wide. Sub-agents share the same semaphore. A 5th call returns an error.\n8. Android 12+ background restriction: if Gotcha is in the background and the assistive ball is off, run_termux_command fails with \"Not allowed to start service\" — Termux exposes a foreground service. Tell the user to bring Gotcha to the foreground (or switch the assistive ball on).\n9. The Play-Store build of Termux has no RUN_COMMAND API and can never work. Only F-Droid or GitHub builds are usable.\n10. The four setup steps are: install Termux from F-Droid, confirm the build exposes Run Commands API, grant com.termux.permission.RUN_COMMAND, and set `allow-external-apps=true` in ~/.termux/termux.properties. Walk the user through Settings -> Termux (Linux shell) if any check fails.\n11. Package-lock contention: an `exit 100` naming `lock-frontend` / `Could not get lock` / `held by process <pid>` means ANOTHER pkg/apt operation is already running and holds the package lock - NOT a mirror or network problem. Do NOT delete `$PREFIX/var/lib/dpkg/lock*` and do NOT `kill -9` the holder: that corrupts the package database and a run_termux_command cannot stop the process anyway. Check with `ps -ef | grep -E '[d]pkg|[a]pt'`; if it never finishes, open the notifications shade and tap Exit on the Termux notification (ends every session, releases the lock), then retry. For large installs that keep failing mid-flight, split the network step from the install step (`pkg download <pkg>` then `dpkg -i $PREFIX/var/cache/apt/archives/*.deb`) and wrap long tasks in `termux-wake-lock && { ...; }; termux-wake-unlock`.\n12. Interactive dpkg/apt prompts: if output shows `Configuration file '...'` with `Y/I/N/O/D/Z [default=N] ?`, a package manager is waiting for an answer that can never arrive — there is no terminal here, and it will block until the timeout. You cannot retype this away; avoid it by running package operations through the defaults Gotcha already applies (`DEBIAN_FRONTEND=noninteractive`, keep the current config). If a bare `dpkg --configure` still prompts, pipe the answer via the stdin param: `echo N | dpkg --configure <pkg>`."}diff --git a/app/src/main/assets/skills/termux_repositories.json b/app/src/main/assets/skills/termux_repositories.jsonindex 56bb742..dff4b33 100644--- a/app/src/main/assets/skills/termux_repositories.json+++ b/app/src/main/assets/skills/termux_repositories.json@@ -19,7 +19,12 @@"termux-change-repo","lock","exit 100",- "waiting"+ "waiting",+ "can't link",+ "link",+ "libc++",+ "libplacebo",+ "symbol"],- "instructions": "1. The default Termux mirror (https://packages.termux.dev) is often slow or blocked on networks in China, parts of India, behind corporate firewalls, and on some ISPs. Symptom: `pkg install` hangs at \"0% [Connecting to packages.termux.dev]\" or fails with \"Could not resolve host\" / \"NO_PUBKEY\" / repeated 404s.\n2. To switch mirrors interactively, the user must run `termux-change-repo` INSIDE Termux (it opens a TUI picker). Gotcha cannot drive that TUI from run_termux_command. Tell the user to open Termux, run the command, pick a mirror, and not return to chat until done.\n3. To switch non-interactively from a script, overwrite TWO files:\n - `$PREFIX/etc/apt/sources.list` with: `deb <mirror> termux-main`\n - `$PREFIX/etc/apt/sources.list.d/root.list` with: `deb <mirror> termux-root`\n Then run `apt-get update -y`. `<PREFIX>` is `/data/data/com.termux/files/usr`.\n\n3b. Fast non-interactive switch (when user wants Gotcha to fix mirror without opening Termux TUI):\n `sed -i 's|https://packages.termux.dev/apt/termux-main|https://termux.mentality.org/apt/termux-main|g' $PREFIX/etc/apt/sources.list && sed -i 's|https://packages.termux.dev/apt/termux-root|https://termux.mentality.org/apt/termux-root|g' $PREFIX/etc/apt/sources.list.d/root.list && apt-get update -y`\n Verify with `pkg update -y`. Note: this fast sed only works if the current mirror is still packages.termux.dev; otherwise overwrite the two files as in step 3.\n3c. APT speed tuning (optional, safe):\n `echo 'Acquire::Languages \"none\";' > $PREFIX/etc/apt/apt.conf.d/00nolanguages && echo 'APT::Install-Recommends \"0\";' > $PREFIX/etc/apt/apt.conf.d/00norecommends`\n Reduces apt update download size and time.\n\n4. Known mirrors (substitute the user's geography):\n - Official primary: https://packages.termux.dev/apt/termux-main\n - Official secondary: https://termux.mentality.org/apt/termux-main\n - Tsinghua (China): https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-main\n - USTC (China): https://mirrors.ustc.edu.cn/termux/apt/termux-main\n - ISCAS (China): https://mirror.iscas.ac.cn/termux/apt/termux-main\n - CERN (China): https://mirrors.cernet.edu.cn/termux/apt/termux-main\n - NJU (China): https://mirror.nju.edu.cn/termux/apt/termux-main\n - Netherlands: https://ftp.snt.utwente.nl/termux/apt/termux-main\n5. After a mirror change, ALWAYS run `pkg update -y` to verify the new server. A `NO_PUBKEY` error means the mirror is missing the signing key — fall back to the official primary.\n6. Large packages — ffmpeg, python, rust, chromium, golang, nodejs-lts, texlive, qt — typically take 5-15 minutes to install even on a fast mirror. Always raise timeout_seconds to 600 and warn the user before kicking one off.\n7. If `pkg install` keeps failing midway, split the network step from the install step: `pkg download <pkg>` puts the .deb in $PREFIX/var/cache/apt/archives/; then `cd $PREFIX/var/cache/apt/archives && dpkg -i *.deb` installs from local cache. This is also useful for retrying a single bad package.\n8. For reproducible installs across mirrors, prefer `pkg install -y` over `apt install`; `pkg` is the wrapper that handles Termux-specific package names and dependencies and is the supported interface.\n9. Triage before switching anything: `exit 100` with `Could not get lock` / `lock-frontend` / `held by process` is package-lock contention from a running pkg/apt - wait, or tap Exit on the Termux notification; never `rm` the lock files or `kill -9` the holder. Only switch mirrors for network symptoms: a hang at `0% [Connecting to packages.termux.dev]`, `Could not resolve host`, `NO_PUBKEY`, or repeated 404s."+ "instructions": "1. The default Termux mirror (https://packages.termux.dev) is often slow or blocked on networks in China, parts of India, behind corporate firewalls, and on some ISPs. Symptom: `pkg install` hangs at \"0% [Connecting to packages.termux.dev]\" or fails with \"Could not resolve host\" / \"NO_PUBKEY\" / repeated 404s.\n2. To switch mirrors interactively, the user must run `termux-change-repo` INSIDE Termux (it opens a TUI picker). Gotcha cannot drive that TUI from run_termux_command. Tell the user to open Termux, run the command, pick a mirror, and not return to chat until done.\n3. To switch non-interactively from a script, overwrite TWO files:\n - `$PREFIX/etc/apt/sources.list` with: `deb <mirror> termux-main`\n - `$PREFIX/etc/apt/sources.list.d/root.list` with: `deb <mirror> termux-root`\n Then run `apt-get update -y`. `<PREFIX>` is `/data/data/com.termux/files/usr`.\n\n3b. Fast non-interactive switch (when user wants Gotcha to fix mirror without opening Termux TUI):\n `sed -i 's|https://packages.termux.dev/apt/termux-main|https://termux.mentality.org/apt/termux-main|g' $PREFIX/etc/apt/sources.list && sed -i 's|https://packages.termux.dev/apt/termux-root|https://termux.mentality.org/apt/termux-root|g' $PREFIX/etc/apt/sources.list.d/root.list && apt-get update -y`\n Verify with `pkg update -y`. Note: this fast sed only works if the current mirror is still packages.termux.dev; otherwise overwrite the two files as in step 3.\n3c. APT speed tuning (optional, safe):\n `echo 'Acquire::Languages \"none\";' > $PREFIX/etc/apt/apt.conf.d/00nolanguages && echo 'APT::Install-Recommends \"0\";' > $PREFIX/etc/apt/apt.conf.d/00norecommends`\n Reduces apt update download size and time.\n\n4. Known mirrors (substitute the user's geography):\n - Official primary: https://packages.termux.dev/apt/termux-main\n - Official secondary: https://termux.mentality.org/apt/termux-main\n - Tsinghua (China): https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-main\n - USTC (China): https://mirrors.ustc.edu.cn/termux/apt/termux-main\n - ISCAS (China): https://mirror.iscas.ac.cn/termux/apt/termux-main\n - CERN (China): https://mirrors.cernet.edu.cn/termux/apt/termux-main\n - NJU (China): https://mirror.nju.edu.cn/termux/apt/termux-main\n - Netherlands: https://ftp.snt.utwente.nl/termux/apt/termux-main\n5. After a mirror change, ALWAYS run `pkg update -y` to verify the new server. A `NO_PUBKEY` error means the mirror is missing the signing key — fall back to the official primary.\n6. Large packages — ffmpeg, python, rust, chromium, golang, nodejs-lts, texlive, qt — typically take 5-15 minutes to install even on a fast mirror. Always raise timeout_seconds to 600 and warn the user before kicking one off.\n7. If `pkg install` keeps failing midway, split the network step from the install step: `pkg download <pkg>` puts the .deb in $PREFIX/var/cache/apt/archives/; then `cd $PREFIX/var/cache/apt/archives && dpkg -i *.deb` installs from local cache. This is also useful for retrying a single bad package.\n8. For reproducible installs across mirrors, prefer `pkg install -y` over `apt install`; `pkg` is the wrapper that handles Termux-specific package names and dependencies and is the supported interface.\n9. Triage before switching anything: `exit 100` with `Could not get lock` / `lock-frontend` / `held by process` is package-lock contention from a running pkg/apt - wait, or tap Exit on the Termux notification; never `rm` the lock files or `kill -9` the holder. Only switch mirrors for network symptoms: a hang at `0% [Connecting to packages.termux.dev]`, `Could not resolve host`, `NO_PUBKEY`, or repeated 404s.\n10. ffmpeg installs that link-fail: `CANNOT LINK EXECUTABLE \"ffmpeg\": cannot locate symbol _ZNSt6__ndk127__from_chars_floating_point... referenced by libplacebo.so` means the installed libplacebo was built against a newer libc++ than the one on the device (here libc++ 27c vs 29). The fix is a TARGETED upgrade, not the wiki's blanket 'pkg upgrade': `apt-get install -y libc++` (a small package, ~86 kB) which reconfigures ffmpeg automatically. Only if that does not clear it should you fall back to `pkg upgrade -y` (heavy, 70+ packages, and it re-asks conffile questions that have no terminal to answer them). See the termux-packages wiki dynamic-library-linking-errors for background."}diff --git a/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt b/app/src/main/java/com/gotcha/tools/MediaConvertTool.ktindex 915bc6f..c82fe85 100644--- a/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt@@ -230,6 +230,16 @@ class MediaConvertTool(val text = result.messageval detail = text.substringAfter("stderr:", "").trim().ifEmpty { text }return when {+ text.contains("CANNOT LINK EXECUTABLE", ignoreCase = true) ||+ text.contains("cannot locate symbol", ignoreCase = true) -> ToolResult.error(+ "Termux's ffmpeg is installed but links against out-of-date libraries — the usual case is " ++ "a libplacebo that needs a newer libc++ (the error names " ++ "_ZNSt6__ndk127__from_chars_floating_point... referenced by libplacebo.so). Fix it with " ++ "a targeted upgrade, NOT a full 'pkg upgrade' (which is heavy and re-asks conffile " ++ "questions): run 'apt-get install -y libc++' — a small package that reconfigures ffmpeg " ++ "automatically. If that does not clear it, then run 'pkg upgrade -y'. Never delete the " ++ "lock files or kill -9 dpkg."+ )text.contains("not found", ignoreCase = true) -> ToolResult.error("Termux has no ffmpeg installed, which is what does the conversion. Install it with " +"'pkg install ffmpeg -y' (a large download — 5-15 minutes, so warn the user and use " +diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.ktindex 5147b88..207239f 100644--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt@@ -272,11 +272,17 @@ class TermuxTool(}if (errmsg.isNotEmpty()) append("\nTermux note: ${cap(errmsg)}")}- // apt/dpkg lock contention (exit 100 "Could not get lock ... lock-frontend held by process N")- // needs a different recovery than a plain failed command: wait, or tap Exit on the Termux+ // apt/dpkg lock contention ("Could not get lock ... lock-frontend held by process N") needs+ // a different recovery than a plain failed command: wait, or tap Exit on the Termux// notification — never delete the lock files or kill the holder. Recognised here so the// model is told what actually fixes it instead of reading a raw apt error.- if (exit != 0 && LOCK_SIGNATURE.containsMatchIn(message)) {+ //+ // Deliberately NOT gated on `exit != 0`: a pipeline like `apt-get ... | tail` or+ // `apt list --upgradable` masks apt's failure behind a successful tail/echo, so the lock+ // error appears in the output while the reported exit code is 0. The signature below is the+ // failing-phrase set only ("Could not get lock" / "Unable to acquire ..."), so listing the+ // lock files with `ls $PREFIX/var/lib/dpkg/lock*` cannot false-positive on the filename.+ if (LOCK_SIGNATURE.containsMatchIn(message)) {return TermuxMessages.lockHeld(HOLDER_PID.find(message)?.groupValues?.get(1))}return ToolResult(success = exit == 0, message = message)@@ -438,14 +444,17 @@ class TermuxTool(internal const val ERRNO_FAILED = 2 // Activity.RESULT_FIRST_USER + 1/** Package-manager commands that are inherently slow and benefit from a larger default timeout. */- private val PKG_LIKE_REGEX = Regex("""\b(pkg|apt|apt-get|pip3?|npm|cargo|proot-distro)\b""")+ private val PKG_LIKE_REGEX = Regex("""\b(pkg|apt|apt-get|dpkg|pip3?|npm|cargo|proot-distro)\b""")/**- * The apt/dpkg lock-contention signature, as a quick `exit 100` with "Could not get lock".- * Recognised before the raw output reaches the model so it is told the real remedy.+ * The apt/dpkg lock-contention signature: the *failure* phrases apt prints when it cannot+ * take the lock. Kept to failure text on purpose — bare "lock-frontend" or "cache lock"+ * would match `ls $PREFIX/var/lib/dpkg/lock*` output and mislead the model. Matched against+ * the whole result (stdout+stderr), not just the exit code, because pipelines such as+ * `apt-get ... | tail` report exit 0 while the lock failure is sitting in the output.*/private val LOCK_SIGNATURE = Regex(- """(?:lock-frontend|Could not get lock|cache lock|Unable to acquire the dpkg frontend lock)""",+ """(?:Could not get lock|Unable to acquire the dpkg frontend lock|dpkg frontend lock was locked by another process)""",RegexOption.IGNORE_CASE)@@ -456,6 +465,13 @@ class TermuxTool(private const val WAKE_LOCK = "termux-wake-lock"private const val WAKE_UNLOCK = "termux-wake-unlock"+ /**+ * The Debian frontend env var that tells dpkg/apt to take default actions instead of asking+ * conffile questions. It is safe for every package-manager command and skipped when the user+ * already set it explicitly.+ */+ private const val DEBIAN_FRONTEND = "DEBIAN_FRONTEND"+/** Shell separators the deny-list splits on before matching each part. */private val SEGMENT_SEPARATORS = Regex("""[;&|\n]+""")@@ -476,13 +492,25 @@ class TermuxTool(internal const val MAX_CONCURRENT_FOR_TEST = MAX_CONCURRENT_COMMANDS/**- * The command actually sent to Termux: the user's text, wrapped in a wake-lock when it is a- * package-manager operation. Doze and OEM battery savers throttle a backgrounded `pkg install`- * mid-download, which is how a 30-second install turns into a 10-minute hang — the exact shape- * of the ffmpeg failure this guard targets.+ * The command actually sent to Termux: the user's text, made non-interactive for+ * package-manager operations (dpkg/apt conffile prompts would otherwise block on a TTY that+ * does not exist) and wrapped in a wake-lock so Doze cannot throttle the download. The+ * exact shape of the ffmpeg failure this guard targets: a `pkg upgrade` silently re-asking+ * `openssl.cnf` and a 30-second install turning into a 10-minute hang.+ */+ internal fun commandToRun(trimmed: String): String {+ if (!PKG_LIKE_REGEX.containsMatchIn(trimmed)) return trimmed+ return withWakeLock(withNonInteractive(trimmed))+ }++ /**+ * Prefixes [command] with `DEBIAN_FRONTEND=noninteractive` unless one is already present.+ * apt/dpkg conffile questions ("Configuration file ... Y/I/N/O/D/Z") have no TTY to read+ * the answer from and would block until the timeout; the non-interactive frontend takes the+ * default action (keep the current version), which is what the user's own edit implies.*/- internal fun commandToRun(trimmed: String): String =- if (PKG_LIKE_REGEX.containsMatchIn(trimmed)) withWakeLock(trimmed) else trimmed+ internal fun withNonInteractive(command: String): String =+ if (DEBIAN_FRONTEND in command) command else "$DEBIAN_FRONTEND=noninteractive $command"/*** Wraps [command] in `termux-wake-lock`/`termux-wake-unlock`, preserving its exit code (a naivediff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex efbaafe..cd368c2 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -2403,6 +2403,11 @@ object ToolDefinitions {"this is NOT a mirror problem. Wait for it or tap Exit on the Termux notification to end all " +"sessions; never delete the lock files or kill -9 the process, which corrupts the package " +"database without releasing the lock.\n" ++ "- Interactive prompts: if output shows `Configuration file '...'` with `Y/I/N/O/D/Z`, a " ++ "package manager is waiting for an answer no terminal can provide and will block until the " ++ "timeout. Package operations are run non-interactively by default; if a bare `dpkg " ++ "--configure` still asks, supply the answer via the stdin param (`echo N | dpkg --configure " ++ "<pkg>`).\n" +"- Hard ceiling: timeout_seconds <= 600. `pkg install` of ffmpeg, chromium, rust, golang, or " +"texlive can hit this — raise timeout_seconds to 600 and warn the user before starting one.\n" +"- 4 commands in flight, process-wide. Sub-agents share the same semaphore.\n" +diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.ktindex d429aa6..62d4585 100644--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt@@ -370,6 +370,45 @@ class TermuxToolTest {assertTrue(result.message.contains("Exit"))}+ @Test+ fun `a lock failure masked behind a successful pipe is still reported`() {+ // A pipeline like `apt-get ... | tail` or `apt list --upgradable` exits 0 while apt's lock+ // error sits in the output — the reported exit code cannot be trusted, so detection must+ // look at the message, not the code.+ val bundle = resultBundle(+ exitCode = 0,+ stdout = "Hit:1 https://ro.mirror.flokinet.net/termux/termux-main stable InRelease\n" ++ "Reading package lists...\n" ++ "E: Could not get lock /data/data/com.termux/files/usr/var/lib/dpkg/lock-frontend. " ++ "It is held by process 15138 (apt).\n" ++ "E: Unable to acquire the dpkg frontend lock, is another process using it?"+ )++ val result = tool.formatResult(bundle)++ assertFalse("a masked lock must still be a failure", result.success)+ assertTrue(result.message.contains("process 15138"))+ }++ @Test+ fun `listing the lock files does not read as lock contention`() {+ // `ls -l $PREFIX/var/lib/dpkg/lock*` prints filenames that contain "lock-frontend"; the+ // detector must match apt's failure phrases, not bare filenames, or every such listing+ // would be misreported as a held lock.+ val bundle = resultBundle(+ exitCode = 0,+ stdout = "-rw-------. 1 u0_a234 u0_a234 0 Aug 29 00:37 " ++ "/data/data/com.termux/files/usr/var/lib/dpkg/lock\n" ++ "-rw-------. 1 u0_a234 u0_a234 0 Aug 29 00:36 " ++ "/data/data/com.termux/files/usr/var/lib/dpkg/lock-frontend\n"+ )++ val result = tool.formatResult(bundle)++ assertTrue("a successful listing is not a lock failure", result.success)+ assertFalse(result.message.contains("Do NOT delete the lock files"))+ }+@Testfun `a non-lock failure is passed through unaltered`() {val bundle = resultBundle(exitCode = 127, stderr = "sh: nope: not found")@@ -394,11 +433,34 @@ class TermuxToolTest {assertTrue("an already-wrapped command is not double-wrapped", wrapped == TermuxTool.withWakeLock(wrapped))}+ @Test+ fun `pkg-like commands are made non-interactive and wake-locked`() {+ val run = TermuxTool.commandToRun("pkg install ffmpeg -y")++ assertTrue(+ "must silence conffile prompts",+ run.contains("DEBIAN_FRONTEND=noninteractive pkg install ffmpeg -y")+ )+ assertTrue("must still wake-lock", run.contains("termux-wake-lock"))+ }++ @Test+ fun `an explicit DEBIAN_FRONTEND is left untouched`() {+ val explicit = "DEBIAN_FRONTEND=interactive apt-get install -y libc++"+ assertEquals(explicit, TermuxTool.withNonInteractive(explicit))+ assertTrue(+ TermuxTool.withNonInteractive("apt-get install -y libc++")+ .startsWith("DEBIAN_FRONTEND=noninteractive")+ )+ }+@Testfun `a non-pkg command is not wake-lock wrapped`() {- // withWakeLock itself wraps anything; the package-manager gate lives in commandToRun.+ // withWakeLock/withNonInteractive themselves wrap anything; the package-manager gate lives in commandToRun.assertEquals("echo hello", TermuxTool.commandToRun("echo hello"))- assertTrue(TermuxTool.commandToRun("pkg install ffmpeg -y").contains("termux-wake-lock"))+ val run = TermuxTool.commandToRun("pkg install ffmpeg -y")+ assertTrue(run.contains("termux-wake-lock"))+ assertTrue(run.contains("DEBIAN_FRONTEND=noninteractive"))}@Testdiff --git a/docs/termux-setup.md b/docs/termux-setup.mdindex cac4fb1..981e0e1 100644--- a/docs/termux-setup.md+++ b/docs/termux-setup.md@@ -110,6 +110,20 @@ in order of how often they bite:package (`/data/user/<id>/com.termux/files/usr` under a work profile);commands should use `$PREFIX` rather than a hardcoded `/data/data/...`prefix.+- **Interactive `dpkg` prompts.** A package manager stuck at+ `Configuration file '...' ... Y/I/N/O/D/Z [default=N] ?` is waiting for an+ answer no terminal can provide and blocks until the timeout. Gotcha runs+ package operations non-interactively (`DEBIAN_FRONTEND=noninteractive`, keep+ the current config) so this should not appear; if a bare `dpkg --configure`+ still asks, answer it through the tool's `stdin` param+ (`echo N | dpkg --configure <pkg>`).+- **ffmpeg link error (`libplacebo` / `libc++`).** If `ffmpeg` prints+ `CANNOT LINK EXECUTABLE ... cannot locate symbol ... referenced by+ libplacebo.so`, a freshly installed `libplacebo` was built against a newer+ `libc++` than the device has. Fix it with the targeted+ `apt-get install -y libc++` (a small package that reconfigures `ffmpeg`+ itself) rather than the heavy `pkg upgrade`, which re-asks the conffile+ questions above.- **4 commands in flight, process-wide.** Sub-agents share the samesemaphore. A 5th call returns an error.- **Android 12+ background restriction.** If Gotcha is in the background