Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools/relay.py: reach the TV from an assistant whose sandbox can't

sim5f2b2c2a847a
diff --git a/PROMPT.md b/PROMPT.md
index a3766df22..badc3b5f5 100644
--- a/PROMPT.md
+++ b/PROMPT.md
@@ -25,6 +25,9 @@ Connect
macOS Local Network privacy blocking adb. Don't debug it: use the Python `adb-shell` package in a venv
as the ADB client instead. If its file push hangs on larger files, transfer files as base64 chunks
through the shell and verify the md5.
+- If your own commands can't reach the TV at all while it answers from an ordinary terminal (a sandbox that
+ blocks the local network), ask me to run `tools/relay.py <tv ip>` in a terminal and leave it running, then
+ use `TV_HOST=127.0.0.1 TV_PORT=15555` (`tools/relay.md`).
- If port 5555 stays closed, the TV may only offer Wireless debugging (Google TV sets often do): look for
`_adb-tls-connect._tcp` with `dns-sd -B` or `adb mdns services`, ask me for the code and port under
Developer options > Wireless debugging > Pair device with pairing code, then `adb pair`, `adb connect`
diff --git a/README.md b/README.md
index 6226ebc37..2e87939ad 100644
--- a/README.md
+++ b/README.md
@@ -273,6 +273,7 @@ tools/theme.sh themes/aurora # push a theme; --r
|---|---|
| [`tools/tv.py`](tools/tv.py) | Pure-Python ADB client: shell, batch, push, pull. Works where the stock `adb` binary is blocked. |
| [`tools/b64push.py`](tools/b64push.py) | Uploads large files such as APKs in base64 chunks and verifies the checksum. |
+| [`tools/relay.py`](tools/relay.py) | Forwards a local port to the TV's ADB port, for assistants whose sandbox can't reach your network. Listens on this computer only. [Guide](tools/relay.md). |
| [`tools/disable.sh`](tools/disable.sh), [`restore.sh`](tools/restore.sh) | Apply or undo a debloat list, the undo from the state recorded before the change. |
| [`tools/recovery.py`](tools/recovery.py) | Writes the record `disable.sh` needs to undo itself, and prints the restore batch. |
| [`tools/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. |
diff --git a/tests/test_relay.py b/tests/test_relay.py
new file mode 100644
index 000000000..42ff5e1e1
--- /dev/null
+++ b/tests/test_relay.py
@@ -0,0 +1,123 @@
+"""tools/relay.py forwards bytes both ways, listens on loopback only, and says so when the TV is out of reach.
+
+A small echo server on this machine stands in for the TV, so the test needs no TV.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+from pathlib import Path
+import socket
+import subprocess
+import sys
+import threading
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def echo_server():
+ """A stand-in TV on 127.0.0.1: echoes whatever it receives. Returns its port."""
+ srv = socket.socket()
+ srv.bind(("127.0.0.1", 0))
+ srv.listen(4)
+
+ def run():
+ while True:
+ try:
+ conn, _ = srv.accept()
+ except OSError:
+ return
+ with conn:
+ while True:
+ data = conn.recv(65536)
+ if not data:
+ break
+ conn.sendall(data)
+
+ threading.Thread(target=run, daemon=True).start()
+ return srv
+
+
+def free_port():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+class RelayTest(unittest.TestCase):
+ def start_relay(self, tv_port, *extra):
+ proc = subprocess.Popen([sys.executable, str(ROOT / "tools" / "relay.py"), "127.0.0.1",
+ "--tv-port", str(tv_port), "--port", "0", *extra],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ # Cleanups run last-in first-out: kill, wait, then close the pipes.
+ self.addCleanup(proc.stderr.close)
+ self.addCleanup(proc.stdout.close)
+ self.addCleanup(proc.wait, 10)
+ self.addCleanup(proc.kill)
+ first = proc.stdout.readline()
+ if not first.startswith("relay 127.0.0.1:"):
+ proc.kill() # stderr is only complete once the relay has exited
+ self.fail(first + proc.stderr.read())
+ port = int(first.split()[1].split(":")[1])
+ self.assertIn(f"TV_HOST=127.0.0.1 TV_PORT={port}", proc.stdout.readline())
+ return proc, port
+
+ def test_bytes_go_both_ways(self):
+ tv = echo_server()
+ self.addCleanup(tv.close)
+ _, port = self.start_relay(tv.getsockname()[1])
+ payload = b"CNXN\x00\x00\x00\x01" + bytes(range(256)) * 400 # bigger than one recv
+ with socket.create_connection(("127.0.0.1", port), timeout=10) as c:
+ # Send from a thread while reading here: the echo comes back while we are still sending, and a
+ # single sendall would fill the buffers on the way back and never finish.
+ threading.Thread(target=c.sendall, args=(payload,), daemon=True).start()
+ got = b""
+ while len(got) < len(payload):
+ chunk = c.recv(65536)
+ if not chunk:
+ break
+ got += chunk
+ self.assertEqual(got, payload)
+
+ def test_listens_on_loopback_only(self):
+ tv = echo_server()
+ self.addCleanup(tv.close)
+ _, port = self.start_relay(tv.getsockname()[1])
+ # This machine's address on the network (no packet is sent to 192.0.2.1, a documentation address).
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
+ try:
+ probe.connect(("192.0.2.1", 9))
+ lan = probe.getsockname()[0]
+ except OSError:
+ self.skipTest("no network interface besides loopback")
+ if lan.startswith("127."):
+ self.skipTest("no network interface besides loopback")
+ with self.assertRaises(OSError):
+ socket.create_connection((lan, port), timeout=3).close()
+
+ def test_an_unreachable_tv_closes_the_client_and_says_why(self):
+ proc, port = self.start_relay(free_port()) # nothing listens there
+ with socket.create_connection(("127.0.0.1", port), timeout=10) as c:
+ c.settimeout(15)
+ self.assertEqual(c.recv(16), b"")
+ self.assertIn("cannot reach 127.0.0.1:", proc.stdout.readline())
+
+ def test_a_port_already_in_use_is_reported(self):
+ with socket.socket() as taken:
+ taken.bind(("127.0.0.1", 0))
+ taken.listen(1)
+ result = subprocess.run([sys.executable, str(ROOT / "tools" / "relay.py"), "192.0.2.1",
+ "--port", str(taken.getsockname()[1])],
+ capture_output=True, text=True, timeout=30)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Is a relay already running?", result.stderr)
+
+ def test_pointing_the_relay_at_itself_is_refused(self):
+ result = subprocess.run([sys.executable, str(ROOT / "tools" / "relay.py"), "127.0.0.1",
+ "--tv-port", "15555", "--port", "15555"], capture_output=True, text=True, timeout=30)
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("the relay itself", result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/relay.md b/tools/relay.md
new file mode 100644
index 000000000..2f13a5856
--- /dev/null
+++ b/tools/relay.md
@@ -0,0 +1,38 @@
+# tools/relay.py
+
+Forwards a port on this computer to the TV's ADB port. Use it when your coding assistant runs its commands in
+a sandbox that can reach this computer but not other devices on your network. Claude Code on macOS is the
+usual case: Local Network privacy blocks its sandbox, so `tools/tv.py` times out or says "No route to host"
+even though the TV answers from an ordinary terminal.
+
+```bash
+# In an ordinary terminal (Terminal, iTerm, VS Code), and leave it running:
+tools/venv/bin/python -I tools/relay.py 192.168.1.50
+
+# Then, wherever the assistant runs the tools:
+export TV_HOST=127.0.0.1 TV_PORT=15555
+tools/venv/bin/python -I tools/tv.py --probe
+```
+
+- **Options:** `--tv-port` if the TV's ADB port isn't 5555; `--port` for another local port (run one relay
+ per TV, each on its own port). The TV's address defaults to `$TV_HOST`.
+- **It prints the `TV_HOST`/`TV_PORT` to use**, and one line each time it can't reach the TV.
+- **Stop it with Ctrl-C** when you're done.
+
+## Safety
+
+- **It listens on `127.0.0.1` only**, never on your network, and has no option to change that. Other
+ devices can't use it to reach your TV.
+- **Programs on this computer can reach the TV's ADB port through it while it runs.** ADB still needs a key
+ the TV has accepted ("Allow USB debugging?"), but stop the relay when you're done, as you'd close network
+ ADB itself.
+
+## When it fails
+
+- **"cannot reach 192.168.1.50:5555"**, printed by the relay: the TV is off or in standby (some TVs drop off
+ the network), on another network, or network debugging was switched off. The tools then see the connection
+ reset by peer.
+- **"cannot listen on 127.0.0.1:15555"**: a relay is already running on that port. Use it, or pick another
+ `--port`.
+- **"that is the relay itself"**: the TV's address was given as `127.0.0.1` with the relay's own port. Give
+ the TV's IP address.
diff --git a/tools/relay.py b/tools/relay.py
new file mode 100644
index 000000000..ae938a137
--- /dev/null
+++ b/tools/relay.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+"""Forward a port on this computer to the TV's ADB port, for assistants whose sandbox can't reach the network.
+
+Some coding assistants run their commands in a sandbox that may talk to this computer but not to other devices
+on the local network (Claude Code on macOS, where Local Network privacy blocks it). Run this in an ordinary
+terminal, then point the tools at it:
+
+ tools/venv/bin/python -I tools/relay.py 192.168.1.50 # leave it running
+ TV_HOST=127.0.0.1 TV_PORT=15555 tools/venv/bin/python -I tools/tv.py --probe
+
+Usage: relay.py [TV_HOST] [--tv-port 5555] [--port 15555]
+It listens on 127.0.0.1 only, never on the network. Read tools/relay.md first.
+"""
+import argparse
+import os
+import socket
+import sys
+import threading
+
+LISTEN = "127.0.0.1" # loopback only: the relay must never put the TV's ADB port on the network
+
+
+def pipe(src, dst):
+ """Copy one direction until either side closes, then close both directions."""
+ try:
+ while True:
+ data = src.recv(65536)
+ if not data:
+ break
+ dst.sendall(data)
+ except OSError:
+ pass
+ finally:
+ for s in (src, dst):
+ try:
+ s.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+
+
+def serve(srv, tv_host, tv_port):
+ while True:
+ client, _ = srv.accept()
+ try:
+ tv = socket.create_connection((tv_host, tv_port), timeout=10)
+ tv.settimeout(None)
+ except OSError as e:
+ print(f"cannot reach {tv_host}:{tv_port}: {e} (is the TV on, and network debugging still on?)",
+ flush=True)
+ client.close()
+ continue
+ for a, b in ((client, tv), (tv, client)):
+ threading.Thread(target=pipe, args=(a, b), daemon=True).start()
+
+
+def main():
+ p = argparse.ArgumentParser(description="Forward 127.0.0.1:PORT to the TV's ADB port. See tools/relay.md.")
+ p.add_argument("tv_host", nargs="?", default=os.environ.get("TV_HOST"),
+ help="the TV's IP address (default: $TV_HOST)")
+ p.add_argument("--tv-port", type=int, default=5555, help="the TV's ADB port (default 5555)")
+ p.add_argument("--port", type=int, default=15555, help="local port to listen on (default 15555; 0 picks one)")
+ args = p.parse_args()
+ if not args.tv_host:
+ p.error("give the TV's IP address, e.g. tools/relay.py 192.168.1.50")
+ if args.tv_host in ("127.0.0.1", "localhost") and args.tv_port == args.port:
+ p.error("that is the relay itself: give the TV's IP address")
+
+ srv = socket.socket()
+ srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ srv.bind((LISTEN, args.port))
+ except OSError as e:
+ sys.exit(f"cannot listen on {LISTEN}:{args.port}: {e}. Is a relay already running? Pick another --port.")
+ srv.listen(8)
+ port = srv.getsockname()[1]
+ print(f"relay {LISTEN}:{port} -> {args.tv_host}:{args.tv_port}", flush=True)
+ print(f"use TV_HOST={LISTEN} TV_PORT={port} with tools/tv.py and the other tools; Ctrl-C stops it", flush=True)
+ try:
+ serve(srv, args.tv_host, args.tv_port)
+ except KeyboardInterrupt:
+ print("relay stopped", flush=True)
+ finally:
+ srv.close()
+
+
+if __name__ == "__main__":
+ main()