#!/usr/bin/env python3
"""ROS2Lab "Try it on your PC" bridge v3: the www.ros2lab.com page runs real `ros2` commands for turtlesim on THIS computer.

Runs inside the ros2lab-try pixi environment (ROS 2 Jazzy from RoboStack), started by try.sh / try-mac.sh / try.ps1.
Standard library + rclpy only. Source: https://www.ros2lab.com/install/try/ros2lab-try.py.
STATUS: tested on Ubuntu 24.04; not yet run on a real Windows PC or Mac.

Default (v3): the RELAY. This bridge opens no port. It connects OUT to the ROS2Lab relay (Firebase Realtime Database, signed in
anonymously), makes a random 256-bit secret, and opens your browser at https://www.ros2lab.com/pc#s=<secret>. The part after # is
never sent to any server; the relay only sees SHA-256(secret) as the room name. A 6-character code (XXX-XXX, once, 10 minutes)
is printed for another browser. One browser at a time; the terminal prints who connected. Ctrl+C deletes the room.
Page -> bridge messages arrive in rooms/<room>/in, bridge -> page messages go to rooms/<room>/out, turtles to rooms/<room>/state.
The relay is only a pipe: the grammar below is checked HERE, on this PC.

--direct (or when the relay cannot be reached): bridge v2's local server, below.
- Listens on 127.0.0.1 only: nothing outside this computer can reach it.
- Every request: the Host header must be 127.0.0.1:7777 or localhost:7777 (stops DNS rebinding) and the Origin must be exactly
  https://www.ros2lab.com, https://ros2lab.com or this bridge's own page (plus ROS2LAB_DEV_ORIGIN when you set it).
- A page must first type the 6-digit pairing code printed in YOUR terminal; it then gets a token that dies with the bridge.
- NO SHELL, ever: each line is split with shlex and checked word by word against a fixed grammar of turtlesim lesson commands,
  then run as an argument list (shell=False). At most 4 commands at once; 20 s for one-shot commands, 10 min for long ones.

Protocol (the contract with the page):
  GET  /hello  -> {"ros2lab":"try-2.0","os":"linux|mac|windows","distro":"jazzy","turtlesim":bool,"pair":true,"ws":"/ws"}
  POST /pair {"code":"123456"} -> {"token":"<64 hex>"} | 403 {"error":"wrong code"}
  GET  /ws?token=T  (WebSocket; no token needed from this bridge's own page)
    page -> bridge: {"t":"run","id":N,"tab":K,"line":"..."} {"t":"sig","id":N,"sig":"INT"} {"t":"key","k":"up|down|left|right|stop"}
                    {"t":"complete","id":N,"line":"..."}
    bridge -> page: {"t":"out","id":N,"s":"o|e","d":"..."} {"t":"exit","id":N,"code":0} {"t":"complete","id":N,"options":[...]}
                    {"t":"state","turtles":[{"name","x","y","theta","pen":{"r","g","b","w","off"}}],"bg":[r,g,b]} (20 Hz) {"t":"err","msg"}
  GET  /       -> the local console page (Safari/iOS, or no internet); GET /source -> this file.
"""
import signal, sys
if __name__ == "__main__": signal.signal(signal.SIGINT, lambda *_: sys.exit(0))   # Ctrl+C = a quiet exit, even during start-up
import base64, codecs, hashlib, hmac, json, os, re, secrets, shlex, shutil, struct, subprocess, threading, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

VERSION = "try-3.0"
PORT = int(os.environ.get("ROS2LAB_TRY_PORT", "7777"))
DEV_ORIGIN = os.environ.get("ROS2LAB_DEV_ORIGIN", "").rstrip("/")
SELF_ORIGINS = {f"http://127.0.0.1:{PORT}", f"http://localhost:{PORT}"}
ORIGINS = {"https://www.ros2lab.com", "https://ros2lab.com"} | SELF_ORIGINS | ({DEV_ORIGIN} if DEV_ORIGIN else set())
HOSTS = {f"127.0.0.1:{PORT}", f"localhost:{PORT}"}
OS = "windows" if os.name == "nt" else "mac" if sys.platform == "darwin" else "linux"
TRY = os.path.dirname(os.path.abspath(__file__))
BAGS = os.path.join(TRY, "bags")
IDLE = float(os.environ.get("ROS2LAB_TRY_IDLE", "3600"))     # seconds with no page connected -> exit
RESTART = os.environ.get("ROS2LAB_TRY_CMD", "the same try command as before")
MAX_PROCS, ONE_SHOT, LONG, CAP, MAX_SIMS = 4, 20, 600, 65536, 2
NOT_ALLOWED = "not allowed here: only ros2 commands for turtlesim"
DEFAULT_PEN = {"r": 179, "g": 184, "b": 255, "w": 3, "off": False}   # turtlesim turtle.cpp DEFAULT_PEN_R/G/B (0xb3,0xb8,0xff), width 3
DEFAULT_BG = [69, 86, 255]                                            # turtlesim parameters background_r/g/b defaults
# the console module V72 publishes (public/js/lab/pc-console-2.js, hash = pc-console-2.sri.txt); a new version = new name + hash
# (pc-console-1.js stays served unchanged for v2 bridges)
CONSOLE_URL = "https://www.ros2lab.com/js/lab/pc-console-2.js"
CONSOLE_SRI = "sha384-yfRClJU+oiPSm0d18es0cHaGcVIWuMVqQc81vnqsBfYnuJsvlgWOgUfshUYDEFeA"
if DEV_ORIGIN:   # dev only (you set ROS2LAB_DEV_ORIGIN yourself): test another console module
    CONSOLE_URL = os.environ.get("ROS2LAB_CONSOLE_URL", CONSOLE_URL); CONSOLE_SRI = os.environ.get("ROS2LAB_CONSOLE_SRI", CONSOLE_SRI)

# ---------------------------------------------------------------- log: <try>/bridge.log, at most 20 lines/s, never a code or token
_log_lock = threading.Lock(); _log_win = [0.0, 0, 0]   # window start, lines in window, dropped
LOG_ON = os.path.isdir(os.path.join(TRY, ".pixi")) or os.environ.get("ROS2LAB_TRY_LOG") == "1"   # never next to the site copy in public/
def log(msg):
    if not LOG_ON: return
    with _log_lock:
        now = time.time()
        if now - _log_win[0] >= 1: dropped = _log_win[2]; _log_win[:] = [now, 0, 0]
        else: dropped = 0
        if _log_win[1] >= 20: _log_win[2] += 1; return
        _log_win[1] += 1
        try:
            with open(os.path.join(TRY, "bridge.log"), "a", encoding="utf-8") as f:
                if dropped: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} ({dropped} log lines dropped: more than 20/s)\n")
                f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg[:300]!s}\n")
        except OSError: pass
def say(msg): print(msg, flush=True)

# ---------------------------------------------------------------- the grammar: every word is checked, nothing reaches a shell
NAME = re.compile(r"/[A-Za-z0-9_/]+"); TYPE = re.compile(r"[A-Za-z0-9_]+/((msg|srv|action)/)?[A-Za-z0-9_]+")
PARAM = re.compile(r"[A-Za-z0-9_.]{1,100}"); PKG = re.compile(r"[A-Za-z0-9_]{1,100}"); WORD = re.compile(r"[A-Za-z0-9_.:-]{1,64}")
NUM = re.compile(r"-?[0-9]{1,9}(\.[0-9]{1,9})?"); BAGP = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_./-]{0,120}")
ROSNAME = re.compile(r"[A-Za-z0-9_/~]{1,100}"); PVAL = re.compile(r"[A-Za-z0-9_.\-]{1,64}")
def _text(a): return 0 < len(a) <= 2000 and not re.search(r"[\x00-\x1f\x7f]", a)   # a message / YAML / value: ONE argv element
CHECK = {"NAME": NAME.fullmatch, "TYPE": TYPE.fullmatch, "PARAM": PARAM.fullmatch, "PKG": PKG.fullmatch, "WORD": WORD.fullmatch,
         "N": NUM.fullmatch, "MSG": _text, "BAG": lambda a: bool(BAGP.fullmatch(a)) and ".." not in a.split("/")}
