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
tools: recovery.py stops recording Android's HOME chooser as the Home to restore
Mazin Kanuga92aa4aa3025d
diff --git a/tests/test_recovery_home_chooser.py b/tests/test_recovery_home_chooser.pynew file mode 100644index 000000000..4dec8f01f--- /dev/null+++ b/tests/test_recovery_home_chooser.py@@ -0,0 +1,123 @@+"""tools/recovery.py does not record Android's HOME chooser as the Home to restore.++When Home has no default, `cmd package resolve-activity --brief` ends at the chooser. A Chromecast+with Google TV 4K (Google TV 14, UTTC.250917.004) prints a lookup that ends there as two lines, a+priority line and then the component; there a plain LAUNCHER lookup does:++ priority=0 preferredOrder=0 match=0x0 specificIndex=-1 isDefault=false+ android/com.android.internal.app.ResolverActivity++recovery.py took the last line as the Home that owned the TV, which put "android" among the+recorded packages. That is not a package name, so load_record refused the file: disable.sh wrote it+and exited 0, and from then on restore.sh and every later disable.sh run stopped at "not a usable+recovery record" until the owner moved the file aside by hand. The chooser cases in+tests/test_home_guard.py fake the answer as a bare "android", which is why they did not catch it.++The record tests borrow the fake TV and helpers of tests/test_recovery_record.py, and the check.py+tests those of tests/test_drift_check.py. query_home is shared with check.py, whose report on the+chooser stays what it was, so the fix lives in save() and the last two tests pin that.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import test_drift_check as drift # noqa: E402+import test_recovery_record as records # noqa: E402++CHOOSER = "android/com.android.internal.app.ResolverActivity"+CHOOSER_ANSWER = "priority=0 preferredOrder=0 match=0x0 specificIndex=-1 isDefault=false\n" + CHOOSER+STOCK = "com.google.android.tvlauncher"+++class RecoveryHomeChooserTest(unittest.TestCase):+ # Borrowed rather than inherited, so the tests of tests/test_recovery_record.py do not run a+ # second time under this class.+ setUp = records.RecoveryRecordTest.setUp+ write_list = records.RecoveryRecordTest.write_list+ tv = records.RecoveryRecordTest.tv+ run_script = records.RecoveryRecordTest.run_script+ record = records.RecoveryRecordTest.record+ sent = records.RecoveryRecordTest.sent+ clear_sent = records.RecoveryRecordTest.clear_sent++ def test_the_chooser_is_not_recorded_as_home(self):+ self.tv(home=CHOOSER_ANSWER)+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ record = self.record()+ self.assertIsNone(record["home"])+ # No "android" entry: it is not a package name, and a record holding it cannot be read back.+ self.assertEqual(record["packages"], {+ "com.example.enabled": "enabled",+ "com.example.already_off": "disabled",+ "com.example.absent": "absent",+ })+ self.assertIn("Android's chooser", result.stdout)++ def test_restore_after_the_chooser_resolves_the_stock_launcher(self):+ # The same batch as on a TV where nothing answered HOME: no `pm enable android`, and Home goes+ # to whatever the stock launcher resolves to, never to the chooser.+ self.tv(home=CHOOSER_ANSWER)+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ self.clear_sent()+ result = self.run_script("restore.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(self.sent(), [+ "pm enable com.example.enabled",+ f"pm enable {STOCK}",+ "cmd package set-home-activity --user 0 $(cmd package resolve-activity --brief -a "+ f"android.intent.action.MAIN -c android.intent.category.HOME {STOCK} | tail -n 1)",+ "settings put global window_animation_scale 0.5",+ "settings delete global transition_animation_scale",+ "settings put global animator_duration_scale 1.0",+ "pm list packages -d",+ ])++ def test_a_second_run_after_the_chooser_keeps_the_record(self):+ self.tv(home=CHOOSER_ANSWER)+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ first = self.record()+ # The retry happens on a TV where the list has already been applied.+ self.tv(home=CHOOSER_ANSWER, installed=["com.example.already_off", STOCK],+ disabled=["com.example.enabled", "com.example.already_off"])+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("keeping the recovery record", result.stdout)+ self.assertEqual(self.record(), first)+ self.assertIn("pm disable-user --user 0 com.example.enabled", self.sent())+++class CheckHomeChooserTest(unittest.TestCase):+ # check.py reads Home through the same query_home, and these two pass with or without the fix:+ # a fix there instead of in save() would turn the first one into "Home is nothing" and exit 1 on+ # every cron run, and --fix would then move Home on a TV that only debloats.+ setUp = drift.DriftCheckTest.setUp+ write_list = drift.DriftCheckTest.write_list+ tv = drift.DriftCheckTest.tv+ run_check = drift.DriftCheckTest.run_check+ sent = drift.DriftCheckTest.sent++ def test_the_chooser_without_our_launcher_is_not_drift(self):+ self.write_list(["com.example.music", "com.example.store"])+ self.tv(installed=["com.example.music", "com.example.store", STOCK, "com.example.launcher"],+ disabled=["com.example.music", "com.example.store"], home=CHOOSER_ANSWER,+ home_activities=[f"{STOCK}/.MainActivity", "com.example.launcher/.Home"])+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"nothing drifted: 2 listed packages are still disabled and Home is {CHOOSER}",+ result.stdout)+ self.assertEqual(self.sent(), [])++ def test_the_chooser_with_our_launcher_is_drift_by_name(self):+ self.tv(home=CHOOSER_ANSWER)+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"Home is {CHOOSER}, not {drift.CUSTOM}", result.stdout)+ self.assertEqual(self.sent(), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_recovery_old_chooser_record.py b/tests/test_recovery_old_chooser_record.pynew file mode 100644index 000000000..c63c29667--- /dev/null+++ b/tests/test_recovery_old_chooser_record.py@@ -0,0 +1,135 @@+"""tools/recovery.py reads a record that an older save() wrote with Android's HOME chooser in it.++Before save() learned to leave the chooser out (tests/test_recovery_home_chooser.py), disable.sh on a+TV whose Home had no default recorded "home": "android/com.android.internal.app.ResolverActivity"+and "android": "enabled" among the packages, and exited 0. A Chromecast with Google TV 4K (Google+TV 14, UTTC.250917.004) lists package:android in `pm list packages` and not in `pm list packages -d`,+so "enabled" is what such a TV got. load_record refused those records ("not a package name:+'android'"), and moving the file aside, the only way past that, loses the state the record exists+to keep: restore without a record enables every listed package, including the ones the owner had+disabled before cleanup (#239), and a new disable.sh run records the TV after cleanup as the+original. Everything else in such a record is right, so load_record now drops the chooser and its+one entry and reads the rest.++The first three tests fail without that and pass with it. The last one passes either way: it pins+that only the chooser's own entry is dropped, and that any other bad name is still refused.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import json+import shutil+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import test_recovery_home_chooser as chooser # noqa: E402+import test_recovery_record as records # noqa: E402++CHOOSER = chooser.CHOOSER+STOCK = chooser.STOCK+++class OldChooserRecordTest(unittest.TestCase):+ # Borrowed rather than inherited, so the tests of tests/test_recovery_record.py do not run a+ # second time under this class.+ setUp = records.RecoveryRecordTest.setUp+ write_list = records.RecoveryRecordTest.write_list+ tv = records.RecoveryRecordTest.tv+ run_script = records.RecoveryRecordTest.run_script+ record = records.RecoveryRecordTest.record+ sent = records.RecoveryRecordTest.sent+ clear_sent = records.RecoveryRecordTest.clear_sent++ def write_old_record(self, **edits):+ """The record the older save() left on a TV whose Home had no default, and its path."""+ self.tv(home=chooser.CHOOSER_ANSWER)+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ path = next((self.home / ".cleanyourtv").glob("recovery-*.json"))+ record = json.loads(path.read_text())+ record["home"] = CHOOSER+ record["packages"]["android"] = "enabled"+ record.update(edits)+ path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n")+ self.clear_sent()+ return path++ def test_restore_replays_an_old_record_without_the_chooser(self):+ path = self.write_old_record()+ before = path.read_bytes()+ result = self.run_script("restore.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ # The batch a record written by the fixed save() gives: no `pm enable android`, Home goes to+ # what the stock launcher resolves to, and the package that was off before cleanup stays off.+ self.assertEqual(self.sent(), [+ "pm enable com.example.enabled",+ f"pm enable {STOCK}",+ "cmd package set-home-activity --user 0 $(cmd package resolve-activity --brief -a "+ f"android.intent.action.MAIN -c android.intent.category.HOME {STOCK} | tail -n 1)",+ "settings put global window_animation_scale 0.5",+ "settings delete global transition_animation_scale",+ "settings put global animator_duration_scale 1.0",+ "pm list packages -d",+ ])+ self.assertIn("leaving com.example.already_off alone", result.stderr)+ self.assertIn(f"the recorded Home is Android's chooser ({CHOOSER})", result.stderr)+ self.assertEqual(path.read_bytes(), before, "restore reads the record, it does not rewrite it")++ def test_disable_runs_again_on_an_old_record_and_keeps_it(self):+ path = self.write_old_record()+ before = path.read_bytes()+ # The retry happens on a TV where the list has already been applied.+ self.tv(home=chooser.CHOOSER_ANSWER, installed=["com.example.already_off", STOCK],+ disabled=["com.example.enabled", "com.example.already_off"])+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("keeping the recovery record", result.stdout)+ self.assertEqual(path.read_bytes(), before, "nothing was added, so the file is not rewritten")+ self.assertIn("pm disable-user --user 0 com.example.enabled", self.sent())++ def test_a_list_that_gained_names_writes_the_old_record_back_without_the_chooser(self):+ path = self.write_old_record()+ first = json.loads(path.read_text())+ self.write_list(["com.example.enabled", "com.example.already_off", "com.example.absent",+ "com.example.added_later"])+ self.tv(home=chooser.CHOOSER_ANSWER,+ installed=["com.example.already_off", "com.example.added_later", STOCK],+ disabled=["com.example.enabled", "com.example.already_off"])+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ record = self.record()+ self.assertIsNone(record["home"])+ # The entries from before cleanup are kept as they were, not the TV as it is now.+ self.assertEqual(record["packages"], {+ "com.example.enabled": "enabled",+ "com.example.already_off": "disabled",+ "com.example.absent": "absent",+ "com.example.added_later": "enabled",+ })+ self.assertEqual(record["created"], first["created"])+ self.assertEqual(record["settings"], first["settings"])++ def test_only_the_chooser_entry_is_dropped(self):+ # "android" with a launcher as Home is no chooser record, and a chooser record that holds+ # another bad name is not one the old save() wrote: both are refused as before, and the file+ # and the TV are left alone.+ cases = {+ "android without the chooser": dict(home=records.STOCK_HOME),+ "another bad name": dict(packages={"com.example.enabled": "enabled", "android": "enabled",+ "com.example.x; reboot #": "enabled"}),+ }+ for case, edits in cases.items():+ for script in ("restore.sh", "disable.sh"):+ with self.subTest(case=case, script=script):+ shutil.rmtree(self.home / ".cleanyourtv", ignore_errors=True)+ path = self.write_old_record(**edits)+ before = path.read_bytes()+ result = self.run_script(script, str(self.list_path))+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("not a usable recovery record (not a package name", result.stderr)+ self.assertEqual(self.sent(), [], "nothing reached the TV")+ self.assertEqual(path.read_bytes(), before, "the file is left for inspection")+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/recovery.py b/tools/recovery.pyindex 11d4eb8eb..8b95befa2 100644--- a/tools/recovery.py+++ b/tools/recovery.py@@ -75,6 +75,16 @@ def record_path(list_path, host):return Path.home() / ".cleanyourtv" / f"recovery-{tag}-{digest}.json"+def is_chooser(home):+ """Whether a Home component is Android's chooser rather than a launcher.++ When Home has no default, HOME resolves to android/com.android.internal.app.ResolverActivity+ (#85). Its package, "android", is not a package name a record can hold, and that is the test+ here: a launcher always has one.+ """+ return bool(home) and not PACKAGE_RE.fullmatch(home.split("/", 1)[0])++def load_record(path):try:with open(path) as f:@@ -85,6 +95,18 @@ def load_record(path):"replace the state recorded before the first change.")if record.get("version") != VERSION or not isinstance(record.get("packages"), dict):raise SystemExit(f"{path}: unknown recovery record format; move it aside deliberately.")+ # Records written before save() left the chooser out hold it as Home, and "android" among the+ # packages with it. Everything else in them is the TV before cleanup, and moving the file aside+ # would lose that: restore would then enable every listed package, and a new disable.sh run would+ # record the TV after cleanup as the original. So the chooser and that one entry are dropped here,+ # which reads the record the way save() writes it now. Any other bad name is still refused below,+ # and save() writes the record back this way only when the list has gained names.+ home = record.get("home")+ if isinstance(home, str) and HOME_RE.fullmatch(home) and is_chooser(home):+ record["packages"].pop(home.split("/", 1)[0], None)+ record["home"] = None+ sys.stderr.write(f"{path}: the recorded Home is Android's chooser ({home}), not a launcher; "+ "reading it as no Home, so undo resolves the stock launcher.\n")# The record is replayed on the TV's shell, so it gets the same checks as the list and the TV's# answers did when it was written: a hand-edited or damaged file stops here, before any command.for name, state in record["packages"].items():@@ -138,8 +160,11 @@ def query_home(dev):answer = shell(dev, "cmd package resolve-activity --brief -a android.intent.action.MAIN -c ""android.intent.category.HOME")candidate = answer.splitlines()[-1].strip() if answer else ""- # Android answers "android" (the chooser) when nothing handles HOME; that is not a component and- # must never be written into a set-home-activity command.+ # Only a component counts: "No activity found" when nothing handles HOME, or the shell's error on+ # firmware older than `cmd`, comes back as None. Android's chooser does pass, though: when Home has+ # no default the last line is android/com.android.internal.app.ResolverActivity (#85). check.py+ # reports that as the Home it found, and save() keeps it out of the record, because the chooser is+ # no launcher to put back and must never be written into a set-home-activity command.return candidate if HOME_RE.fullmatch(candidate) else None@@ -196,6 +221,14 @@ def save(list_path, host):finally:dev.close()+ # Android's chooser, android/com.android.internal.app.ResolverActivity, answers HOME when Home has+ # no default. Recorded, it would put "android" among the packages, which is not a package name a+ # record can hold. A Home whose package the record cannot hold is left out instead, and restore+ # then resolves the stock launcher, as it does when nothing answered HOME.+ chooser = home if is_chooser(home) else None+ if chooser:+ home = None+# The launcher that owns Home may not be in the list, but it is what undo has to put back.home_package = home.split("/", 1)[0] if home else Nonetargets = packages + ([home_package] if home_package and home_package not in packages else [])@@ -213,7 +246,11 @@ def save(list_path, host):already = sum(1 for state in record["packages"].values() if state == "disabled")print(f"recorded {len(record['packages'])} packages on {host} "f"({already} already disabled, left alone by undo) -> {path}")- print(f"HOME before: {home or 'no component answered'}")+ if chooser:+ print(f"HOME before: {chooser}, Android's chooser (Home has no default), so no Home was "+ "recorded")+ else:+ print(f"HOME before: {home or 'no component answered'}")print("undo with tools/restore.sh <same list>; keep this file, it is the only copy.")return 0