Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
Merge PR #350: disable: skip the launcher that owns Home while nothing else can take it (#239)
Gathin23bff91403469b
diff --cc tests/test_home_guard.pyindex 000000000,1d4c741eb..722794026mode 000000,100644..100644--- a/tests/test_home_guard.py+++ b/tests/test_home_guard.py@@@ -1,0 -1,230 +1,245 @@@+ """tools/disable.sh and tools/disable.ps1 must not disable the app that owns Home (#239).++ A list from `examples/` (the Xiaomi one, for instance) includes the stock launcher, and running it+ before the replacement launcher is Home leaves the TV with nothing to start. The property worth+ testing is the one no TV reproduces on demand, so tools/tv.py is replaced by a fake that answers the+ queries from a JSON file: the real disable script runs, only the ADB transport is simulated.++ Run from the repository root: python3 -m unittest discover -s tests -v+ The PowerShell cases need `pwsh` on PATH and skip without it; CI has no PowerShell.+ """+ import json+ import os+ from pathlib import Path+ import shutil+ import subprocess+ import sys+ import tempfile+ import unittest+++ ROOT = Path(__file__).resolve().parents[1]+ STOCK = "com.google.android.tvlauncher"+ CUSTOM = "com.gathin.tvhome"+ PWSH = shutil.which("pwsh")++ # Stands in for tools/tv.py: answers the queries the disable script makes and records what a batch+ # would send, without a TV.+ FAKE_TV = r'''+ import json+ import os+ import sys++ STATE_PATH = os.environ["FAKE_TV_STATE"]+++ def load():+ with open(STATE_PATH) as f:+ return json.load(f)+++ state = load()+++ def save():+ with open(STATE_PATH, "w") as f:+ json.dump(state, f)+++ def answer(command):+ if command == "pm list packages":+ return "".join(f"package:{name}\n" for name in state["installed"])+ if command == "pm list packages -d":+ return "".join(f"package:{name}\n" for name in state["disabled"])+ if command.startswith("cmd package query-activities"):+ if state["claims_fail"]:+ sys.exit(1)+ return "".join(f" {name}/.MainActivity\n" for name in state["claims"])+ if command.startswith("cmd package resolve-activity"):+ if state["home_fails"]:+ sys.exit(1)+ return (state["home"] or "") + "\n"+ if command.startswith("settings get global "):+ return "null\n"+ return ""+++ class Device:+ def shell(self, command, read_timeout_s=None):+ return answer(command)++ def close(self):+ pass+++ def connect():+ # recovery.py imports this module and calls connect() directly.+ return Device()+++ def main():+ args = sys.argv[1:]+ if "--batch" in args:+ for line in sys.stdin:+ line = line.strip()+ if line and not line.startswith("#"):+ state["commands"].append(line)+ save()+ return 0+ print(answer(args[-1]), end="")+ return 0+++ if __name__ == "__main__":+ sys.exit(main())+ '''+++ class HomeGuardTest(unittest.TestCase):+ def setUp(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.base = Path(tmp.name)+ self.repo = self.base / "repo"+ self.tools = self.repo / "tools"+ self.tools.mkdir(parents=True)+ for name in ("disable.sh", "disable.ps1", "recovery.py"):+ shutil.copy2(ROOT / "tools" / name, self.tools / name)+ (self.tools / "tv.py").write_text(FAKE_TV)+ # The scripts call the tools venv's Python. Run the real interpreter, which imports the fake+ # tv.py for the transport and the real recovery.py for the logic. disable.ps1 asks for the+ # Windows path, which PowerShell resolves to tools/venv/Scripts/python.exe here too.+ for client in (self.tools / "venv" / "bin" / "python",+ self.tools / "venv" / "Scripts" / "python.exe"):+ client.parent.mkdir(parents=True, exist_ok=True)+ client.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')+ client.chmod(0o755)++ self.home = self.base / "home"+ self.home.mkdir()+ self.state_path = self.base / "tv-state.json"+ self.list_path = self.base / "debloat.txt"+ self.write_list(["com.example.before", STOCK, "com.example.after"])++ def write_list(self, names):+ self.list_path.write_text("# My TV\n" + "".join(f"{name}\n" for name in names))++ def tv(self, **overrides):+ state = {+ "installed": ["com.example.before", "com.example.after", STOCK],+ "disabled": [],+ "home": f"{STOCK}/.MainActivity",+ "claims": [STOCK],+ "home_fails": False,+ "claims_fail": False,+ "commands": [],+ }+ state.update(overrides)+ self.state_path.write_text(json.dumps(state))++ def disable(self, entry, extra_env=None, list_path=None):+ env = dict(os.environ, TV_HOST="192.168.1.50", HOME=str(self.home),+ FAKE_TV_STATE=str(self.state_path), **(extra_env or {}))+ if entry == "sh":+ argv = ["bash", str(self.tools / "disable.sh"), str(list_path or self.list_path)]+ else:+ argv = [PWSH, "-NoProfile", "-File", str(self.tools / "disable.ps1"),+ "-TvHost", "192.168.1.50", str(list_path or self.list_path)]+ result = subprocess.run(argv, cwd=self.repo, env=env, capture_output=True, text=True,+ timeout=180)+ with open(self.state_path) as f:+ return result, json.load(f)["commands"]++ def entries(self):+ return ("sh", "ps1") if PWSH else ("sh",)++ def output(self, result):+ return result.stdout + result.stderr++ def test_the_owner_of_home_is_skipped_when_it_is_the_only_home(self):+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv()+ result, sent = self.disable(entry)+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent,+ "the only Home the TV has must not be disabled")+ self.assertEqual(sent[:2], ["pm disable-user --user 0 com.example.before",+ "pm disable-user --user 0 com.example.after"])+ self.assertIn(f"Skipping {STOCK}", self.output(result))++ def test_a_second_home_lets_the_list_disable_the_owner(self):+ # The usual end state: the new launcher is Home, and the stock one is still enabled.+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv(installed=["com.example.before", "com.example.after", STOCK, CUSTOM],+ home=f"{CUSTOM}/.MainActivity", claims=[CUSTOM, STOCK])+ result, sent = self.disable(entry)+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)++ def test_a_list_that_disables_every_home_keeps_the_owner(self):+ self.write_list(["com.example.before", STOCK, CUSTOM])+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv(installed=["com.example.before", STOCK, CUSTOM], claims=[STOCK, CUSTOM])+ result, sent = self.disable(entry)+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent,+ "the app that owns Home stays enabled")+ self.assertIn(f"pm disable-user --user 0 {CUSTOM}", sent,+ "the other launcher listed is still disabled")+++ def test_the_setup_wizard_does_not_count_as_another_home(self):++ # On Google TV, setupwraith and the settings app answer HOME as well. If they counted, the stock++ # launcher would go and setupwraith would take Home: the crash loop in docs/TROUBLESHOOTING.md.++ wizard = "com.google.android.tungsten.setupwraith"++ for entry in self.entries():++ with self.subTest(entry=entry):++ self.tv(installed=["com.example.before", "com.example.after", STOCK, wizard,++ "com.android.tv.settings"],++ claims=[STOCK, wizard, "com.android.tv.settings"])++ result, sent = self.disable(entry)++ self.assertEqual(result.returncode, 0, self.output(result))++ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent,++ "the setup wizard is not a launcher to fall back on")++ self.assertIn(f"Skipping {STOCK}", self.output(result))+++ def test_a_tv_that_cannot_list_its_homes_is_left_with_one(self):+ # tv.py fails or the TV answers nothing: the owner is the only Home this run knows about.+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv(claims_fail=True)+ result, sent = self.disable(entry)+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent)++ def test_force_disables_the_owner(self):+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv()+ result, sent = self.disable(entry, {"FORCE_HOME": "1"})+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)++ def test_the_guard_does_not_touch_a_list_without_the_owner(self):+ # Home belongs to the new launcher: the stock one in the list is fair game.+ for entry in self.entries():+ with self.subTest(entry=entry):+ self.tv(installed=["com.example.before", "com.example.after", STOCK, CUSTOM],+ home=f"{CUSTOM}/.MainActivity", claims=[CUSTOM, STOCK])+ result, sent = self.disable(entry)+ self.assertEqual(result.returncode, 0, self.output(result))+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)+ self.assertNotIn("Skipping", self.output(result))++ def test_the_skipped_launcher_stays_in_the_recovery_record(self):+ self.tv()+ result, sent = self.disable("sh")+ self.assertEqual(result.returncode, 0, self.output(result))+ record = next((self.home / ".cleanyourtv").glob("recovery-*.json"))+ self.assertEqual(json.loads(record.read_text())["packages"][STOCK], "enabled")+++ if __name__ == "__main__":+ unittest.main()diff --cc tools/disable.ps1index b07f325a7,d39ecfeb8..831fb41fe--- a/tools/disable.ps1+++ b/tools/disable.ps1@@@ -38,14 -38,27 +38,37 @@@ if ($pkgs -contains $setup -and -not $e$pkgs = @($pkgs | Where-Object { $_ -ne $setup })}}+# Same as disable.sh: on firmware with ro.adb.secure=0, port 5555 gives a shell to any device on the+# network without the "Allow" prompt. Read it now and say so once the list is done; a failed read only+# skips the note. Windows PowerShell turns redirected stderr into an error that 'Stop' would throw.+$ErrorActionPreference = 'Continue'+$adbSecure = ((& $py -I (Join-Path $repo 'tools\tv.py') 'getprop ro.adb.secure' 2>$null) -join '').Trim()+if ($LASTEXITCODE -ne 0) { $adbSecure = '' }+$ErrorActionPreference = 'Stop'++ # Home guard (#239), the same check as disable.sh: a list that disables the app owning Home leaves the+ # TV with nothing to start Home with. Skip the owner while nothing else on the TV can answer HOME;+ # `$env:FORCE_HOME=1` disables it anyway, for a TV reachable another way.+ if (-not $env:FORCE_HOME) {+ $homeQuery = 'cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME'+ $homeLine = @(& $py -I (Join-Path $repo 'tools\tv.py') $homeQuery) |+ Where-Object { $_ -match '\S' } | Select-Object -Last 1+ $homePkg = "$homeLine".Trim() -split '/' | Select-Object -First 1+ if ($homePkg -and ($pkgs -contains $homePkg)) {+ # Every package with a HOME activity the TV can start now; a disabled one does not answer.+ $claimQuery = 'cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME'+ $claims = @(& $py -I (Join-Path $repo 'tools\tv.py') $claimQuery | ForEach-Object {+ if ($_ -match '^\s*([A-Za-z0-9_.]+)/') { $Matches[1] }+ } | Sort-Object -Unique)- $others = @($claims | Where-Object { $_ -ne $homePkg -and $pkgs -notcontains $_ })++ # The setup wizard and the settings apps answer HOME too, but they are not launchers (disable.sh).++ $notLaunchers = @('com.google.android.tungsten.setupwraith', 'com.android.tv.settings', 'com.android.settings', 'com.android.provision')++ $others = @($claims | Where-Object { $_ -ne $homePkg -and $pkgs -notcontains $_ -and $notLaunchers -notcontains $_ })+ if ($others.Count -eq 0) {+ Write-Warning "Skipping ${homePkg}: it owns Home, and no other app that can answer Home is installed and staying enabled. Make the new launcher Home first (launcher\build-and-install.ps1), then run this list again to disable the old one; or set `$env:FORCE_HOME=1 if you can still reach the TV."+ $pkgs = @($pkgs | Where-Object { $_ -ne $homePkg })+ }+ }+ }# Same as disable.sh: the state undo needs is recorded before the first command reaches the TV, and# a failed save leaves the TV untouched (#239).& $py -I (Join-Path $repo 'tools\recovery.py') --save $Listdiff --cc tools/disable.shindex b56495e3b,cb0f993aa..8d8161f65--- a/tools/disable.sh+++ b/tools/disable.sh@@@ -49,10 -49,30 +49,38 @@@ if printf '%s\n' "$PKGS" | grep -x "$SEfifi+# On firmware with ro.adb.secure=0, port 5555 gives a shell to any device on the network without the+# "Allow" prompt. Read it now and say so once the list is done; a failed read only skips the note.+ADB_SECURE="$("$PY" -I tools/tv.py "getprop ro.adb.secure" 2>/dev/null | tr -d '[:space:]')" || ADB_SECURE=""++ # Home guard (#239): a list that disables the app owning Home leaves the TV with nothing to start the+ # next time Home is pressed, and on Google TV the setup wizard can take the category instead and+ # crash-loop system_server (docs/TROUBLESHOOTING.md). Skip the owner while nothing else on the TV can+ # answer HOME; FORCE_HOME=1 disables it anyway, for a TV reachable another way.+ # The extra query is worth it only when the list holds Home's own package, which is how a list that+ # leaves the TV without a launcher looks before anything is disabled.+ HOME_QUERY='cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME'+ HOME_PKG=$("$PY" -I tools/tv.py "$HOME_QUERY" 2>/dev/null | tail -n 1 | tr -d '\r' | cut -d/ -f1 || true)-if [ -n "$HOME_PKG" ] && printf '%s\n' "$PKGS" | grep -qxF "$HOME_PKG" && [ -z "${FORCE_HOME:-}" ]; then++# grep without -q: an early exit could SIGPIPE printf and fail open under pipefail (see above).++if [ -n "$HOME_PKG" ] && printf '%s\n' "$PKGS" | grep -xF "$HOME_PKG" >/dev/null && [ -z "${FORCE_HOME:-}" ]; then+ # Every package with a HOME activity the TV can start now: disabled packages do not answer, so this+ # is "what could take Home if the list went through".+ CLAIMS=$("$PY" -I tools/tv.py 'cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME' 2>/dev/null \+ | tr -d '\r' | grep -o '^ *[A-Za-z0-9_.]*/' | tr -d ' /' | sort -u || true)+ # Nothing left to answer Home once the list is applied, or the TV could not say who does: either+ # way the owner is the only Home this run knows about, so it stays enabled.- OTHERS=$(printf '%s\n' "$CLAIMS" | grep -vxF "$HOME_PKG" | grep -vxF "$PKGS" || true)++ # The setup wizard and the settings apps answer HOME too, but they are not launchers: on Google TV,++ # setupwraith taking Home is the crash loop this guard exists to prevent. They don't count.++ OTHERS=$(printf '%s\n' "$CLAIMS" | grep -vxF "$HOME_PKG" | grep -vxF "$PKGS" \++ | grep -vxF -e com.google.android.tungsten.setupwraith -e com.android.tv.settings -e com.android.settings -e com.android.provision || true)+ if [ -z "$OTHERS" ]; then+ echo "Skipping $HOME_PKG: it owns Home, and no other app that can answer Home is installed and" >&2+ echo "staying enabled. Make the new launcher Home first (launcher/build-and-install.sh), then run" >&2+ echo "this list again to disable the old one; or set FORCE_HOME=1 if you can still reach the TV." >&2+ PKGS="$(printf '%s\n' "$PKGS" | grep -vxF "$HOME_PKG" || true)"+ fi+ fi+# The state undo needs goes to disk before the first command reaches the TV, and a failed save stops# here with the TV untouched: a record written afterwards would describe a TV that is already broken,# and a retry must not overwrite the one taken before the first change (#239).