COMMON = {"-h": None, "--help": None, "-s": "N", "--spin-time": "N", "--use-sim-time": None, "--no-daemon": None}
QOS = {f"--qos-{k}": "WORD" for k in ("profile", "depth", "history", "reliability", "durability", "liveliness")} | {"--qos-depth": "N"}
def F(*no, **val): return {**{f: None for f in no}, **{k.replace("_", "-"): v for k, v in val.items()}}
# positional pattern ("?" optional, "+" one or more, "*" any) and flags (None = no value, else the value's check) per sub-command
GRAMMAR = {
    ("node", "list"): ([], F("-a", "--all", "-c", "--count-nodes")),
    ("node", "info"): (["NAME"], F("--include-hidden")),
    ("topic", "list"): ([], F("-t", "--show-types", "-c", "--count-topics", "--include-hidden-topics", "-v", "--verbose")),
    ("topic", "info"): (["NAME"], F("-v", "--verbose")),
    ("topic", "type"): (["NAME"], {}),
    ("topic", "find"): (["TYPE"], F("-c", "--count-topics", "--include-hidden-topics")),
    ("topic", "echo"): (["NAME", "TYPE?"], F("--once", "--csv", "--flow-style", "--full-length", "--no-arr", "--no-str", "--raw",
                         "--no-lost-messages", "-i", "--include-message-info", **{"--field": "PARAM", "-l": "N", "--truncate_length": "N",
                         "--timeout": "N"}) | QOS),
    ("topic", "hz"): (["NAME"], F("--wall-time", **{"-w": "N", "--window": "N"})),
    ("topic", "bw"): (["NAME"], {"-w": "N", "--window": "N"}),
    ("topic", "delay"): (["NAME"], {"-w": "N", "--window": "N"}),
    ("topic", "pub"): (["NAME", "TYPE", "MSG?"], F("-1", "--once", **{"-r": "N", "--rate": "N", "-t": "N", "--times": "N", "-p": "N",
                       "--print": "N", "-w": "N", "--wait_matching_subscriptions": "N", "--keep_alive": "N", "--max_wait_time_secs": "N",
                       "-n": "PKG", "--node_name": "PKG"}) | QOS),
    ("service", "list"): ([], F("-t", "--show-types", "-c", "--count-services", "--include-hidden-services")),
    ("service", "type"): (["NAME"], {}),
    ("service", "info"): (["NAME"], {}),
    ("service", "find"): (["TYPE"], F("-c", "--count-services", "--include-hidden-services")),
    ("service", "call"): (["NAME", "TYPE", "MSG?"], {"-r": "N", "--rate": "N"}),
    ("service", "echo"): (["NAME", "TYPE?"], F("--csv", "--flow-style", "--full-length", "--no-arr", "--no-str", **{"-l": "N"})),
    ("param", "list"): (["NAME?"], F("--param-type", "--include-hidden-nodes")),
    ("param", "get"): (["NAME", "PARAM"], F("--hide-type", "--include-hidden-nodes", **{"--timeout": "N"})),
    ("param", "set"): (["NAME", "PARAM", "MSG"], F("--include-hidden-nodes", **{"--timeout": "N"})),
    ("param", "describe"): (["NAME", "PARAM+"], F("--include-hidden-nodes", **{"--timeout": "N"})),
    ("param", "dump"): (["NAME"], F("--include-hidden-nodes", **{"--timeout": "N"})),
    ("param", "delete"): (["NAME", "PARAM+"], F("--include-hidden-nodes", **{"--timeout": "N"})),
    ("action", "list"): ([], F("-t", "--show-types", "-c", "--count-actions")),
    ("action", "info"): (["NAME"], F("-t", "--show-types", "-c", "--count")),
    ("action", "type"): (["NAME"], {}),
    ("action", "send_goal"): (["NAME", "TYPE", "MSG"], F("-f", "--feedback", **{"-t": "N", "--timeout": "N"})),
    ("interface", "list"): ([], F("-m", "-s", "-a", "--only-msgs", "--only-srvs", "--only-actions")),
    ("interface", "packages"): ([], F("-m", "-s", "-a", "--only-msgs", "--only-srvs", "--only-actions")),
    ("interface", "package"): (["PKG"], F("-m", "-s", "-a", "--only-msgs", "--only-srvs", "--only-actions")),
    ("interface", "show"): (["TYPE"], F("--all-comments", "--no-comments")),
    ("interface", "proto"): (["TYPE"], F("--no-quotes")),
    ("pkg", "list"): ([], {}),
    ("pkg", "executables"): (["PKG?"], F("--full-path")),
    ("pkg", "prefix"): (["PKG"], F("--share")),
    ("pkg", "xml"): (["PKG"], {"-t": "WORD", "--tag": "WORD"}),
    ("doctor", ""): ([], F("-r", "--report", "-rf", "--report-failed", "-iw", "--include-warnings")),
    ("bag", "record"): (["NAME*"], F("-a", "--all", "--all-topics", "--all-services", "--include-hidden-topics", "--start-paused",
                        "--disable-keyboard-controls", "--topics", **{"-o": "BAG", "--output": "BAG", "-d": "N", "--max-bag-duration": "N",
                        "-b": "N", "--max-bag-size": "N", "-s": "WORD", "--storage": "WORD"})),
    ("bag", "play"): (["BAG?"], F("-l", "--loop", "--start-paused", "--disable-keyboard-controls", "--topics",
                      **{"-i": "BAG", "--input": "BAG", "-r": "N", "--rate": "N", "-d": "N", "--delay": "N"})),
    ("bag", "info"): (["BAG"], F("-v", "--verbose", **{"-t": "NAME", "--topic-name": "NAME"})),
    ("bag", "list"): (["WORD"], F("-v", "--verbose")),
}
# the real Jazzy verb lists (`ros2 -h`, `ros2 <verb> -h`; tools/v68/verbs.py): a real verb we do not allow -> "not allowed here";
# a word that is no verb at all (a typo) goes to the real ros2 alone, so the learner sees the real argparse error
REAL_TOP = {"action", "bag", "component", "control", "daemon", "doctor", "interface", "launch", "lifecycle", "multicast", "node",
            "param", "pkg", "plugin", "run", "security", "service", "topic", "wtf", "extension_points", "extensions"}
REAL_SUBS = {"action": {"info", "list", "send_goal", "type"}, "bag": {"burst", "convert", "info", "list", "play", "record", "reindex"},
             "interface": {"list", "package", "packages", "proto", "show"}, "node": {"info", "list"},
             "param": {"delete", "describe", "dump", "get", "list", "load", "set"}, "pkg": {"create", "executables", "list", "prefix", "xml"},
             "service": {"call", "echo", "find", "info", "list", "type"}, "topic": {"bw", "delay", "echo", "find", "hz", "info", "list", "pub", "type"}}
VERBS = sorted(REAL_SUBS) + ["doctor", "run"]
TURTLESIM_EXES = {"draw_square", "mimic", "turtle_teleop_key", "turtlesim_node"}

def _ros_args(r):
    """--ros-args for `ros2 run turtlesim ...`: -r a:=b remaps and -p name:=value with plain names only."""
    i = 0
    while i < len(r):
        f = r[i]
        if f in ("-r", "--remap") and i + 1 < len(r):
            a, sep, b = r[i + 1].partition(":=")
            if not (sep and ROSNAME.fullmatch(a) and ROSNAME.fullmatch(b)): return False
        elif f in ("-p", "--param") and i + 1 < len(r):
            a, sep, b = r[i + 1].partition(":=")
            if not (sep and PARAM.fullmatch(a) and PVAL.fullmatch(b)): return False
        elif f == "--log-level" and i + 1 < len(r):
            if not WORD.fullmatch(r[i + 1]): return False
        else: return False
        i += 2
    return True

def installed_pkgs():
    p = os.environ.get("CONDA_PREFIX") or ""
    for d in (os.path.join(p, "share/ament_index/resource_index/packages"), os.path.join(p, "Library/share/ament_index/resource_index/packages")):
        if os.path.isdir(d): return set(os.listdir(d))
    return None

def classify(a):
    """a = shlex.split(line). Returns (kind, argv) or None. kind: "once" | "long" | "teleop" | "sim" | "bag-once" | "bag-long".
    argv is what runs after `ros2` (as a list, never a shell string)."""
    if not a or a[0] != "ros2" or len(a) > 40: return None
    r = a[1:]
    if not r or r in (["-h"], ["--help"]): return "once", r
    verb = "doctor" if r[0] == "wtf" else r[0]
    if verb not in VERBS:   # a typo of a verb -> real ros2 says "invalid choice"; a real but unused verb -> refused
        return ("once", [r[0]]) if re.fullmatch(r"[a-z_]{1,40}", r[0]) and r[0] not in REAL_TOP else None
    if verb == "run":
        if len(r) >= 2 and r[1:2] in (["-h"], ["--help"]) and len(r) == 2: return "once", r
        if len(r) < 3 or not PKG.fullmatch(r[1]) or not PKG.fullmatch(r[2]): return None
        pk = installed_pkgs()
        if r[1] != "turtlesim":   # a misspelt package -> the real "Package 'x' not found"
            return ("once", r[:3]) if len(r) == 3 and pk is not None and r[1] not in pk else None
        if r[2] not in TURTLESIM_EXES: return ("once", r[:3]) if len(r) == 3 else None   # real "No executable found"
        if len(r) > 3 and (r[3] != "--ros-args" or not _ros_args(r[4:])): return None
        return {"turtlesim_node": "sim", "turtle_teleop_key": "teleop"}.get(r[2], "long"), r   # mimic (V67 mission 8), draw_square
    if verb == "doctor": sub, rest = "", r[1:]
    else:
        if len(r) == 1 or r[1] in ("-h", "--help"): return ("once", r) if len(r) <= 2 else None
        sub, rest = r[1], r[2:]
        if (verb, sub) not in GRAMMAR:
            return ("once", r[:2]) if re.fullmatch(r"[a-z_]{1,40}", sub) and sub not in REAL_SUBS[verb] else None
    pos_pat, flags = GRAMMAR[(verb, sub)]; flags = {**COMMON, **flags}
    pos, i = [], 0
    while i < len(rest):
        t = rest[i]
        if t in flags:
            kind = flags[t]
            if kind:
                if i + 1 >= len(rest) or not CHECK[kind](rest[i + 1]): return None
                i += 1
            if t == "--topics":   # bag: the rest are topic names
                if not all(NAME.fullmatch(x) for x in rest[i + 1:]): return None
                pos += rest[i + 1:]; i = len(rest); continue
        elif t.startswith("-") and not NUM.fullmatch(t): return None
        else: pos.append(t)
        i += 1
    j = 0
    for p in pos_pat:   # match positionals against the pattern
        k, mult = p.rstrip("?+*"), p[-1] if p[-1] in "?+*" else ""
        take = []
        while j < len(pos) and CHECK[k](pos[j]) and (mult in ("+", "*") or not take): take.append(pos[j]); j += 1
        if not take and mult in ("", "+"): return None
    if j != len(pos): return None
    if verb == "bag":   # bag paths (BAG check: relative, no ..) run with cwd <try>/bags, so they stay inside it
        return ("bag-long" if sub in ("record", "play") else "bag-once"), r
    longrun = (verb, sub) in (("topic", "hz"), ("topic", "bw"), ("topic", "delay"), ("service", "echo"))
    longrun |= (verb, sub) == ("topic", "echo") and "--once" not in rest
    longrun |= (verb, sub) == ("topic", "pub") and not ({"-1", "--once", "-t", "--times"} & set(rest))
    longrun |= (verb, sub) == ("action", "send_goal")
    longrun |= verb == "doctor"   # its checks reach the network; seen > 20 s with no output on this PC (Ctrl+C still works)
    longrun |= (verb, sub) == ("service", "call") and bool({"-r", "--rate"} & set(rest))
    return ("long" if longrun else "once"), r

# ---------------------------------------------------------------- WebSocket (RFC 6455), server side, text frames only
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def ws_accept(key): return base64.b64encode(hashlib.sha1((key + WS_GUID).encode()).digest()).decode()
def ws_frame(data, opcode=1):
    n = len(data)
    head = bytes([0x80 | opcode]) + (bytes([n]) if n < 126 else bytes([126]) + struct.pack(">H", n) if n < 65536 else bytes([127]) + struct.pack(">Q", n))
    return head + data
def ws_read(rf, limit=65536):
    """One whole message -> (opcode, bytes); client frames must be masked; None when the socket closes."""
    buf, op = b"", None
    while True:
        h = rf.read(2)
        if len(h) < 2: return None
        fin, opcode, masked, n = h[0] & 0x80, h[0] & 0x0F, h[1] & 0x80, h[1] & 0x7F
        if not masked: return None
        if n == 126: n = struct.unpack(">H", rf.read(2))[0]
        elif n == 127: n = struct.unpack(">Q", rf.read(8))[0]
        if n > limit or len(buf) + n > limit: return None
        mask = rf.read(4); data = rf.read(n)
        if len(data) < n: return None
        data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
        if opcode >= 8: return opcode, data          # control frames are never fragmented
        if opcode: op = opcode
        buf += data
        if fin: return op, buf

# ---------------------------------------------------------------- shared state
LOCK = threading.Lock()
PAIR = {"code": None, "bad": 0}; TOKENS = set()
CLIENTS = set(); LAST_CLIENT = [time.time()]
PROCS = {}            # (client, id) -> Proc
SIMS = []             # turtlesim_node Popen objects (the first window included)
POSES, PENS = {}, {}  # turtle -> (x, y, theta, t), turtle -> pen dict
GRAPH = {"turtlesim": False, "bg": list(DEFAULT_BG), "topics": [], "nodes": [], "services": [], "actions": []}
STOPPING = threading.Event()
ROSQ = []             # work for the rclpy thread: ("pub", topic, lin, ang) | ("teleop", on)
ROS2 = None

