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 safety guards against destructive package manager lock removal and introduce wake-lock support for long-running Termux tasks.

Gotcha Contributor2c77b05c97d2
diff --git a/app/src/main/assets/skills/termux_background.json b/app/src/main/assets/skills/termux_background.json
index 626d760..83cd00e 100644
--- a/app/src/main/assets/skills/termux_background.json
+++ b/app/src/main/assets/skills/termux_background.json
@@ -18,7 +18,13 @@
"long",
"running",
"disown",
- "service"
+ "service",
+ "lock",
+ "dpkg",
+ "exit 100",
+ "stuck",
+ "waiting",
+ "taking long"
],
- "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 \u2014 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 \u2014 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 \u2014 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."
-}
\ No newline at end of file
+ "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."
+}
diff --git a/app/src/main/assets/skills/termux_filesystem.json b/app/src/main/assets/skills/termux_filesystem.json
index 7a59809..8f5c181 100644
--- a/app/src/main/assets/skills/termux_filesystem.json
+++ b/app/src/main/assets/skills/termux_filesystem.json
@@ -18,7 +18,10 @@
"home",
"directory",
"upload",
- "download"
+ "download",
+ "profile",
+ "secondary user",
+ "prefix"
],
- "instructions": "Three filesystem worlds \u2014 keep them separate:\n1. Gotcha's working dir (default cwd for `run_command`, `read_file`, `write_file`, `edit`, `glob`, `grep`): `/storage/emulated/0/Gotcha/chats/<slug_id>/`. INVISIBLE to Termux (different UID).\n2. Termux's home (default `working_dir` for `run_termux_command`): `/data/data/com.termux/files/home`. INVISIBLE to Gotcha.\n3. Shared storage: `/storage/emulated/0/Download`, `/storage/emulated/0/Pictures`, `/storage/emulated/0/Music`. Readable by both UIDs, but ONLY AFTER the user has run `termux-setup-storage` in Termux once. Before that, Termux sees `/sdcard/` as empty.\n\nThe only safe bridge between the two worlds is `/sdcard/Download/`:\n1. Gotcha: write_file('/storage/emulated/0/Download/foo.txt', ...). Termux reads: cat /sdcard/Download/foo.txt.\n2. Termux writes /sdcard/Download/result.txt. Gotcha reads: read_file('/storage/emulated/0/Download/result.txt').\n\nInside Termux, use `/sdcard` (which symlinks to `/storage/emulated/0`). Do NOT use `/storage/emulated/0` directly inside Termux for write paths \u2014 go through `/sdcard`.\n\n`$PREFIX` is `/data/data/com.termux/files/usr`. The model should not guess `/usr/bin` for Termux \u2014 that path is empty.\n\nIf a Gotcha `read_file` on a path that exists in `/sdcard/Download/` fails inside Termux's view, the user has likely not run `termux-setup-storage`. Ask the user to open Termux once and run `termux-setup-storage`, then retry.\n\nTermux's `/data/data/com.termux/files/home` is a real directory, but writing to it from Gotcha via `run_command` would fail with Permission denied \u2014 that is a different UID. Stick to the /sdcard bridge.\n\nFor small-to-medium scripts and payloads <100KB, prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the run_termux_command stdin param) over the /sdcard bridge \u2014 it avoids FUSE overhead and does not require termux-setup-storage. For temporary files inside Termux, prefer $TMPDIR \u2014 private to Termux and survives a single call; use /data/data/com.termux/files/home/.tmp/ as fallback.\n\ncross-uid file sizes above 100MB are slow across the /sdcard bridge (FUSE + sdcardfs). When transferring large files, prefer streaming via `dd` or `tar` straight through a pipe."
-}
\ No newline at end of file
+ "instructions": "Three filesystem worlds — keep them separate:\n1. Gotcha's working dir (default cwd for `run_command`, `read_file`, `write_file`, `edit`, `glob`, `grep`): `/storage/emulated/0/Gotcha/chats/<slug_id>/`. INVISIBLE to Termux (different UID).\n2. Termux's home (default `working_dir` for `run_termux_command`): `/data/data/com.termux/files/home`. INVISIBLE to Gotcha.\n3. Shared storage: `/storage/emulated/0/Download`, `/storage/emulated/0/Pictures`, `/storage/emulated/0/Music`. Readable by both UIDs, but ONLY AFTER the user has run `termux-setup-storage` in Termux once. Before that, Termux sees `/sdcard/` as empty.\n\nThe only safe bridge between the two worlds is `/sdcard/Download/`:\n1. Gotcha: write_file('/storage/emulated/0/Download/foo.txt', ...). Termux reads: cat /sdcard/Download/foo.txt.\n2. Termux writes /sdcard/Download/result.txt. Gotcha reads: read_file('/storage/emulated/0/Download/result.txt').\n\nInside Termux, use `/sdcard` (which symlinks to `/storage/emulated/0`). Do NOT use `/storage/emulated/0` directly inside Termux for write paths — go through `/sdcard`.\n\n`$PREFIX` is `/data/data/com.termux/files/usr`. The model should not guess `/usr/bin` for Termux — that path is empty.\n\nIf a Gotcha `read_file` on a path that exists in `/sdcard/Download/` fails inside Termux's view, the user has likely not run `termux-setup-storage`. Ask the user to open Termux once and run `termux-setup-storage`, then retry.\n\nTermux's `/data/data/com.termux/files/home` is a real directory, but writing to it from Gotcha via `run_command` would fail with Permission denied — that is a different UID. Stick to the /sdcard bridge.\n\nFor small-to-medium scripts and payloads <100KB, prefer heredoc/stdin (python3 - << 'PY' / sh -s << 'EOF' via the run_termux_command stdin param) over the /sdcard bridge — it avoids FUSE overhead and does not require termux-setup-storage. For temporary files inside Termux, prefer $TMPDIR — private to Termux and survives a single call; use /data/data/com.termux/files/home/.tmp/ as fallback.\n\ncross-uid file sizes above 100MB are slow across the /sdcard bridge (FUSE + sdcardfs). When transferring large files, prefer streaming via `dd` or `tar` straight through a pipe.\n`$PREFIX` is not always `/data/data/com.termux/files/usr`: Gotcha resolves the real path from the installed package, and under a secondary user or work profile it is `/data/user/<id>/com.termux/files/usr`. Prefer `$PREFIX` over a hardcoded `/data/data/...` prefix in commands."
+}
diff --git a/app/src/main/assets/skills/termux_operations.json b/app/src/main/assets/skills/termux_operations.json
index 2396051..efcf5fc 100644
--- a/app/src/main/assets/skills/termux_operations.json
+++ b/app/src/main/assets/skills/termux_operations.json
@@ -16,7 +16,13 @@
"pkg",
"apt",
"linux",
- "run_termux_command"
+ "run_termux_command",
+ "lock",
+ "dpkg",
+ "exit 100",
+ "stuck",
+ "waiting",
+ "taking long"
],
- "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\" \u2014 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."
-}
\ No newline at end of file
+ "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`."
+}
diff --git a/app/src/main/assets/skills/termux_repositories.json b/app/src/main/assets/skills/termux_repositories.json
index 42e91c3..56bb742 100644
--- a/app/src/main/assets/skills/termux_repositories.json
+++ b/app/src/main/assets/skills/termux_repositories.json
@@ -16,7 +16,10 @@
"ffmpeg",
"install",
"repository",
- "termux-change-repo"
+ "termux-change-repo",
+ "lock",
+ "exit 100",
+ "waiting"
],
- "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 \u2014 fall back to the official primary.\n6. Large packages \u2014 ffmpeg, python, rust, chromium, golang, nodejs-lts, texlive, qt \u2014 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."
-}
\ No newline at end of file
+ "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."
+}
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index e2914ce..d8c7c49 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -1112,77 +1112,8 @@ class AgentEngine(
""
}
val core = when (agent) {
- AgentMode.MONITOR ->
- "You are Gotcha (operating in Monitor mode), a read-only AI assistant " +
- "created by Samosa AI running on the user's Android phone. " +
- "You can inspect, read, and query the device, but you CANNOT create, modify, or " +
- "delete anything. You control the device only through the provided tools; never " +
- "invent tool names or capabilities. If a tool reports a missing permission, " +
- "explain what to grant and ask again. Use the sleep tool to pause and wait " +
- "between operations. Use the search_skills tool when interacting with " +
- "unfamiliar apps or complex operations to learn the optimal steps. " +
- "When you have the answer, call finish_task with it — that is what actually " +
- "delivers it to the user. " +
- "Gotcha also has an Operator mode that CAN act on the device. Its abilities:\n" +
- "- Communication: place calls, send SMS, compose/send email and mark mail read, " +
- "add contacts.\n" +
- "- Screen control: tap, long-press, swipe, type text, press keys, back/home/" +
- "recents — i.e. drive any app on screen, including via the App Navigator " +
- "sub-agent.\n" +
- "- Calendar & reminders: create/edit/delete events, alarms and timers, snooze " +
- "and dismiss them, manage the task list.\n" +
- "- Files & media: write and edit files, read images, take photos, record and " +
- "pause/stop audio, edit or convert media and PDFs, set the wallpaper.\n" +
- "- Device settings: volume, brightness, ringer, Do Not Disturb, Wi-Fi, torch, " +
- "vibrate, clipboard, lock the screen, open any Settings page, write secure " +
- "settings, uninstall apps, disable the camera and set password policy.\n" +
- "- Notifications: dismiss them.\n" +
- "- Shell: run shell commands, Termux commands and root commands when available.\n" +
- "- Connectors: write actions on connected services (e.g. create, update and " +
- "delete Notion pages) alongside the read tools you already have.\n" +
- "- Delegation: hand multi-step work to the General and App Navigator " +
- "sub-agents.\n" +
- "When the user asks for something that needs any of the above, say it is doable " +
- "in Operator mode and that they can switch with the mode badge at the top of " +
- "the chat — do not attempt it yourself. " +
- "Keep replies short and conversational."
- AgentMode.OPERATOR ->
- "You are Gotcha (operating in Operator mode), an AI assistant " +
- "created by Samosa AI running on the user's Android phone. " +
- "You can inspect, read, query, create, modify, and delete on the device. " +
- "You control the device only through the provided tools; never invent tool " +
- "names or capabilities. If a tool reports a missing permission, explain what " +
- "to grant and ask again. After changing device state, confirm what was done. " +
- "Use the sleep tool to pause and wait between operations (e.g. wait for " +
- "a recording to finish before reading it). " +
- "Use the task tool to delegate complex multi-step operations to the General " +
- "sub-agent. Prefer delegation whenever a task involves many tool calls whose " +
- "intermediate steps are not important — only the final result matters. " +
- "For example: organizing files, gathering information from multiple sources, " +
- "or performing a series of device checks. The sub-agent runs in the foreground; " +
- "you will receive its complete report when done. " +
- "Use the navigate_app tool to delegate app interaction tasks to the App " +
- "Navigator sub-agent. For example: opening an app, searching for something, " +
- "scrolling through results, or reading on-screen information. The navigator " +
- "will look at the screen, tap, swipe, and type step by step. " +
- "You will receive its complete report when done. " +
- "A sub-agent's report is the outcome — trust it. It runs in the foreground and " +
- "control returns to Gotcha afterwards, so the screen it worked on is no longer " +
- "in front of you and re-delegating cannot verify anything; it only repeats the " +
- "work. Delegate a second time only for a genuinely different remaining step.\n" +
- "When the work is done, call finish_task with a short summary. That is what " +
- "ends your turn and delivers the outcome to the user — until you call it (or " +
- "reply in plain text with no tool calls) the user has been told nothing. " +
- "Call it for failures too, saying what went wrong.\n" +
- "Keep replies short and conversational. Be careful with destructive actions.\n" +
- "If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
- "When interacting with unfamiliar apps, system settings, or complex " +
- "workflows, use the search_skills tool to fetch context-aware " +
- "operational instructions.\n" +
- "When using uninstall_app: after calling it, the system will open a dialog. " +
- "Tell the user to tap OK in the system dialog to finish the uninstall. " +
- "Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " +
- "use uninstall_app only."
+ AgentMode.MONITOR -> monitorCore()
+ AgentMode.OPERATOR -> operatorCore()
}
val reminder = when (agent) {
AgentMode.MONITOR ->
@@ -1210,6 +1141,81 @@ class AgentEngine(
return core + serveDirective + languageDirective + styleDirective + reminder
}
+ /** The Monitor-mode core instruction block; split out so [agentInstructionText] stays readable. */
+ private fun monitorCore(): String =
+ "You are Gotcha (operating in Monitor mode), a read-only AI assistant " +
+ "created by Samosa AI running on the user's Android phone. " +
+ "You can inspect, read, and query the device, but you CANNOT create, modify, or " +
+ "delete anything. You control the device only through the provided tools; never " +
+ "invent tool names or capabilities. If a tool reports a missing permission, " +
+ "explain what to grant and ask again. Use the sleep tool to pause and wait " +
+ "between operations. Use the search_skills tool when interacting with " +
+ "unfamiliar apps or complex operations to learn the optimal steps. " +
+ "When you have the answer, call finish_task with it — that is what actually " +
+ "delivers it to the user. " +
+ "Gotcha also has an Operator mode that CAN act on the device. Its abilities:\n" +
+ "- Communication: place calls, send SMS, compose/send email and mark mail read, " +
+ "add contacts.\n" +
+ "- Screen control: tap, long-press, swipe, type text, press keys, back/home/" +
+ "recents — i.e. drive any app on screen, including via the App Navigator " +
+ "sub-agent.\n" +
+ "- Calendar & reminders: create/edit/delete events, alarms and timers, snooze " +
+ "and dismiss them, manage the task list.\n" +
+ "- Files & media: write and edit files, read images, take photos, record and " +
+ "pause/stop audio, edit or convert media and PDFs, set the wallpaper.\n" +
+ "- Device settings: volume, brightness, ringer, Do Not Disturb, Wi-Fi, torch, " +
+ "vibrate, clipboard, lock the screen, open any Settings page, write secure " +
+ "settings, uninstall apps, disable the camera and set password policy.\n" +
+ "- Notifications: dismiss them.\n" +
+ "- Shell: run shell commands, Termux commands and root commands when available.\n" +
+ "- Connectors: write actions on connected services (e.g. create, update and " +
+ "delete Notion pages) alongside the read tools you already have.\n" +
+ "- Delegation: hand multi-step work to the General and App Navigator " +
+ "sub-agents.\n" +
+ "When the user asks for something that needs any of the above, say it is doable " +
+ "in Operator mode and that they can switch with the mode badge at the top of " +
+ "the chat — do not attempt it yourself. " +
+ "Keep replies short and conversational."
+
+ /** The Operator-mode core instruction block; split out so [agentInstructionText] stays readable. */
+ private fun operatorCore(): String =
+ "You are Gotcha (operating in Operator mode), an AI assistant " +
+ "created by Samosa AI running on the user's Android phone. " +
+ "You can inspect, read, query, create, modify, and delete on the device. " +
+ "You control the device only through the provided tools; never invent tool " +
+ "names or capabilities. If a tool reports a missing permission, explain what " +
+ "to grant and ask again. After changing device state, confirm what was done. " +
+ "Use the sleep tool to pause and wait between operations (e.g. wait for " +
+ "a recording to finish before reading it). " +
+ "Use the task tool to delegate complex multi-step operations to the General " +
+ "sub-agent. Prefer delegation whenever a task involves many tool calls whose " +
+ "intermediate steps are not important — only the final result matters. " +
+ "For example: organizing files, gathering information from multiple sources, " +
+ "or performing a series of device checks. The sub-agent runs in the foreground; " +
+ "you will receive its complete report when done. " +
+ "Use the navigate_app tool to delegate app interaction tasks to the App " +
+ "Navigator sub-agent. For example: opening an app, searching for something, " +
+ "scrolling through results, or reading on-screen information. The navigator " +
+ "will look at the screen, tap, swipe, and type step by step. " +
+ "You will receive its complete report when done. " +
+ "A sub-agent's report is the outcome — trust it. It runs in the foreground and " +
+ "control returns to Gotcha afterwards, so the screen it worked on is no longer " +
+ "in front of you and re-delegating cannot verify anything; it only repeats the " +
+ "work. Delegate a second time only for a genuinely different remaining step.\n" +
+ "When the work is done, call finish_task with a short summary. That is what " +
+ "ends your turn and delivers the outcome to the user — until you call it (or " +
+ "reply in plain text with no tool calls) the user has been told nothing. " +
+ "Call it for failures too, saying what went wrong.\n" +
+ "Keep replies short and conversational. Be careful with destructive actions.\n" +
+ "If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
+ "When interacting with unfamiliar apps, system settings, or complex " +
+ "workflows, use the search_skills tool to fetch context-aware " +
+ "operational instructions.\n" +
+ "When using uninstall_app: after calling it, the system will open a dialog. " +
+ "Tell the user to tap OK in the system dialog to finish the uninstall. " +
+ "Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " +
+ "use uninstall_app only."
+
/**
* Builds the environment info string with device info, agent mode,
* and service statuses (PRD §14.1).
diff --git a/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt b/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt
index b8d6f83..915bc6f 100644
--- a/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt
+++ b/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt
@@ -231,9 +231,13 @@ class MediaConvertTool(
val detail = text.substringAfter("stderr:", "").trim().ifEmpty { text }
return when {
text.contains("not found", ignoreCase = true) -> ToolResult.error(
- "Termux has no ffmpeg installed, which is what does the conversion. Ask the user to open Termux " +
- "and run 'pkg install ffmpeg' (it is a large download, so say that), then try again. " +
- "You may also run it yourself with run_termux_command if the user agrees."
+ "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 " +
+ "timeout_seconds=600). If that reports a package lock held by another process, wait for it " +
+ "or tap Exit on the Termux notification; never delete the lock files or kill -9 the process. " +
+ "On a slow or blocked network, split it as 'pkg download ffmpeg' then 'dpkg -i " +
+ "\$PREFIX/var/cache/apt/archives/*.deb' (see the termux_repositories skill). You may also run " +
+ "it yourself with run_termux_command if the user agrees."
)
text.contains("No such file or directory", ignoreCase = true) -> ToolResult.error(
"ffmpeg could not see '${input.canonicalPath}', although Gotcha can. This almost always means the " +
diff --git a/app/src/main/java/com/gotcha/tools/PodcastTool.kt b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
index 2941958..24900ed 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
@@ -421,8 +421,9 @@ class PodcastTool(
}
}
return kept to " The MP3 conversion step failed " +
- "(${result.message.take(ERROR_DETAIL_CHARS)}) — the finished audio was kept as '${kept.name}'; " +
- "media_convert can turn it into an MP3 once that is fixed."
+ "(${result.message.take(ERROR_DETAIL_CHARS)}) — the finished audio was kept as '${kept.name}'. " +
+ "Install Termux's ffmpeg ('pkg install ffmpeg -y' — a large download, 5-15 minutes, so ask the " +
+ "user first) and run media_convert on '${m4a.name}' to finish the MP3."
}
// ---- sharing ----
diff --git a/app/src/main/java/com/gotcha/tools/TermuxMessages.kt b/app/src/main/java/com/gotcha/tools/TermuxMessages.kt
index 09b8c7a..12fc357 100644
--- a/app/src/main/java/com/gotcha/tools/TermuxMessages.kt
+++ b/app/src/main/java/com/gotcha/tools/TermuxMessages.kt
@@ -64,6 +64,31 @@ internal object TermuxMessages {
"nothing is pending."
)
+ /**
+ * apt/dpkg lock contention — the `exit 100` "Could not get lock ... lock-frontend" shape.
+ *
+ * This is the failure this app actually meets on slow installs: a previous `pkg install`
+ * timed out, its process kept running under Termux's uid, and every later call waits on the
+ * lock it still holds. Treated distinctly from a timeout because it is *quick* (apt gives up
+ * after ~100 polls) and from [tooManyInFlight] because the semaphore slot is free — the lock
+ * is held by the OS process, not by Gotcha. The two destructive "fixes" a model reaches for
+ * (delete the lock files, `kill -9` the holder) are exactly what must be refused, so they are
+ * spelled out rather than implied.
+ */
+ fun lockHeld(holderPid: String?): ToolResult {
+ val holder = holderPid?.let { " (process $it)" }.orEmpty()
+ return ToolResult.error(
+ "Another apt/dpkg package operation is already running in Termux$holder and holds the package " +
+ "lock, so this command could not start. This is NOT a mirror or network problem. " +
+ "A run_termux_command cannot stop that process — a timed-out or still-running pkg/apt keeps " +
+ "holding the lock under Termux's uid. Do NOT delete the lock files and do NOT kill -9 the " +
+ "process; that corrupts the package database without releasing the lock. Check it with " +
+ "`ps -ef | grep -E '[d]pkg|[a]pt'`. If it never finishes, open the notifications shade " +
+ "(global_action or press_key 'notifications') and tap the Exit action on the Termux " +
+ "notification — that ends every Termux session and releases the lock. Then retry."
+ )
+ }
+
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 — a run_termux_command cannot kill them. To stop them, open the " +
diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
index db36339..5147b88 100644
--- a/app/src/main/java/com/gotcha/tools/TermuxTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt
@@ -141,7 +141,17 @@ class TermuxTool(
// Defeats coreutils' own refusal to remove `/`, so its presence is intent enough.
Regex("""--no-preserve-root"""),
Regex("""\bfastboot\b"""),
- Regex("""\brecovery\b[^\n]*--wipe""")
+ Regex("""\brecovery\b[^\n]*--wipe"""),
+ // Deleting a live package manager's lock files or DB while a dpkg holds the fd does not
+ // release the lock — it lets a second apt write /var/lib/dpkg/status concurrently and
+ // corrupt the package database. The only remedies are to wait or to tap Exit on the
+ // Termux notification, so the mistake is refused rather than explained after the fact.
+ Regex("""\brm\b[^\n]*(?:dpkg/lock(?:-frontend)?|dpkg/status|apt/lists/lock|apt/archives/lock)"""),
+ // SIGKILL on a package manager or a bare PID. The model cannot legitimately kill a
+ // process from another call anyway (see termux_background), and `kill -9` on a live
+ // dpkg mid-transaction leaves a half-configured package that needs dpkg --configure -a.
+ Regex("""\bkill\s+-9\b[^\n]*(?:\b\d+\b|\bdpkg\b|\bapt(?:-get)?\b|\bpkg\b)"""),
+ Regex("""\b(?:pkill|killall)\b[^\n]*(?:\bdpkg\b|\bapt(?:-get)?\b|\bpkg\b)""")
)
fun status(): TermuxStatus {
@@ -219,7 +229,7 @@ class TermuxTool(
pendingIntentFlags()
)
val started = runCatching {
- context.startService(commandIntent(trimmed, workingDir, stdin, pendingIntent))
+ context.startService(commandIntent(commandToRun(trimmed), workingDir, stdin, pendingIntent))
}
started.exceptionOrNull()?.let { return TermuxMessages.startFailed(it) }
// startService reports "no such service" by returning null, not by throwing. Android
@@ -262,6 +272,13 @@ 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
+ // 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)) {
+ return TermuxMessages.lockHeld(HOLDER_PID.find(message)?.groupValues?.get(1))
+ }
return ToolResult(success = exit == 0, message = message)
}
@@ -423,6 +440,22 @@ class TermuxTool(
/** 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""")
+ /**
+ * 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.
+ */
+ private val LOCK_SIGNATURE = Regex(
+ """(?:lock-frontend|Could not get lock|cache lock|Unable to acquire the dpkg frontend lock)""",
+ RegexOption.IGNORE_CASE
+ )
+
+ /** The holder named by apt's wait message: `It is held by process 24247 (dpkg)`. */
+ private val HOLDER_PID = Regex("""held by process (\d+)""")
+
+ /** Termux's wake-lock helpers; required for any task longer than ~30s that Doze would throttle. */
+ private const val WAKE_LOCK = "termux-wake-lock"
+ private const val WAKE_UNLOCK = "termux-wake-unlock"
+
/** Shell separators the deny-list splits on before matching each part. */
private val SEGMENT_SEPARATORS = Regex("""[;&|\n]+""")
@@ -442,6 +475,26 @@ class TermuxTool(
/** Test seam: lets the cap be saturated without hardcoding the number twice. */
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.
+ */
+ internal fun commandToRun(trimmed: String): String =
+ if (PKG_LIKE_REGEX.containsMatchIn(trimmed)) withWakeLock(trimmed) else trimmed
+
+ /**
+ * Wraps [command] in `termux-wake-lock`/`termux-wake-unlock`, preserving its exit code (a naive
+ * `cmd; termux-wake-unlock` would swallow failures) and skipping the wrap entirely when the
+ * lock tools are not installed. Split out so the shape can be asserted without Termux.
+ */
+ internal fun withWakeLock(command: String): String {
+ if (WAKE_LOCK in command) return command
+ val wrapped = "$WAKE_LOCK; { $command; rc=\$?; $WAKE_UNLOCK; exit \$rc; }"
+ return "if command -v $WAKE_LOCK >/dev/null 2>&1; then $wrapped; else $command; fi"
+ }
+
/**
* 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
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index de22190..efbaafe 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -2398,6 +2398,11 @@ object ToolDefinitions {
"(global_action or press_key 'notifications') and tap the Exit action on the Termux " +
"notification, which ends every Termux session. If you cannot reach that, ask the user to tap " +
"Exit on the Termux notification.\n" +
+ "- Lock contention: an `exit 100` whose error names `lock-frontend` / `Could not get lock` / " +
+ "`held by process <pid>` means ANOTHER pkg/apt is already running and holds the package lock — " +
+ "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" +
"- 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/main/java/com/gotcha/ui/ConnectorsSection.kt b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
index 2639faa..49bc0c2 100644
--- a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
@@ -36,12 +36,12 @@ import com.gotcha.connectors.microsoft.MicrosoftConnector
import com.gotcha.connectors.notion.NotionConnector
import com.gotcha.connectors.oauth.OAuthConnectFlow
import com.gotcha.data.SettingsRepository
-import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import kotlin.math.roundToInt
/**
* The body of the Connectors screen: one card per connector, built from the two
diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
index 4f96e91..d429aa6 100644
--- a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt
@@ -309,6 +309,98 @@ class TermuxToolTest {
}
}
+ @Test
+ fun `package-manager lock file deletion and dpkg sigkill are blocked`() = runTest {
+ // The destructive "fixes" a model reaches for when apt reports a held lock: deleting the
+ // lock files or SIGKILL-ing the holder. Neither releases the lock (the holder keeps the fd),
+ // and both can corrupt the dpkg database — so they are refused before reaching the shell.
+ installTermux()
+ grantRunCommand()
+ listOf(
+ "rm -f /data/data/com.termux/files/usr/var/lib/dpkg/lock-frontend",
+ "rm -f \$PREFIX/var/lib/dpkg/lock",
+ "rm -rf \$PREFIX/var/lib/dpkg/status",
+ "rm -f /data/data/com.termux/files/usr/var/cache/apt/archives/lock",
+ "kill -9 24247",
+ "kill -9 \$(pgrep dpkg)",
+ "killall apt-get",
+ "pkill dpkg",
+ "pkill -f apt"
+ ).forEach { command ->
+ val result = tool.runCommand(command)
+ assertFalse("expected '$command' to be blocked", result.success)
+ assertTrue("'$command' should cite the policy: ${result.message}", result.message.contains("safety policy"))
+ }
+ }
+
+ @Test
+ fun `kill of a process the agent itself started stays allowed`() = runTest {
+ // The background-skill persistence pattern kills a pid it wrote to disk; that is legitimate
+ // and must not trip the new SIGKILL guard (which targets package managers and bare pids).
+ listOf(
+ "kill \$(cat /sdcard/Download/myserver.pid)",
+ "kill -TERM 1234",
+ "rm -f ~/notes.txt",
+ "ls /var/lib/dpkg"
+ ).forEach { command ->
+ val result = tool.runCommand(command)
+ assertFalse("'$command' must not be refused: ${result.message}", result.message.contains("safety policy"))
+ }
+ }
+
+ @Test
+ fun `a package-lock failure is reported with lock recovery guidance`() {
+ // The exact output from the ffmpeg incident: apt polls ~100 times then exits 100 with the
+ // lock-frontend message. The model must be told it is lock contention, not a mirror problem,
+ // and given the only safe remedies.
+ val bundle = resultBundle(
+ exitCode = 100,
+ stdout = "WARNING: apt does not have a stable CLI interface. Use with caution in scripts.\n" +
+ "E: Could not get lock /data/data/com.termux/files/usr/var/lib/dpkg/lock-frontend. " +
+ "It is held by process 24247 (dpkg).\n" +
+ "E: Unable to acquire the dpkg frontend lock, is another process using it?"
+ )
+
+ val result = tool.formatResult(bundle)
+
+ assertFalse(result.success)
+ assertTrue("must name the holder: ${result.message}", result.message.contains("process 24247"))
+ assertTrue(result.message.contains("NOT a mirror"))
+ assertTrue("must forbid the destructive fix", result.message.contains("Do NOT delete the lock files"))
+ assertTrue(result.message.contains("Exit"))
+ }
+
+ @Test
+ fun `a non-lock failure is passed through unaltered`() {
+ val bundle = resultBundle(exitCode = 127, stderr = "sh: nope: not found")
+
+ val result = tool.formatResult(bundle)
+
+ assertFalse(result.success)
+ assertTrue(result.message.contains("exit code: 127"))
+ assertTrue(result.message.contains("not found"))
+ }
+
+ @Test
+ fun `pkg-like commands are wrapped in a wake-lock that preserves the exit code`() {
+ val wrapped = TermuxTool.withWakeLock("pkg install ffmpeg -y -q")
+
+ assertTrue(wrapped.contains("termux-wake-lock"))
+ assertTrue(wrapped.contains("termux-wake-unlock"))
+ assertTrue("must capture the original exit code", wrapped.contains("rc=\$?"))
+ assertTrue(wrapped.contains("exit \$rc"))
+ assertTrue("must degrade on a stripped Termux", wrapped.contains("command -v termux-wake-lock"))
+ assertTrue(wrapped.contains("pkg install ffmpeg -y -q"))
+ assertTrue("an already-wrapped command is not double-wrapped", wrapped == TermuxTool.withWakeLock(wrapped))
+ }
+
+ @Test
+ fun `a non-pkg command is not wake-lock wrapped`() {
+ // withWakeLock itself wraps 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"))
+ }
+
@Test
fun `rm -r inside termux home is allowed unlike run_command`() = runTest {
// TerminalTool blocks every `rm -r`; here it is ordinary housekeeping, so the deny-list
diff --git a/docs/termux-setup.md b/docs/termux-setup.md
index d90c3fb..cac4fb1 100644
--- a/docs/termux-setup.md
+++ b/docs/termux-setup.md
@@ -95,6 +95,21 @@ in order of how often they bite:
- **Hard ceiling: 600 s.** `pkg install` of `ffmpeg`, `chromium`, `rust`,
`golang`, or `texlive` can hit this. Raise `timeout_seconds` to 600
and warn the user before starting one.
+- **Package-lock contention (`exit 100`).** If `pkg install` returns
+ `Could not get lock ... lock-frontend ... held by process <pid> (dpkg)`,
+ another package operation is still running under Termux's uid — usually a
+ timed-out install that Gotcha could not kill. It is **not** a mirror or
+ network problem. Check `ps -ef | grep -E '[d]pkg|[a]pt'`; if it never
+ finishes, tap **Exit** on the Termux notification (that ends every session
+ and releases the lock). Never delete the lock files or `kill -9` the
+ process — that corrupts the package database without releasing the lock.
+ Package-manager commands are automatically wrapped in `termux-wake-lock` so
+ Doze cannot throttle them mid-download.
+- **Secondary users / work profiles.** `/data/data/com.termux` is only the
+ primary user's path. Gotcha derives Termux's real root from the installed
+ package (`/data/user/<id>/com.termux/files/usr` under a work profile);
+ commands should use `$PREFIX` rather than a hardcoded `/data/data/...`
+ prefix.
- **4 commands in flight, process-wide.** Sub-agents share the same
semaphore. A 5th call returns an error.
- **Android 12+ background restriction.** If Gotcha is in the background
@@ -125,6 +140,12 @@ should know these so the user does not have to:
If a `pkg install` keeps failing midway, split the network step from
the install step with `pkg download <pkg>` and `dpkg -i` from the local
cache.
+- **ffmpeg is used by three tools.** `media_convert` (audio format
+ conversion), `synthesize_podcast` / `synthesize_podcast_dialogue` with
+ `format='mp3'`, and the podcast MP3 salvage path all run through Termux's
+ `ffmpeg`. When it is missing, `media_convert` says exactly what to install;
+ a requested `.mp3` podcast degrades to `.m4a` and explains how to finish the
+ MP3 once ffmpeg is installed.
- **Shared storage (`/sdcard`).** `/sdcard/Download` is the only safe
cross-uid bridge between Gotcha and Termux. It is empty inside Termux
until the user runs `termux-setup-storage` once in Termux.