def new_code(why):
    PAIR["code"] = f"{secrets.randbelow(10**6):06d}"; PAIR["bad"] = 0
    say(f"{why} - pairing code {PAIR['code'][:3]} {PAIR['code'][3:]}")
    log(f"new pairing code ({why})")

# Windows: ROS 2's logger cannot make its "latest" log symlink without a privilege and says so on every command (harmless)
WIN1314 = re.compile(r"[^\n]*\[WinError 1314\] A required privilege is not held[^\n]*\n?")
QT_FAIL = re.compile(r"could not load the Qt platform plugin|no Qt platform plugin could be initialized|could not connect to display", re.I)
def ansi_strip(s): return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07|\r(?!\n)", "", s)

def child_env():
    return dict(os.environ, PYTHONUNBUFFERED="1", RCUTILS_COLORIZED_OUTPUT="0", PYTHONIOENCODING="utf-8")

def popen(argv, cwd, pipes=True):
    kw = dict(cwd=cwd, env=child_env(), stdin=subprocess.DEVNULL)
    if pipes: kw.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if os.name == "nt": kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP   # so CTRL_BREAK_EVENT reaches only this command
    else: kw["start_new_session"] = True                                             # own process group, like a terminal job
    return subprocess.Popen(argv, **kw)

def interrupt(p):
    """Ctrl+C for a command: SIGINT to its process group (Windows: CTRL_BREAK_EVENT to its group); harder if it ignores it."""
    def esc():
        for wait, hard in ((5, False), (2, True)):
            try: p.wait(wait); return
            except subprocess.TimeoutExpired: pass
            try:
                if os.name == "nt": subprocess.run(["taskkill", "/T", "/F", "/PID", str(p.pid)], capture_output=True)
                else: os.killpg(p.pid, signal.SIGKILL if hard else signal.SIGTERM)
            except (OSError, ProcessLookupError): return
    if p.poll() is not None: return
    try:
        if os.name == "nt": p.send_signal(signal.CTRL_BREAK_EVENT)
        else: os.killpg(p.pid, signal.SIGINT)
    except (OSError, ProcessLookupError): return
    threading.Thread(target=esc, daemon=True).start()

class Client:
    def __init__(self, handler): self.h = handler; self.wlock = threading.Lock(); self.alive = True; self.teleop = None; self.times = []
    def send(self, obj):
        if not self.alive: return
        try:
            with self.wlock: self.h.wfile.write(ws_frame(json.dumps(obj, separators=(",", ":")).encode())); self.h.wfile.flush()
        except (OSError, ValueError): self.alive = False   # ValueError: the socket file was closed by now (would kill the broadcaster)

class Proc:
    def __init__(self, client, cid, kind, argv, line):
        self.c, self.id, self.kind, self.line, self.sent, self.cut, self.timed = client, cid, kind, line, 0, False, False
        cwd = BAGS if kind.startswith("bag") else TRY
        if cwd == BAGS: os.makedirs(BAGS, exist_ok=True)
        self.p = popen([ROS2, *argv], cwd)
        self.readers = [threading.Thread(target=self.read, args=(self.p.stdout, "o"), daemon=True),
                        threading.Thread(target=self.read, args=(self.p.stderr, "e"), daemon=True)]
        for t in self.readers: t.start()
        threading.Thread(target=self.wait, daemon=True).start()
    def read(self, pipe, s):
        dec = codecs.getincrementaldecoder("utf-8")("replace")
        while True:
            b = pipe.read1(4096) if hasattr(pipe, "read1") else os.read(pipe.fileno(), 4096)
            if not b: break
            d = WIN1314.sub("", ansi_strip(dec.decode(b)))
            if not d or self.cut: continue
            if self.sent + len(d) > CAP:
                d = d[:max(0, CAP - self.sent)] + "\n... (output cut at 64 KB; press Ctrl+C to stop the command)\n"; self.cut = True
            self.sent += len(d); self.c.send({"t": "out", "id": self.id, "s": s, "d": d})
    def wait(self):
        limit = LONG if self.kind in ("long", "sim", "bag-long") else ONE_SHOT
        try: self.p.wait(limit)
        except subprocess.TimeoutExpired:
            self.timed = True; interrupt(self.p); self.p.wait()
        for t in self.readers: t.join(5)
        rc = self.p.returncode
        if rc == 0: track_pen(self.line)   # before "exit": the page's next command (a teleport) must already draw with the new pen
        if self.timed: self.c.send({"t": "out", "id": self.id, "s": "e", "d": f"\n(stopped after {limit} s: the time limit for this command here)\n"})
        self.c.send({"t": "exit", "id": self.id, "code": rc if rc >= 0 else 128 - rc})
        with LOCK:
            PROCS.pop((self.c, self.id), None)
            if self.p in SIMS: SIMS.remove(self.p)
        log(f"exit {rc} id={self.id}")

def track_pen(line):
    """Pens are not on any topic: remember the set_pen / spawn / kill / reset calls made through this bridge."""
    try: a = shlex.split(line)
    except ValueError: return
    if a[1:3] != ["service", "call"] or len(a) < 4: return
    m = re.fullmatch(r"/([A-Za-z0-9_]+)/set_pen", a[3])
    with LOCK:
        if m and len(a) >= 6:
            try:
                import yaml
                v = yaml.safe_load(a[5]) or {}
                PENS[m.group(1)] = {"r": int(v.get("r", 0)), "g": int(v.get("g", 0)), "b": int(v.get("b", 0)),
                                    "w": int(v.get("width", 0)), "off": bool(v.get("off", 0))}
            except Exception: pass
        elif a[3] == "/reset": PENS.clear()
        elif a[3] == "/kill" and len(a) >= 6:
            try:
                import yaml
                PENS.pop(str((yaml.safe_load(a[5]) or {}).get("name", "")), None)
            except Exception: pass

TELEOP_BANNER = ("Reading from keyboard\n---------------------------\nUse arrow keys to move the turtle.\n"
                 "Use g|b|v|c|d|e|r|t keys to rotate to absolute orientations. 'f' to cancel a rotation.\n'q' to quit.\n")
KEYS = {"up": (2.0, 0.0), "down": (-2.0, 0.0), "left": (0.0, 2.0), "right": (0.0, -2.0), "stop": (0.0, 0.0)}   # teleop_turtle_key.cpp: l_scale_ = a_scale_ = 2.0

def run_line(c, cid, line):
    if not isinstance(line, str) or len(line) > 4000: c.send({"t": "out", "id": cid, "s": "e", "d": NOT_ALLOWED + "\n"}); c.send({"t": "exit", "id": cid, "code": 1}); return
    try: a = shlex.split(line, posix=True)
    except ValueError: a = None
    res = classify(a) if a is not None and "\n" not in line and "\r" not in line else None
    log(f"run id={cid} {'ok' if res else 'refused'}: {line[:200]!r}")
    if not res:
        # V74 persona 4: a line copied from a chat app has curly quotes or long dashes; say so (beginner hint after the error)
        tip = "  The line has curly quotes or a long dash (copied from a chat app?). Type plain \" and -- instead.\n" if re.search("[“”‘’–—]", line) else ""
        c.send({"t": "out", "id": cid, "s": "e", "d": NOT_ALLOWED + "\n" + tip}); c.send({"t": "exit", "id": cid, "code": 1}); return
    kind, argv = res
    if not ROS2: c.send({"t": "out", "id": cid, "s": "e", "d": "ros2 was not found: start this bridge with the try script\n"}); c.send({"t": "exit", "id": cid, "code": 127}); return
    if kind == "teleop":
        if c.teleop is not None: c.send({"t": "out", "id": cid, "s": "e", "d": "turtle_teleop_key is already running in another tab here\n"}); c.send({"t": "exit", "id": cid, "code": 1}); return
        topic = "/turtle1/cmd_vel"
        for i, x in enumerate(argv):
            if x in ("-r", "--remap") and i + 1 < len(argv) and argv[i + 1].split(":=")[0].lstrip("/") == "turtle1/cmd_vel":
                t = argv[i + 1].split(":=")[1]; topic = t if t.startswith("/") else "/" + t
        c.teleop = (cid, topic)
        with LOCK: ROSQ.append(("teleop", True))
        c.send({"t": "out", "id": cid, "s": "o", "d": TELEOP_BANNER}); return
    with LOCK:
        if (c, cid) in PROCS: c.send({"t": "err", "msg": f"id {cid} is already running"}); return
        if len(PROCS) >= MAX_PROCS:
            c.send({"t": "out", "id": cid, "s": "e", "d": f"busy: {MAX_PROCS} commands are already running here; stop one with Ctrl+C\n"}); c.send({"t": "exit", "id": cid, "code": 1}); return
        if kind == "sim" and len([s for s in SIMS if s.poll() is None]) >= MAX_SIMS:
            c.send({"t": "out", "id": cid, "s": "e", "d": f"at most {MAX_SIMS} turtlesim windows here; close one first\n"}); c.send({"t": "exit", "id": cid, "code": 1}); return
        try: pr = Proc(c, cid, kind, argv, line)
        except OSError as e: c.send({"t": "out", "id": cid, "s": "e", "d": f"could not start: {e}\n"}); c.send({"t": "exit", "id": cid, "code": 127}); return
        PROCS[(c, cid)] = pr
        if kind == "sim": SIMS.append(pr.p)

def complete(line):
    """Tab completion from the grammar and the live graph: the options for the last word."""
    words = line.split(" "); cur = words[-1]; prev = [w for w in words[:-1] if w]
    opts = []
    if not prev: opts = ["ros2"]
    elif prev == ["ros2"]: opts = VERBS
    elif len(prev) == 2 and prev[1] == "run": opts = ["turtlesim"]
    elif len(prev) == 3 and prev[1:3] == ["run", "turtlesim"]: opts = sorted(TURTLESIM_EXES)
    elif len(prev) == 2 and prev[1] in REAL_SUBS: opts = sorted(s for (v, s) in GRAMMAR if v == prev[1])
    elif len(prev) >= 3:
        v, s = prev[1], prev[2]; n = len(prev) - 3
        g = GRAPH
        if cur.startswith("-") and (v, s) in GRAMMAR: opts = sorted(GRAMMAR[(v, s)][1])
        elif n == 0:
            opts = {"topic": g["topics"], "service": g["services"], "action": g["actions"], "node": g["nodes"], "param": g["nodes"],
                    "interface": [], "bag": []}.get(v, [])
            opts = [x for x, _ in opts] if opts and isinstance(opts[0], tuple) else opts
        elif n == 1 and (v, s) in (("topic", "pub"), ("topic", "echo"), ("service", "call"), ("action", "send_goal")):
            src = {"topic": g["topics"], "service": g["services"], "action": g["actions"]}[v]
            opts = [t for name, types in src if name == prev[3] for t in types]
        elif n == 1 and v == "param" and s in ("get", "set", "describe", "delete"):
            opts = ["background_r", "background_g", "background_b", "holonomic", "use_sim_time"] if prev[3] == "/turtlesim" else []
    return sorted({o for o in opts if o.startswith(cur)})[:50]

# ---------------------------------------------------------------- rclpy: poses, background, teleop publisher (one hidden node)
def ros_thread():
    try:
        import rclpy
        from rclpy.node import Node
        from turtlesim.msg import Pose
        from geometry_msgs.msg import Twist
        from rcl_interfaces.msg import ParameterEvent
    except ImportError as e:
        say(f"  (no rclpy here: the page gets no turtle positions: {e})"); return
    try:   # rclpy's own SIGINT/SIGTERM handlers would only stop ROS and leave the server holding the port (seen in V64)
        from rclpy.signals import SignalHandlerOptions
        rclpy.init(signal_handler_options=SignalHandlerOptions.NO)
    except ImportError: rclpy.init()
    node = Node("_ros2lab_try_bridge")   # a leading _ keeps it out of `ros2 node list`
    from rclpy.executors import SingleThreadedExecutor
    ex = SingleThreadedExecutor(); ex.add_node(node)
    subs, pubs, tele = {}, {}, {"node": None}
    def on_param(ev):
        if ev.node != "/turtlesim": return
        for p in list(ev.new_parameters) + list(ev.changed_parameters):
            k = {"background_r": 0, "background_g": 1, "background_b": 2}.get(p.name)
            if k is not None and p.value.type == 2: GRAPH["bg"][k] = int(p.value.integer_value)
    node.create_subscription(ParameterEvent, "/parameter_events", on_param, 50)
    def fetch_bg():
        try:
            from rclpy.parameter_client import AsyncParameterClient
            cl = AsyncParameterClient(node, "/turtlesim")
            fut = cl.get_parameters(["background_r", "background_g", "background_b"])
            def done(f):
                try:
                    vals = f.result().values
                    if len(vals) == 3 and all(v.type == 2 for v in vals): GRAPH["bg"] = [int(v.integer_value) for v in vals]
                except Exception: pass
            fut.add_done_callback(done)
        except Exception: pass
    def scan():
        names = [("/" + ns.strip("/") + "/" + n).replace("//", "/") for n, ns in node.get_node_names_and_namespaces() if not n.startswith("_")]
        had = GRAPH["turtlesim"]; GRAPH["turtlesim"] = "/turtlesim" in names; GRAPH["nodes"] = sorted(names)
        if GRAPH["turtlesim"] and not had: GRAPH["bg"] = list(DEFAULT_BG); fetch_bg()
        tt = node.get_topic_names_and_types(); GRAPH["topics"] = tt
        GRAPH["services"] = node.get_service_names_and_types()
        GRAPH["actions"] = sorted({(t[:-len("/_action/status")], ()) for t, _ in tt if t.endswith("/_action/status")})
        for topic, types in tt:
            m = re.fullmatch(r"/([A-Za-z0-9_]+)/pose", topic)
            if m and "turtlesim/msg/Pose" in types and topic not in subs:
                subs[topic] = node.create_subscription(Pose, topic, lambda msg, n=m.group(1): POSES.__setitem__(n, (msg.x, msg.y, msg.theta, time.time())), 10)
    def work():   # 20 Hz: run what the WebSocket threads asked for
        with LOCK: q = ROSQ[:]; ROSQ.clear()
        for item in q:
            if item[0] == "teleop":
                on = any(c.teleop for c in list(CLIENTS))
                if on and tele["node"] is None: tele["node"] = Node("teleop_turtle"); ex.add_node(tele["node"])   # the real teleop's node name
                elif not on and tele["node"] is not None:
                    ex.remove_node(tele["node"]); tele["node"].destroy_node(); tele["node"] = None; pubs.clear()
            elif item[0] == "pub" and tele["node"] is not None:
                topic = item[1]
                if topic not in pubs: pubs[topic] = tele["node"].create_publisher(Twist, topic, 1)
                msg = Twist(); msg.linear.x, msg.angular.z = item[2], item[3]; pubs[topic].publish(msg)
    node.create_timer(1.0, scan); node.create_timer(0.05, work); scan()
    try: ex.spin()
    except Exception: pass

def state():
    now = time.time()
    with LOCK:
        live = sorted(n for n, p in POSES.items() if now - p[3] < 1.0)
        return {"t": "state", "bg": list(GRAPH["bg"]), "turtles": [{"name": n, "x": round(POSES[n][0], 4), "y": round(POSES[n][1], 4),
                "theta": round(POSES[n][2], 4), "pen": dict(PENS.get(n, DEFAULT_PEN))} for n in live]}

def broadcaster():
    while True:
        t0 = time.time()
        if CLIENTS:
            s = state()
            for c in list(CLIENTS): c.send(s)
        time.sleep(max(0.0, 0.05 - (time.time() - t0)))

# ---------------------------------------------------------------- the local console page (Safari/iOS path; works offline too)
CONSOLE_JS = r"""
const URL_ = document.body.dataset.mod, SRI = document.body.dataset.sri, el = document.getElementById('app');
function fallback(why) {
  document.getElementById('note').textContent = 'Simple console (' + why + ').';
  const log = document.getElementById('log'), inp = document.getElementById('in'), st = document.getElementById('state');
  const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws');
  let id = 0, cur = null, hist = [], hi = 0;
  const add = (t, cls) => { const s = document.createElement('span'); s.textContent = t; if (cls) s.className = cls; log.append(s); log.scrollTop = log.scrollHeight; };
  ws.onopen = () => add('Connected to ROS 2 on this PC. Type a ros2 command for turtlesim.\n', 'm');
  ws.onclose = () => add('\nDisconnected: is the bridge still running in your terminal?\n', 'e');
  ws.onmessage = ev => { const m = JSON.parse(ev.data);
    if (m.t === 'out') add(m.d, m.s === 'e' ? 'e' : '');
    else if (m.t === 'exit') { if (m.id === cur) cur = null; }
    else if (m.t === 'err') add(m.msg + '\n', 'e');
    else if (m.t === 'state') st.textContent = m.turtles.map(t => t.name + ': x ' + t.x.toFixed(2) + ' y ' + t.y.toFixed(2) + ' theta ' + t.theta.toFixed(2)).join('   ') || 'no turtle yet'; };
  const sig = () => { if (cur !== null) ws.send(JSON.stringify({ t: 'sig', id: cur, sig: 'INT' })); add('^C\n', 'm'); };
  inp.addEventListener('keydown', e => {
    if (e.key === 'Enter') { const line = inp.value.trim(); inp.value = ''; if (!line) return; hist.push(line); hi = hist.length;
      add('$ ' + line + '\n', 'm'); if (line === 'clear') { log.textContent = ''; return; }
      id += 1; cur = id; ws.send(JSON.stringify({ t: 'run', id, tab: 1, line })); }
    else if (e.key === 'c' && e.ctrlKey) { e.preventDefault(); sig(); }
    else if (e.key === 'ArrowUp' && hist.length) { e.preventDefault(); hi = Math.max(0, hi - 1); inp.value = hist[hi]; }
    else if (e.key === 'ArrowDown' && hist.length) { e.preventDefault(); hi = Math.min(hist.length, hi + 1); inp.value = hist[hi] || ''; } });
  document.getElementById('ctrlc').onclick = sig;
  for (const k of ['up', 'down', 'left', 'right', 'stop']) document.getElementById('k-' + k).onclick = () => ws.send(JSON.stringify({ t: 'key', k }));
  document.getElementById('simple').hidden = false; inp.focus();
}
(async () => {
  if (!SRI || SRI.includes('PLACEHOLDER')) return fallback('the full console is not published yet');
  try {
    const r = await fetch(URL_, { integrity: SRI, mode: 'cors' });   // fails if the file does not match its SRI hash
    if (!r.ok) throw new Error('HTTP ' + r.status);
    const mod = await import(URL_);
    const api = mod && mod.mount ? mod : window.ROS2LabPC;   // V67's bundle sets window.ROS2LabPC = { mount, version }
    await api.mount(el, { wsUrl: '/ws', sameOrigin: true });
    document.getElementById('note').textContent = '';
  } catch (e) { fallback('no internet or the full console could not load'); }
})();
"""
def console_page():
    imap = json.dumps({"imports": {}, "integrity": {CONSOLE_URL: CONSOLE_SRI}})
    h = lambda s: "'sha256-" + base64.b64encode(hashlib.sha256(s.encode()).digest()).decode() + "'"
    mod_origin = "/".join(CONSOLE_URL.split("/")[:3])
    html = f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ROS2Lab - ROS 2 on this PC</title><style>
body{{font:15px/1.4 system-ui,sans-serif;margin:0;padding:12px;background:#10141a;color:#e6e6e6}} a{{color:#8cc8ff}}
#log{{white-space:pre-wrap;font:13px/1.35 ui-monospace,Menlo,Consolas,monospace;background:#000;padding:8px;height:55vh;overflow:auto;margin:0}}
#in{{width:100%;box-sizing:border-box;font:14px ui-monospace,Menlo,Consolas,monospace;padding:8px;background:#000;color:#fff;border:1px solid #555}}
.e{{color:#ff8a80}} .m{{color:#9ccc65}} button{{font-size:15px;padding:6px 12px;margin:4px 4px 0 0}} #state{{font:12px ui-monospace,monospace;color:#aaa}}
</style><script type="importmap">{imap}</script></head>
<body data-mod="{CONSOLE_URL}" data-sri="{CONSOLE_SRI}"><h1 style="font-size:18px;margin:0 0 6px">ROS 2 on this PC <small>(ROS2Lab bridge {VERSION})</small></h1>
<p id="note" style="margin:0 0 6px">Loading the console...</p><div id="app"></div>
<div id="simple" hidden><pre id="log" role="log" aria-live="polite"></pre>
<label for="in">Command</label><input id="in" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" enterkeyhint="send" placeholder="ros2 node list">
<div><button id="ctrlc">Ctrl+C</button> Teleop keys: <button id="k-up">Up</button><button id="k-down">Down</button><button id="k-left">Left</button><button id="k-right">Right</button><button id="k-stop">Stop</button></div>
<p id="state">no turtle yet</p></div>
<p style="font-size:12px;color:#aaa">Only this PC can open this page. It talks to the ROS2Lab bridge running in your terminal.
Source: <a href="/source">/source</a> (same as https://www.ros2lab.com/install/try/ros2lab-try.py).</p>
<script type="module">{CONSOLE_JS}</script></body></html>"""
    csp = (f"default-src 'none'; script-src {h(imap)} {h(CONSOLE_JS)} {mod_origin}; connect-src 'self' ws://127.0.0.1:{PORT} ws://localhost:{PORT} {mod_origin}; "
           f"style-src 'unsafe-inline' {mod_origin}; img-src 'self' data: {mod_origin}; font-src {mod_origin}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
    return html.encode(), csp

# ---------------------------------------------------------------- HTTP + WebSocket handler
class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    def _origin_ok(self, need):
        """Host must be exactly ours (DNS rebinding); Origin must be on the list. Origin "null" is always refused; a missing
        Origin only for plain GETs (a browser always sends one on POST and WebSocket, and no CORS header goes back)."""
        if self.headers.get("Host") not in HOSTS: return False
        o = self.headers.get("Origin")
        if o is None: return not need
        return o in ORIGINS
    def _send(self, code, body=b"", ctype="application/json", extra=()):
        self.send_response(code); o = self.headers.get("Origin")
        if o in ORIGINS: self.send_header("Access-Control-Allow-Origin", o); self.send_header("Vary", "Origin")
        self.send_header("Access-Control-Allow-Headers", "Content-Type"); self.send_header("Access-Control-Allow-Methods", "GET, POST")
        self.send_header("Access-Control-Allow-Private-Network", "true")
        self.send_header("Content-Type", ctype); self.send_header("Cache-Control", "no-store"); self.send_header("X-Content-Type-Options", "nosniff")
        for k, v in extra: self.send_header(k, v)
        self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
    def _json(self, obj, code=200): self._send(code, json.dumps(obj).encode())
    def _refuse(self):
        log(f"refused {self.command} {self.path[:60]!r} Host={self.headers.get('Host')!r} Origin={self.headers.get('Origin')!r}")
        self.send_response(403); self.send_header("Content-Length", "0"); self.end_headers()
    def do_OPTIONS(self):
        if not self._origin_ok(True): return self._refuse()
        self._send(204)
    def do_GET(self):
        path = urlsplit(self.path).path
        if path == "/ws": return self.websocket()
        if not self._origin_ok(False): return self._refuse()
        if path == "/hello": self._json({"ros2lab": VERSION, "os": OS, "distro": "jazzy", "turtlesim": bool(GRAPH["turtlesim"]), "pair": True, "ws": "/ws"})
        elif path == "/":
            body, csp = console_page()
            self._send(200, body, "text/html; charset=utf-8", [("Content-Security-Policy", csp), ("Referrer-Policy", "no-referrer")])
        elif path == "/source":
            with open(os.path.abspath(__file__), "rb") as f: self._send(200, f.read(), "text/plain; charset=utf-8")
        else: self._json({"error": "not found"}, 404)
    def do_POST(self):
        if not self._origin_ok(True): return self._refuse()
        if urlsplit(self.path).path != "/pair": return self._json({"error": "not found"}, 404)
        try:
            n = int(self.headers.get("Content-Length", 0))
            if not 0 < n <= 1024: raise ValueError
            code = json.loads(self.rfile.read(n)).get("code")
            if not isinstance(code, str): raise ValueError
        except (ValueError, AttributeError): return self._json({"error": "send {\"code\": \"<6 digits>\"}"}, 400)
        code = code.replace(" ", "")
        with LOCK:
            good = hmac.compare_digest(code.encode(), PAIR["code"].encode())
            if good:
                tok = secrets.token_hex(32); TOKENS.add(tok)
            else:
                PAIR["bad"] += 1
                if PAIR["bad"] >= 5: new_code("5 wrong codes were tried: new")
        log(f"pair {'ok' if good else 'wrong code'} from {self.headers.get('Origin')}")
        if good: say("  A page is paired (it can now run turtlesim ros2 commands here).")
        self._json({"token": tok} if good else {"error": "wrong code"}, 200 if good else 403)
    def websocket(self):
        o = self.headers.get("Origin")
        if self.headers.get("Host") not in HOSTS or o not in ORIGINS: return self._refuse()
        tok = (parse_qs(urlsplit(self.path).query).get("token") or [""])[0]
        with LOCK: tok_ok = any(hmac.compare_digest(tok.encode(), t.encode()) for t in TOKENS)
        if o not in SELF_ORIGINS and not tok_ok:
            log("refused /ws: no valid token"); self.send_response(401); self.send_header("Content-Length", "0"); self.end_headers(); return
        key = self.headers.get("Sec-WebSocket-Key")
        if (self.headers.get("Upgrade") or "").lower() != "websocket" or not key: return self._json({"error": "WebSocket only"}, 400)
        self.send_response(101); self.send_header("Upgrade", "websocket"); self.send_header("Connection", "Upgrade")
        self.send_header("Sec-WebSocket-Accept", ws_accept(key)); self.end_headers(); self.wfile.flush()
        self.close_connection = True
        c = Client(self)
        with LOCK: CLIENTS.add(c)
        log(f"ws open from {o}")
        try: self.ws_loop(c)
        finally:
            client_gone(c); log("ws closed")
    def ws_loop(self, c):
        while True:
            try: m = ws_read(self.rfile)
            except OSError: return   # the page went away
            if m is None: return
            op, data = m
            if op == 8:
                with c.wlock: self.wfile.write(ws_frame(b"", 8)); self.wfile.flush()
                return
            if op == 9:
                with c.wlock: self.wfile.write(ws_frame(data, 10)); self.wfile.flush()
                continue
            if op != 1: continue
            try: msg = json.loads(data.decode("utf-8"))
            except (ValueError, UnicodeDecodeError): msg = None
            dispatch(c, msg)
    def log_message(self, *a): pass

def dispatch(c, msg):
    """One page -> bridge message (the same for the WebSocket and the relay)."""
    now = time.time(); c.times = [t for t in c.times if now - t < 1] + [now]
    if len(c.times) > 50: c.send({"t": "err", "msg": "too many messages (more than 50 a second)"}); return
    if not isinstance(msg, dict): c.send({"t": "err", "msg": "bad message"}); return
    t = msg.get("t"); cid = msg.get("id")
    if t in ("run", "sig", "complete") and not (isinstance(cid, int) and not isinstance(cid, bool) and 0 <= cid < 2**31):
        c.send({"t": "err", "msg": "id must be a whole number"}); return
    if t == "run": run_line(c, cid, msg.get("line"))
    elif t == "sig":
        if c.teleop and c.teleop[0] == cid:
            c.teleop = None
            with LOCK: ROSQ.append(("teleop", False))
            c.send({"t": "exit", "id": cid, "code": 0}); return
        with LOCK: pr = PROCS.get((c, cid))
        if pr: interrupt(pr.p)
    elif t == "key":
        k = msg.get("k")
        if k not in KEYS: c.send({"t": "err", "msg": "key must be up, down, left, right or stop"}); return
        if not c.teleop: c.send({"t": "err", "msg": "start ros2 run turtlesim turtle_teleop_key first"}); return
        with LOCK: ROSQ.append(("pub", c.teleop[1], *KEYS[k]))
    elif t == "complete": c.send({"t": "complete", "id": cid, "options": complete(str(msg.get("line", ""))[:400])})
    else: c.send({"t": "err", "msg": "unknown message"})

def client_gone(c):
    """A page closed (WebSocket) or left / was taken over (relay): its commands get Ctrl+C, like closing a terminal."""
    c.alive = False; had_teleop = c.teleop; c.teleop = None   # cleared first: the rclpy thread checks it
    with LOCK:
        CLIENTS.discard(c); LAST_CLIENT[0] = time.time()
        mine = [p for (cl, _), p in PROCS.items() if cl is c]
        if had_teleop: ROSQ.append(("teleop", False))
    for pr in mine: interrupt(pr.p)

class Server(ThreadingHTTPServer):
    allow_reuse_address = os.name != "nt"   # on Windows SO_REUSEADDR would let us take a port another program holds
    daemon_threads = True
    request_queue_size = 64                  # the default 5 drops bursts of page requests (seen in tests: 1 s SYN retries)
    def handle_error(self, request, client_address): log(f"request error: {sys.exc_info()[1]!r}")   # not a traceback in the user's terminal

# ---------------------------------------------------------------- the relay (bridge v3): OUTBOUND only, no port is opened on this PC
# Firebase Realtime Database REST + Anonymous Auth REST. The page and this bridge meet in rooms/<ROOM> where ROOM = SHA-256 of a
# secret that only this PC and the browser tab know (it travels in the link's #fragment, which browsers never send to a server).
import http.client, platform, urllib.parse, urllib.request
SITE = (os.environ.get("ROS2LAB_SITE") or "https://www.ros2lab.com").rstrip("/")   # where the page lives (tests: a local copy)
RELAY_DB = (os.environ.get("ROS2LAB_RELAY_DB") or "https://ros2lab-default-rtdb.asia-southeast1.firebasedatabase.app").rstrip("/")
RELAY_NS = os.environ.get("ROS2LAB_RELAY_NS", "")   # only the local emulator needs ?ns=
AUTH_URL = os.environ.get("ROS2LAB_AUTH_URL") or "https://identitytoolkit.googleapis.com/v1"
TOKEN_URL = os.environ.get("ROS2LAB_TOKEN_URL") or "https://securetoken.googleapis.com/v1"
CODE_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
# s: short code valid (the rules allow at most 10 min); no page heartbeat -> "Browser left" (tests set both shorter)
CODE_LIFE = min(600, int(os.environ.get("ROS2LAB_CODE_LIFE", "600"))); PAGE_GONE = float(os.environ.get("ROS2LAB_PAGE_GONE", "35"))
RELAY_FILE = os.path.join(TRY, ".relay.json")      # anonymous account + last room, so a crashed run's room is deleted next time
SV = {".sv": "timestamp"}

class RelayError(Exception): pass

def clean_label(s, n=40): return re.sub(r"[^A-Za-z0-9 .,()+/_-]", "", str(s))[:n].strip() or "a browser"   # never terminal escapes

def pc_label():
    if OS == "mac": return f"macOS {platform.mac_ver()[0]} Mac"
    if OS == "windows": return f"Windows {platform.release()} PC"
    try:
        with open("/etc/os-release", encoding="utf-8") as f: name = re.search(r'^PRETTY_NAME="?([^"\n]*)', f.read(), re.M).group(1)
    except (OSError, AttributeError): name = "Linux"
    return clean_label(re.sub(r" LTS$", "", name), 50) + " PC"

_PUSH = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; _push_last = [0, []]
def push_id():
    """Firebase-style push id made here: sorts by time, so one PATCH can add many ordered out/ messages."""
    now = int(time.time() * 1000)
    if now <= _push_last[0]:   # same (or earlier) ms: count up the random part so the order holds
        now = _push_last[0]; r = _push_last[1]; i = 11
        while i >= 0 and r[i] == 63: r[i] = 0; i -= 1
        if i >= 0: r[i] += 1
    else: r = [secrets.randbelow(64) for _ in range(12)]
    _push_last[:] = [now, r]
    t, n = "", now
    for _ in range(8): t = _PUSH[n % 64] + t; n //= 64
    return t + "".join(_PUSH[x] for x in r)

def proxy_for(url):
    """(host, port) of the HTTPS proxy from HTTPS_PROXY / NO_PROXY, or None (http.client does not read them by itself)."""
    host = urlsplit(url).hostname or ""
    p = urllib.request.getproxies().get(urlsplit(url).scheme)
    if not p or urllib.request.proxy_bypass(host): return None
    u = urlsplit(p if "://" in p else "http://" + p)
    return u.hostname, u.port or 8080

class Conn:
    """One keep-alive HTTP(S) connection (through HTTPS_PROXY when set), reconnected when it breaks."""
    def __init__(self, base, timeout=20): self.base, self.timeout, self.c = base, timeout, None
    def _open(self, url, timeout):
        u = urlsplit(url); px = proxy_for(url)
        cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
        if px:
            c = cls(px[0], px[1], timeout=timeout); c.set_tunnel(u.hostname, u.port or (443 if u.scheme == "https" else 80))
        else: c = cls(u.hostname, u.port, timeout=timeout)
        return c
    def request(self, method, url, body=None, headers=None):
        u = urlsplit(url); path = u.path + ("?" + u.query if u.query else "")
        data = body if isinstance(body, (bytes, type(None))) else json.dumps(body, separators=(",", ":")).encode()
        h = {"Content-Type": "application/json", "User-Agent": f"ros2lab-try/{VERSION}", **(headers or {})}
        for attempt in (0, 1):   # a kept-alive connection the server closed fails once: open a new one and send again
            if self.c is None: self.c = self._open(url, self.timeout)
            try:
                self.c.request(method, path, body=data, headers=h); r = self.c.getresponse(); out = r.read()
                return r.status, out, r
            except (OSError, http.client.HTTPException):
                self.close()
                if attempt: raise
    def close(self):
        if self.c:
            try: self.c.close()
            except Exception: pass
        self.c = None

class RelayClient:
    """The connected browser, seen through the relay: same interface as the WebSocket Client."""
    def __init__(self, relay, label): self.r, self.label, self.alive, self.teleop, self.times = relay, label, True, None, []
    def send(self, obj):
        if not self.alive: return
        if obj.get("t") == "state": self.r.latest_state = obj; return   # the state writer sends it at <= 10 Hz
        self.r.queue_out(obj)

class Relay:
    def __init__(self):
        self.secret = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()   # 256 bits, never leaves this PC + tab
        self.room = hashlib.sha256(self.secret.encode()).hexdigest()
        self.code = "".join(secrets.choice(CODE_CHARS) for _ in range(6)); self.code_exp = 0
        self.tok = self.refresh_tok = self.uid = None; self.tok_exp = 0; self.skew = 0.0; self.key = None
        self.lock = threading.Condition(); self.outq = []; self.delq = []; self.seen_in = set(); self.seen_order = []
        self.client = None; self.hello_at = None; self.page_t = 0.0; self.latest_state = None; self.lost = False; self.pending = []
        self.closing = threading.Event(); self.auth = Conn(AUTH_URL); self.w = Conn(RELAY_DB); self.s = Conn(RELAY_DB); self.hb = Conn(RELAY_DB)

    # -- urls and auth
    def url(self, path, tok=True, silent=False):   # silent: a write answers 204 without echoing the data (half the download)
        q = ([f"ns={RELAY_NS}"] if RELAY_NS else []) + ([f"auth={self.tok}"] if tok else []) + (["print=silent"] if silent else [])
        return f"{RELAY_DB}/relay{path}.json" + ("?" + "&".join(q) if q else "")
    def api_key(self):
        k = os.environ.get("ROS2LAB_FB_KEY")
        if k: return k
        # the site's public web key (Google designs it to be public; security = database.rules.json), read from the site itself
        st, body, _ = Conn(SITE, 15).request("GET", f"{SITE}/js/firebase-config.js")
        m = re.search(rb'apiKey:\s*"([A-Za-z0-9_\-]{20,80})"', body) if st == 200 else None
        if not m: raise RelayError(f"could not read the site settings from {SITE} (HTTP {st})")
        return m.group(1).decode()
    def _auth(self, url, body, form=False):
        hdr = {"Referer": SITE + "/"}   # the web key may be limited to the site's pages
        if form: hdr["Content-Type"] = "application/x-www-form-urlencoded"
        st, out, _ = self.auth.request("POST", f"{url}?key={urllib.parse.quote(self.key)}", urllib.parse.urlencode(body).encode() if form else body, hdr)
        try: j = json.loads(out)
        except ValueError: j = {}
        if st != 200: raise RelayError(f"sign-in refused (HTTP {st}: {str((j.get('error') or {}).get('message', ''))[:80]})")
        return j
    def sign_in(self, saved=None):
        if saved and saved.get("refresh"):
            try:
                self.refresh_tok = saved["refresh"]; self.refresh(); return
            except RelayError: pass   # a removed account: make a new one
        j = self._auth(f"{AUTH_URL}/accounts:signUp", {"returnSecureToken": True})
        self.tok, self.refresh_tok, self.uid = j["idToken"], j["refreshToken"], j["localId"]; self.tok_exp = time.time() + int(j.get("expiresIn", 3600))
    def refresh(self):
        j = self._auth(f"{TOKEN_URL}/token", {"grant_type": "refresh_token", "refresh_token": self.refresh_tok}, form=True)
        self.tok, self.refresh_tok, self.uid = j["id_token"], j["refresh_token"], j["user_id"]; self.tok_exp = time.time() + int(j.get("expires_in", 3600))

    # -- REST with one retry after a token refresh
    def call(self, conn, method, path, body=None):
        for attempt in (0, 1):
            st, out, r = conn.request(method, self.url(path, silent=method != "GET"), body)
            if st == 401 and attempt == 0 and time.time() > self.tok_exp - 300: self.refresh(); continue
            if not self.skew and r.getheader("Date"):   # the server's clock: code expiry must be in its time, not this PC's
                try:
                    from email.utils import parsedate_to_datetime
                    self.skew = parsedate_to_datetime(r.getheader("Date")).timestamp() - time.time()
                except (TypeError, ValueError): pass
            return st, out
        return st, out

    # -- start / stop
    def start(self):
        saved = {}
        try:
            with open(RELAY_FILE, encoding="utf-8") as f: saved = json.load(f)
        except (OSError, ValueError): pass
        try:
            self.key = self.api_key(); self.sign_in(saved)
            if saved.get("room") and re.fullmatch(r"[0-9a-f]{64}", str(saved["room"])):   # a room left by a run that crashed
                self.call(self.w, "DELETE", f"/rooms/{saved['room']}")
                if re.fullmatch(f"[{CODE_CHARS}]{{6}}", str(saved.get("code", ""))): self.call(self.w, "DELETE", f"/codes/{saved['code']}")
            st, out = self.call(self.w, "PUT", f"/rooms/{self.room}/meta", {"uid": self.uid, "pc": pc_label(), "os": OS, "distro": "jazzy",
                                                                         "v": VERSION, "created": SV, "seen": SV})
            if st not in (200, 204): raise RelayError(f"the relay refused the room (HTTP {st}: {out[:80].decode('utf-8', 'replace')})")
            self.save()
            self.new_code()
        except (OSError, http.client.HTTPException, KeyError, ValueError) as e:
            raise RelayError(self.why(e)) from None
        for target in (self.writer, self.heartbeat): threading.Thread(target=target, daemon=True).start()
        threading.Thread(target=self.stream, args=("in", self.on_in), daemon=True).start()
        threading.Thread(target=self.stream, args=("page", self.on_page), daemon=True).start()
        threading.Thread(target=self.state_writer, daemon=True).start()
    def why(self, e):
        px = proxy_for(RELAY_DB)
        if px: return f"{e}; the proxy {px[0]}:{px[1]} (HTTPS_PROXY) did not let it through"
        if isinstance(e, ssl_errors()): return f"{e}; a network that inspects secure connections (school/office) can cause this"
        return str(e) or e.__class__.__name__
    def save(self):
        if not LOG_ON: return   # only inside an installed try folder (never next to the site copy)
        try:
            fd = os.open(RELAY_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump({"refresh": self.refresh_tok, "room": self.room, "code": self.code}, f)
        except OSError: pass
    def new_code(self):
        self.code = "".join(secrets.choice(CODE_CHARS) for _ in range(6))
        self.code_exp = int((time.time() + self.skew + CODE_LIFE) * 1000)
        st, _ = self.call(self.w, "PUT", f"/codes/{self.code}", {"room": self.room, "exp": self.code_exp}); self.save()
        if st not in (200, 204): log(f"code refused HTTP {st}")
    def drop_code(self):
        if self.code_exp:
            self.code_exp = 0
            try: self.call(self.hb, "DELETE", f"/codes/{self.code}")
            except (OSError, http.client.HTTPException, RelayError): pass
    def link(self): return f"{SITE}/pc#s={self.secret}"
    def close(self):
        """Ctrl+C / idle: the room (and the code) are deleted, so nothing is left in the relay."""
        self.closing.set()
        with self.lock: self.lock.notify_all()
        for conn in (self.w, self.s, self.hb): conn.close()
        c = Conn(RELAY_DB, 5)
        try:
            self.call(c, "DELETE", f"/rooms/{self.room}")
            if self.code_exp: self.call(c, "DELETE", f"/codes/{self.code}")
            if LOG_ON:
                with open(RELAY_FILE, "w", encoding="utf-8") as f: json.dump({"refresh": self.refresh_tok}, f)
            log("relay room deleted")
        except (OSError, http.client.HTTPException, RelayError): log("relay room not deleted (offline): the next start deletes it")

    # -- page -> bridge: two event streams (text/event-stream), reconnected with backoff
    def stream(self, path, handler):
        wait = 1
        while not self.closing.is_set():
            try:
                self._stream(path, handler); wait = 1
            except (OSError, http.client.HTTPException, ValueError, RelayError) as e:
                if self.closing.is_set(): return
                if not self.lost: self.lost = True; say("  Lost the connection to the relay; trying again... (is the internet on?)")
                log(f"stream {path}: {e!r}")
            self.closing.wait(wait); wait = min(wait * 2, 30)
    def _stream(self, path, handler):
        url = self.url(f"/rooms/{self.room}/{path}")
        for _ in range(3):   # the database may redirect a stream to another server
            u = urlsplit(url); c = Conn(url, 75)._open(url, 75)   # keep-alive events come every ~30 s
            c.request("GET", u.path + "?" + u.query, headers={"Accept": "text/event-stream", "User-Agent": f"ros2lab-try/{VERSION}"})
            r = c.getresponse()
            if r.status in (301, 302, 307, 308) and r.getheader("Location"): url = r.getheader("Location"); c.close(); continue
            break
        if r.status == 401 and time.time() > self.tok_exp - 300: self.refresh(); c.close(); return
        if r.status != 200: c.close(); raise RelayError(f"stream HTTP {r.status}")
        if self.lost: self.lost = False; self.page_t = time.time(); say("  Connected to the relay again.")
        ev = None
        try:
            while not self.closing.is_set():
                line = r.readline()
                if not line: return
                line = line.decode("utf-8", "replace").rstrip("\r\n")
                if line.startswith("event:"): ev = line[6:].strip()
                elif line.startswith("data:") and ev in ("put", "patch"):
                    d = json.loads(line[5:]); handler(ev, d.get("path", "/"), d.get("data"))
                elif line.startswith("data:") and ev in ("auth_revoked", "cancel"):
                    if ev == "auth_revoked": self.refresh()
                    return
        finally: c.close()

    def on_in(self, ev, path, data):
        items = []
        if path == "/" and isinstance(data, dict): items = sorted(data.items())   # push ids sort by time
        elif path.count("/") == 1 and path != "/": items = [(path[1:], data)]
        for key, msg in items:
            if msg is None or key in self.seen_in: continue
            self.seen_in.add(key); self.seen_order.append(key)
            if len(self.seen_order) > 5000: self.seen_in.discard(self.seen_order.pop(0))
            with self.lock: self.delq.append(key); self.lock.notify_all()
            if self.client is None:   # the two streams race: a command can arrive just before the page's hello
                self.pending = (self.pending + [msg])[-20:]; continue
            dispatch(self.client, msg)

    def on_page(self, ev, path, data):
        if data is None and path in ("/", "/hello"):
            self.page_t = 0; self.page_left("the page closed"); return
        self.page_t = time.time()
        hello = data.get("hello") if path == "/" and isinstance(data, dict) else data if path == "/hello" else None
        if not isinstance(hello, dict) or hello.get("at") == self.hello_at: return
        self.hello_at = hello.get("at")
        if self.client: client_gone(self.client); say("  Browser left (another browser took over).")
        label = f"{clean_label(hello.get('browser'))} on {clean_label(hello.get('os'))}"
        self.client = RelayClient(self, label)
        with LOCK: CLIENTS.add(self.client)
        say(f"  Browser connected: {label}, {time.strftime('%H:%M')}"); log(f"browser connected: {label}")
        threading.Thread(target=self.drop_code, daemon=True).start()   # the short code is not needed any more: it cannot be guessed now
        early, self.pending = self.pending, []
        for m in early: dispatch(self.client, m)
    def page_left(self, why):
        c, self.client, self.hello_at = self.client, None, None
        if c:
            client_gone(c); say(f"  Browser left, {time.strftime('%H:%M')}. To come back, open the link above again."); log(f"browser left ({why})")
            self.latest_state = None

    # -- bridge -> page
    def queue_out(self, obj):
        with self.lock: self.outq.append(obj); self.lock.notify_all()
    def writer(self):
        """Out messages in order (ids made here, many per PATCH), then deletes of consumed in/ messages."""
        wait = 1
        while not self.closing.is_set():
            with self.lock:
                while not self.outq and not self.delq and not self.closing.is_set(): self.lock.wait(1)
                out, dels = self.outq[:40], self.delq[:100]
            try:
                if out:
                    batch = {push_id(): m for m in out}
                    st, body = self.call(self.w, "PATCH", f"/rooms/{self.room}/out", batch)
                    if st not in (200, 204): log(f"out refused HTTP {st}: {body[:120]!r}")   # dropped: a rule said no (never loop on it)
                    with self.lock: del self.outq[:len(out)]
                if dels:
                    self.call(self.w, "PATCH", f"/rooms/{self.room}/in", {k: None for k in dels})
                    with self.lock: del self.delq[:len(dels)]
                wait = 1
            except (OSError, http.client.HTTPException, RelayError) as e:
                log(f"writer: {e!r}"); self.closing.wait(wait); wait = min(wait * 2, 30)
    def state_writer(self):
        """Turtles at <= 10 Hz while a browser is connected; unchanged state is re-sent only every 5 s."""
        last, last_t, conn = None, 0.0, Conn(RELAY_DB)
        while not self.closing.wait(0.1):
            s = self.latest_state
            if not self.client or not s: continue
            body = {k: v for k, v in s.items() if k != "t"}
            if body == last and time.time() - last_t < 5: continue
            try:
                st, _ = self.call(conn, "PUT", f"/rooms/{self.room}/state", {**body, "at": SV})
                if st in (200, 204): last, last_t = body, time.time()
            except (OSError, http.client.HTTPException, RelayError): self.closing.wait(1)
    def heartbeat(self):
        while not self.closing.wait(10):
            try:
                if time.time() > self.tok_exp - 600: self.refresh()
                self.call(self.hb, "PATCH", f"/rooms/{self.room}/meta", {"seen": SV})
                if self.client and not self.lost and time.time() - self.page_t > PAGE_GONE: self.page_left("no heartbeat")   # not while WE are offline
                if self.code_exp and not self.client and (time.time() + self.skew) * 1000 > self.code_exp - 5000:
                    self.call(self.hb, "DELETE", f"/codes/{self.code}"); self.new_code()
                    say(f"  The code expired. New code: {self.code[:3]}-{self.code[3:]} (valid 10 minutes)")
            except (OSError, http.client.HTTPException, RelayError) as e: log(f"heartbeat: {e!r}")

def ssl_errors():
    import ssl
    return (ssl.SSLError, ssl.CertificateError)

def browser_env():
    """The visitor's normal environment for the web browser: without this ROS 2 / conda folder's settings."""
    env = {k: v for k, v in os.environ.items() if not (k.startswith(("CONDA", "PIXI", "QT_", "PYTHON", "SSL_CERT", "ROS_", "AMENT", "RMW_"))
                                                      or k in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"))}
    pre = os.environ.get("CONDA_PREFIX")
    if pre: env["PATH"] = os.pathsep.join(p for p in env.get("PATH", "").split(os.pathsep) if not p.startswith(pre))
    return env

def open_browser(url):
    if os.environ.get("ROS2LAB_NO_BROWSER") == "1": return False
    try:
        if OS == "windows": os.startfile(url); return True   # = start "" <url>, without a shell
        if OS == "linux" and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")): return False
        subprocess.Popen(["open" if OS == "mac" else "xdg-open", url], env=browser_env(), stdin=subprocess.DEVNULL,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        return True
    except OSError: return False

def other_bridge():
    import urllib.request
    try:
        rq = urllib.request.Request(f"http://127.0.0.1:{PORT}/hello", headers={"Host": f"127.0.0.1:{PORT}"})
        with urllib.request.urlopen(rq, timeout=3) as r: return json.loads(r.read()).get("ros2lab")
    except Exception: return None

def stop_all():
    with LOCK: ps = [pr.p for pr in PROCS.values()] + list(SIMS)
    for p in ps: interrupt(p)
    for p in ps:
        try: p.wait(8)
        except subprocess.TimeoutExpired: pass
    if ROS2:   # page commands started the ros2 daemon from this folder: stop it too (on Windows it would lock the folder)
        try: subprocess.run([ROS2, "daemon", "stop"], env=child_env(), cwd=TRY, stdin=subprocess.DEVNULL, capture_output=True, timeout=15)
        except (OSError, subprocess.TimeoutExpired): pass

def main(argv):
    srv = relay = None
    if "--direct" not in argv and os.environ.get("ROS2LAB_DIRECT") != "1":   # default: the relay (outbound only); direct = v2's 127.0.0.1 server
        relay = Relay()
        try: relay.start()
        except RelayError as e:
            relay = None
            say(f"  Could not reach the ROS2Lab relay: {e}.\n  Starting the direct connection instead: on the page choose"
                f" 'advanced: direct connection' (your browser will ask for permission to reach this PC).")
    if relay is None:
        try: srv = Server(("127.0.0.1", PORT), Handler)
        except OSError:
            v = other_bridge()
            if v: say(f"  Port {PORT} already has a ROS2Lab bridge ({v}). Stop it (Ctrl+C in its terminal) and run the try command again."); return 0
            say(f"  Port {PORT} is used by another program on this PC, so the page cannot reach ROS 2 here.\n  Close that program and run the try command again."); return 3
    try: serve(srv, relay, argv)
    except (KeyboardInterrupt, SystemExit): pass   # Ctrl+C / TERM / HUP at ANY moment, also during start-up (V67 saw a traceback)
    finally:
        for s in ("SIGINT", "SIGTERM", "SIGHUP"):   # a second Ctrl+C must not break the clean-up
            if hasattr(signal, s): signal.signal(getattr(signal, s), signal.SIG_IGN)
        STOPPING.set(); stop_all()
        if srv: srv.server_close()
        if relay: relay.close()
        log("stopped")
    # rclpy's C++ side aborts ("terminate called without an active exception") if Python tears it down while its thread
    # still spins (seen on Ctrl+C in testing): everything is stopped and flushed, so leave without running destructors
    sys.stdout.flush(); sys.stderr.flush(); os._exit(0)

def open_first_turtle():
    """The first turtle window. Its log lines go to this terminal; a Qt display error gets one retry with X11 (xcb), then a
    plain-English fix. Returns the running process, or None."""
    for attempt in (0, 1):
        say("Opening turtlesim (ros2 run turtlesim turtlesim_node) ...")
        p = popen([ROS2, "run", "turtlesim", "turtlesim_node"], TRY); seen, up = [], threading.Event()
        def fwd(pipe, seen=seen, up=up):
            for raw in iter(pipe.readline, b""):
                line = WIN1314.sub("", raw.decode("utf-8", "replace"))
                if not line: continue
                seen.append(line); sys.stdout.write(line); sys.stdout.flush()
                if "Spawning turtle" in line: up.set()
        for pipe in (p.stdout, p.stderr): threading.Thread(target=fwd, args=(pipe,), daemon=True).start()
        t0 = time.time()
        while not up.is_set() and p.poll() is None and time.time() - t0 < 15: time.sleep(0.1)
        if p.poll() is None:
            with LOCK: SIMS.append(p)
            return p
        time.sleep(0.3); text = "".join(seen)
        plat = os.environ.get("QT_QPA_PLATFORM", "")
        if attempt == 0 and QT_FAIL.search(text) and plat != "xcb" and OS == "linux":
            say(f"  The turtle window could not open with Qt's '{plat or 'default'}' display. Trying again with X11 (QT_QPA_PLATFORM=xcb) ...")
            os.environ["QT_QPA_PLATFORM"] = "xcb"; continue   # the commands from the page get it too (child_env copies os.environ)
        if "xcb-cursor" in text:
            say("  The turtle window needs one Ubuntu library. Install it once, then run the try command again:\n    sudo apt install libxcb-cursor0")
        else:
            say("  The turtle window could not open (the lines above say why). The page still works: type"
                "  ros2 run turtlesim turtlesim_node  there to try again.")
        return None

def dds_selftest():
    """macOS: some Macs' default DDS (Fast DDS) delivers nothing between programs (RoboStack ros-jazzy #50). Send one test message;
    if it does not arrive, switch to Cyclone DDS (in this environment) and try again."""
    def once():
        e = popen([ROS2, "topic", "echo", "--once", "/ros2lab_selftest", "std_msgs/msg/String"], TRY)
        pub = popen([ROS2, "topic", "pub", "-r", "2", "-t", "20", "/ros2lab_selftest", "std_msgs/msg/String", "{data: ros2lab}"], TRY)
        try: got = b"ros2lab" in e.communicate(timeout=20)[0]
        except subprocess.TimeoutExpired: got = False; interrupt(e)
        interrupt(pub); pub.communicate()
        return got
    say("Checking that ROS 2 programs can talk to each other on this computer ...")
    if once(): say("  OK: a test message went from one ROS 2 program to another."); return
    pre = os.environ.get("CONDA_PREFIX", "")
    has_cyclone = any(os.path.exists(os.path.join(pre, d, f)) for d in ("lib", "Library/bin")
                      for f in ("librmw_cyclonedds_cpp.so", "librmw_cyclonedds_cpp.dylib", "rmw_cyclonedds_cpp.dll"))
    if has_cyclone and os.environ.get("RMW_IMPLEMENTATION") != "rmw_cyclonedds_cpp":
        say("  The test message did not arrive with the default DDS. Trying Cyclone DDS (RMW_IMPLEMENTATION=rmw_cyclonedds_cpp) ...")
        os.environ["RMW_IMPLEMENTATION"] = "rmw_cyclonedds_cpp"
        if once(): say("  OK with Cyclone DDS: this bridge and everything it starts use it."); return
    say("  The test message did not arrive. If a firewall asks whether python or turtlesim may use the network, allow it;"
        " then run the try command again.")

def warm_daemon():
    """The page's first `ros2 param set` starts the ros2 daemon, which has not discovered /turtlesim yet and prints
    "Node not found" (V74 personas 2 and 6). Start the daemon now and wait (at most 15 s) until it lists /turtlesim."""
    t0 = time.time()
    while time.time() - t0 < 15:
        try: r = subprocess.run([ROS2, "node", "list"], env=child_env(), cwd=TRY, stdin=subprocess.DEVNULL, capture_output=True, timeout=10)
        except (subprocess.TimeoutExpired, OSError): continue
        if b"/turtlesim" in r.stdout: return True
        time.sleep(0.5)
    return False

DONE = threading.Event()
def serve(srv, relay, argv):
    global ROS2
    for s in ("SIGTERM", "SIGHUP"):   # the try script stops us with TERM; a closed terminal sends HUP
        if hasattr(signal, s): signal.signal(getattr(signal, s), lambda *_: sys.exit(0))
    ROS2 = shutil.which("ros2")
    log(f"start {VERSION} {'relay' if relay else f'direct port {PORT}'} ros2={'yes' if ROS2 else 'no'} dev_origin={DEV_ORIGIN or '-'}")
    if ROS2 and (OS == "mac" or os.environ.get("ROS2LAB_SELFTEST") == "1"): dds_selftest()   # before rclpy picks its middleware
    threading.Thread(target=ros_thread, daemon=True).start()
    threading.Thread(target=broadcaster, daemon=True).start()
    first = open_first_turtle() if "--turtlesim" in argv and ROS2 else None
    if first:
        def watch():
            first.wait()
            with LOCK:
                if first in SIMS: SIMS.remove(first)
            if not STOPPING.is_set(): say("  The turtle window was closed. Type  ros2 run turtlesim turtlesim_node  on the page to open one again (Ctrl+C here stops all).")
        threading.Thread(target=watch, daemon=True).start()
        log(f"daemon warm: {warm_daemon()}")
    def idle():
        while True:
            time.sleep(min(30, IDLE / 4))
            with LOCK: quiet = not CLIENTS and time.time() - LAST_CLIENT[0] >= IDLE
            if quiet:
                say(f"\nNo page was connected for {int(IDLE // 60)} minutes, so the bridge stopped.\n  Start it again with: {RESTART}")
                log("idle exit"); (srv.shutdown() if srv else DONE.set()); return
    threading.Thread(target=idle, daemon=True).start()
    if relay:
        opened = open_browser(relay.link())
        say("")
        say("ROS 2 is ready. Your browser should open ros2lab.com and turn green." if opened else
            "ROS 2 is ready. Open this link in your browser on this PC (it did not open by itself):")
        say(f"  {relay.link()}")
        say(f"  Other browser, phone or remote session: go to {SITE.split('://')[-1]}/pc and type the code {relay.code[:3]}-{relay.code[3:]}"
            " (valid 10 minutes, once).")
        say("Press Ctrl+C here to stop.")
        while not DONE.wait(0.5): pass
        return
    say(f"  Bridge {VERSION} on http://127.0.0.1:{PORT} (only this PC can reach it). Log: {os.path.join(TRY, 'bridge.log')}")
    new_code("ROS2Lab bridge ready")
    say("Now press 'Connect to my PC' on www.ros2lab.com and type this code there.")
    say(f"  Safari, iPhone/iPad or no internet: open http://127.0.0.1:{PORT}/ in a browser on this PC instead.")
    srv.serve_forever()

def selftest():
    """The grammar and the WebSocket framing, without ROS (tests/v68-bridge.mjs runs it too)."""
    good = ["ros2 node list", "ros2 topic list -t", "ros2 topic echo /turtle1/pose --once", "ros2 topic echo /turtle1/pose",
            "ros2 topic pub --once /turtle1/cmd_vel geometry_msgs/msg/Twist \"{linear: {x: 2.0}, angular: {z: 1.8}}\"",
            "ros2 topic pub -r 1 /turtle1/cmd_vel geometry_msgs/msg/Twist \"{linear: {x: 2.0}}\"", "ros2 topic hz /turtle1/pose",
            "ros2 service call /spawn turtlesim/srv/Spawn \"{x: 2, y: 2, theta: 0.0, name: 'turtle2'}\"", "ros2 service list -t",
            "ros2 param set /turtlesim background_r 255", "ros2 param set /turtlesim background_r 1.5", "ros2 param get /turtlesim background_g",
            "ros2 action send_goal --feedback /turtle1/rotate_absolute turtlesim/action/RotateAbsolute \"{theta: 1.57}\"",
            "ros2 interface show turtlesim/srv/SetPen", "ros2 pkg executables turtlesim", "ros2 doctor", "ros2 bag record /turtle1/cmd_vel -o run1",
            "ros2 bag info run1", "ros2 bag play run1", "ros2 run turtlesim turtlesim_node", "ros2 run turtlesim turtle_teleop_key",
            "ros2 run turtlesim turtlesim_node --ros-args -r __node:=my_sim -p background_r:=255", "ros2 topic lst", "ros2 lanch", "ros2",
            "ros2 node info /turtlesim", "ros2 service call /turtle1/set_pen turtlesim/srv/SetPen \"{r: 255, g: 0, b: 0, width: 3, off: 0}\"",
            "ros2 param set /turtlesim background_r -1", "ros2 topic", "ros2 run turtlesim turtlesim_nod", "ros2 topic echo /turtle1/pose --field x", "ros2 run turtlesim draw_square",
            "ros2 run turtlesim mimic --ros-args -r input/pose:=/turtle1/pose -r output/cmd_vel:=/turtle2/cmd_vel"]
    bad = ["ros2 node list; rm -rf ~", "ros2 topic list $(id)", "ros2 topic list `id`", "rm -rf /", "ros2 node list | sh", "ros2 node list && id",
           "ros2 launch turtlesim multisim.launch.py", "ros2 pkg create evil", "ros2 run demo_nodes_cpp talker", "ros2 run turtlesim mimic --ros-args -r a:=$(id)",
           "ros2 bag record -o /etc/x /turtle1/pose", "ros2 bag record -o ../../x /turtle1/pose", "ros2 bag info /home", "ros2 param load /turtlesim x.yaml",
           "ros2 topic echo /turtle1/pose --filter \"__import__('os').system('id')\"", "ros2 topic echo turtle1/pose", "ros2 daemon stop",
           "ros2 run turtlesim turtlesim_node --ros-args -r __node:=$(id)", "ros2 run turtlesim turtlesim_node --ros-args --params-file /etc/passwd",
           "ros2 topic pub /turtle1/cmd_vel geometry_msgs/msg/Twist --stdin", "python3 -c 1", "ros2 security create_keystore k",
           "ros2 node list --evil", "ros2 topic echo /a;id", "ros2 topic echo /turtle1/pose --qos-profile-overrides-path /etc/passwd",
           "ros2 multicast send", "ros2 bag convert -i a -o b", "ros2 run turtlesim turtlesim_node extra"]
    fails = [l for l in good if not classify(shlex.split(l))] + [l for l in bad if classify(shlex.split(l))]
    kinds = {"ros2 topic echo /turtle1/pose": "long", "ros2 topic echo /turtle1/pose --once": "once", "ros2 run turtlesim turtle_teleop_key": "teleop",
             "ros2 action send_goal /turtle1/rotate_absolute turtlesim/action/RotateAbsolute \"{theta: 1.57}\"": "long", "ros2 bag info run1": "bag-once"}
    fails += [f"{l} -> {classify(shlex.split(l))}" for l, k in kinds.items() if (classify(shlex.split(l)) or ("",))[0] != k]
    m = os.urandom(4); payload = b'{"t":"run"}'
    frame = bytes([0x81, 0x80 | len(payload)]) + m + bytes(b ^ m[i % 4] for i, b in enumerate(payload))
    import io
    if ws_read(io.BytesIO(frame)) != (1, payload): fails.append("ws_read")
    if ws_accept("dGhlIHNhbXBsZSBub25jZQ==") != "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=": fails.append("ws_accept (RFC 6455 example)")
    if ws_read(io.BytesIO(bytes([0x81, len(payload)]) + payload)) is not None: fails.append("unmasked frame accepted")
    if ansi_strip("\x1b[31mred\x1b[0m") != "red": fails.append("ansi")
    ids = [push_id() for _ in range(3000)]
    if ids != sorted(ids) or len(set(ids)) != 3000 or any(len(i) != 20 for i in ids): fails.append("push ids not unique and ordered")
    if clean_label("Chrome\x1b]0;evil\x07\x1b[2J on <b>") != "Chrome0evil2J on b": fails.append("clean_label")
    rl = Relay()
    if not (re.fullmatch(r"[0-9a-f]{64}", rl.room) and len(rl.secret) == 43 and hashlib.sha256(rl.secret.encode()).hexdigest() == rl.room
            and re.fullmatch(f"[{CODE_CHARS}]{{6}}", rl.code)): fails.append("secret/room/code")
    print("selftest " + ("ok" if not fails else "FAILED: " + " | ".join(fails))); return 1 if fails else 0

if __name__ == "__main__":
    if sys.argv[1:] == ["--selftest"]: sys.exit(selftest())
    sys.exit(main(sys.argv[1:]))
