#!/usr/bin/env python3
# summary: Pair computers, join a fleet, and share files.
"""starchaser link: connect your computers and share files.

Common commands
  starchaser link list                    show this computer and nearby or paired devices
  starchaser link pair <address>          pair with another computer by checking a code
  starchaser link join <address>          join the group that computer belongs to
  starchaser link send <device-id> <file> send a file to a paired device
  starchaser link clipboard <device-id>   send copied text to a paired device
  starchaser link remote <device-id>      open a paired computer's desktop

What the fields mean and more commands
A computer joins your fleet once, with a code checked on one computer already in it; then the
Starchaser computers share status, files and the clipboard, keep the fleet list the same everywhere, and offer remote
desktop (Settings › Fleet). (The fleet is all your computers; the ones that don't run Starchaser are added in
Mission Control and reached over SSH: `starchaser fleet`.)

In a terminal, pair and join show a code and ask you to compare it with the other computer.
Type the six-digit code shown on the other computer and press Enter within 2 minutes; anything else cancels.
Approve the request on the other computer too.

How it works
  Finding    each Starchaser desktop in a fleet (or with finding turned on) announces itself, only on a network the
             firewall marks as trusted (Avahi, _starchaser._tcp), as "Starchaser <computer name>" without the account name, with its
             fleet's tag and size (fleet=, size=), so a new computer sees "your fleet", not a list of computers.
             The tag is display only: anyone can announce any tag, and trust never comes from it.
  Pairing    one device asks; both screens show a 6-digit code, and the person presses Pair on both. Each side
             computes the code itself from both devices' keys and a random number from each side, and the accepting
             side commits to its number before it sees the asker's, so a device in the middle can't make the two
             codes match (short of a one-in-a-million guess). Neither side trusts the other until both people said
             yes. Keys travel over a short TCP connection to port 47744. The service listens there only after this computer
             joined a fleet or the person turned finding on (the firewall allows it as "Fleet (joining)") and acts
             only on a request you approve on screen.
             Paired, each one is in the other's fleet (`starchaser fleet`), and so in every computer's fleet.
  Talking    afterward everything goes over SSH (so Remote login has to be on, on both computers) with a key that
             is locked to `starchaser link serve` in the other user's authorized_keys (restrict + a forced command,
             no shell, no port forwarding). What a paired device can ask for: status, deliver a file to Downloads
             (over 4 GB asks first), set the clipboard, list AI agent sessions (state and project; prompt text only
             if the person here shares it), exchange the fleet list (fleet-sync), ask to manage this computer
             (manage-request: asked here, once), unpair, set up Wake on LAN (the host is told), and remote desktop:
             open the firewall for Sunshine's streaming ports, start Sunshine, create or check its login and pair
             Moonlight. Remote desktop asks the person at the host once per device first.
  The fleet  a computer another fleet computer paired is trusted here too: the fleet list carries its link key
             and verified host key (adopt, said in a notification). A computer removed from the fleet is refused and
             its keys go on every computer (forget_device). docs/fleet.md has the whole picture.

Commands
  daemon                      announce this device and answer pairing requests (the starchaser link user service)
  list                        JSON: this device, paired devices (with live status), nearby unpaired ones (each
                              with the fleet it says it's in), "fleet" (this computer's tag and size), "fleets"
                              (nearby fleets this one isn't in, grouped), "pending" (pairing requests), and
                              "waiting" (pairings waiting)
  pair <address> [port] [--no-manage]
                              ask a nearby device to pair; prints {"code"}, reads this person's "yes" / "no" on
                              stdin, then prints {"result"} ("accepted" with "manage": "asking" | "off"; "checking"
                              when the last message got lost: finished by the next list if the other side has it).
                              Paired, it joins this computer's fleet; unless --no-manage, it is then asked (there)
                              to let the fleet manage it from Mission Control, and it asks this computer the same
                              back (both ways, on every pairing). The one approval on each side answers both: the
                              question there says its Allow lets the fleet manage it, and this Pair (with both ways
                              on, the default) gives the fleet full control of this account from Mission Control (and
                              as administrator when sudo needs no password here) without asking again; turn it off with
                              "Manage each other after pairing" or later in Settings › Fleet. An older Starchaser there:
                              {"result": "older"}; nothing is kept here, and if it trusts this computer anyway it
                              is asked (in the background) to forget it. One that computes the older code (its hello
                              has no "proto"): {"result": "needs-update"} before any code is shown
  join <address> [port] [--no-manage]
                              join the fleet the computer at <address> is in: pair's code check (the one OK, on
                              that computer), no second question; unless --no-manage this computer lets the fleet
                              manage it, asks that computer whether it may manage it, and is asked the same back
                              (its switch, on, answers with no question); --no-manage ("Join only") asks neither way.
                              Then prints {"members": [{id, name, state}]} while the fleet picks it up
                              (joined / waiting / off / managed / later) and ends with {"done": true, "members"}
  join-wait [seconds]         only the waiting part of join (default 60)
  answer <request-id> yes|no  accept or decline a pairing request shown on this device
  send <device-id> <file>...  deliver files to the other device's Downloads/From <this device>
  clipboard <device-id>       send this clipboard to the other device
  unpair <device-id> [--lost]  remove a device from the fleet on every computer (starchaser fleet remove)
  discovery [on|off|auto]     show or set "Let nearby computers find this one" (auto: on once in a fleet); nothing
                              listens or announces while it is off, and the announcement goes out only on a
                              network marked as trusted
  pairing-mode fleet|help|off  allow join requests for 10 minutes, or close the window
  end-help                  remove helper access and end remote sessions
  fleet-sync [--except <id>]  exchange the fleet list with every paired computer now
  settings-sync [--except <id>]
                              exchange followed settings with fleet computers now
  manage-request <device-id> [--after-pair]
                              ask a paired computer (again) to let the fleet manage it (--after-pair: started by a
                              pairing; waits a few seconds and tries again while the other side doesn't let it in yet)
  manage-fleet-allow          (after a local Allow, when opted in) request the same from paired fleet members
  remote <device-id>          remote desktop to it: gets it ready (Sunshine there), pairs Moonlight here the first time
                              with a PIN it hands over itself, then connects; prints {"step"} lines then {"result"}
  wake <device-id>            Wake-on-LAN magic packet to a sleeping / off desktop (same network only)
  tailscale-up                sign this device in to Tailscale; prints {"url"} to open, then {"result"}
  self                        JSON: this device's status
  serve <device-id>           (the forced command a paired device's key runs)
  wake-prep <device-id>       (started by list, in the background) ask a paired desktop to keep Wake on LAN on
State: ~/.local/share/starchaser/devices/ (key, device id, peers.json, known_hosts; remote-ok.json: devices the
person here allowed to use remote desktop; sunshine-clients.json: the Moonlight pairing each device made with this
computer's Sunshine, removed again when it's unpaired; wake-setup.json).
"""
import contextlib
import errno
import fcntl
import hashlib
import html
import ipaddress
import json
import os
import pwd
import re
import select
import secrets
import selectors
import shlex
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import threading
import time
import unicodedata
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import command_usage_error, takes_nothing_after, usage_error, safe_streams
from starchaser_system_defaults import tool_path  # noqa: E402
safe_streams()

HOME = Path.home()
STATE = HOME / ".local/share/starchaser/devices"
KEY = STATE / "id_ed25519"
IDFILE = STATE / "device-id"
PEERS = STATE / "peers.json"
KNOWN = STATE / "known_hosts"
PENDING = HOME / ".cache/starchaser/devices/pending"
PORT = 47744
SERVICE = "_starchaser._tcp"
AUTH = HOME / ".ssh/authorized_keys"
ME = pwd.getpwuid(os.getuid()).pw_name
if str(Path.home() / ".local/bin") not in os.environ.get("PATH", "").split(os.pathsep):
    os.environ["PATH"] = str(Path.home() / ".local/bin") + os.pathsep + os.environ.get("PATH", "")
SELF_BIN = tool_path("starchaser-link")   # a device's forced command: /usr/lib/starchaser/bin, or a checkout's bin/
PAIRCHECK = STATE / "pair-check"                         # pairings that may have finished on the other side only
BIG_FILE = 4 * 1024 ** 3                                  # files over 4 GB ask first (decided 2026-10-09)
_FLEET = None


class _ThisModule:
    """This module, for starchaser fleet's calls back into it (lan_addresses, adopt, forget_device...): it may be
    loaded under any name (or none, as a test loads it), so it is never looked up in sys.modules."""
    def __getattr__(self, name):
        try:
            return globals()[name]
        except KeyError:
            raise AttributeError(name) from None


THIS = _ThisModule()


class FolderChanges:
    """Wait for a change in some folders (inotify): a file in one written, made, renamed or removed. The daemon's loops
    wait on this instead of reading the same files every few seconds, which kept an idle desktop busy. Without inotify
    a wait just times out, so every caller keeps a bounded wait of its own."""
    # IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE | IN_DELETE
    MASK = 0x08 | 0x40 | 0x80 | 0x100 | 0x200

    def __init__(self, *folders):
        self.folders = [Path(f) for f in folders]
        self.fd = -1
        try:
            import ctypes
            self.libc = ctypes.CDLL(None, use_errno=True)
            self.fd = self.libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK)
        except (OSError, AttributeError):
            self.fd = -1
        self.watch()

    def watch(self) -> None:
        """(Again) watch every folder, making this account's own folders when missing: a folder removed and made
        again is a new one to inotify."""
        for folder in self.folders:
            with contextlib.suppress(OSError):
                folder.mkdir(parents=True, exist_ok=True)
            if self.fd >= 0:
                self.libc.inotify_add_watch(self.fd, os.fsencode(folder), self.MASK)

    def close(self) -> None:
        if self.fd >= 0:
            os.close(self.fd)
            self.fd = -1

    def wait(self, seconds: float) -> bool:
        """True once something changed, False when `seconds` passed first."""
        if self.fd < 0:
            time.sleep(seconds)
            return False
        if not select.select([self.fd], [], [], seconds)[0]:
            return False
        try:
            raw = os.read(self.fd, 65536)
        except BlockingIOError:
            return False
        offset = 0
        while offset + 16 <= len(raw):
            mask, length = int.from_bytes(raw[offset + 4:offset + 8], sys.byteorder), \
                int.from_bytes(raw[offset + 12:offset + 16], sys.byteorder)
            if mask & 0xC000:                           # IN_IGNORED (the folder went), IN_Q_OVERFLOW
                self.watch()
            offset += 16 + length
        return True


def fleet():
    """bin/starchaser-fleet, the one writer of the fleet list, loaded as a module (next to this file, else the
    installed copy)."""
    global _FLEET
    if _FLEET is None:
        import importlib.machinery
        import importlib.util
        here = Path(os.path.realpath(__file__)).parent / "starchaser-fleet"
        path = here if here.exists() else tool_path("starchaser-fleet")
        loader = importlib.machinery.SourceFileLoader("starchaser_fleet", str(path))
        spec = importlib.util.spec_from_loader("starchaser_fleet", loader)
        mod = importlib.util.module_from_spec(spec)
        loader.exec_module(mod)
        _FLEET = mod
    return _FLEET


TIMED_OUT = "starchaser: timed out"          # sh()'s stderr for a timeout (str(TimeoutExpired) holds the whole command line)


def sh(*cmd, timeout=10, input=None, env=None) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, input=input, env=env)
    except subprocess.TimeoutExpired:
        return subprocess.CompletedProcess(cmd, 124, "", TIMED_OUT)
    except OSError as e:
        return subprocess.CompletedProcess(cmd, 1, "", str(e))


def why_not(p: dict, r: subprocess.CompletedProcess) -> str:
    """Plain words for a call to a paired device that failed: never ssh's or Python's own text, which can hold the
    whole command line and key paths."""
    err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
    name = p.get("name") or "The other computer"
    if TIMED_OUT in err or r.returncode == 124:
        return f"{name} took too long to answer. Check that it's awake, then try again."
    if r.returncode != 255:                 # ssh got in (it exits 255 only for its own failures): the other side failed
        return f"{name} answered but couldn't do it. Try again; if it keeps happening, restart {name}."
    if "Host key verification failed" in err or "IDENTIFICATION HAS CHANGED" in err:
        return f"{name} doesn't look like the computer that was paired (it may have been reinstalled). Unpair it and pair again."
    if "Permission denied (" in err:         # ssh's own refusal ("Permission denied (publickey)"), not a file error there
        return f"{name} doesn't let this computer in anymore. Unpair it and pair again."
    return f"{name} didn't answer. Check that it's on and on the same network, then try again."


def jread(p: Path, default):
    try:
        return json.loads(p.read_text())
    except (OSError, ValueError):
        return default


def state_unwritable(error: OSError) -> None:
    """A state folder it may not read or write: one plain line, never a Python traceback."""
    sys.exit(f"starchaser link: couldn't read or save this computer's device state ({error.strerror}). "
             "Check that you can write to ~/.local/share.")


def jwrite(p: Path, data) -> None:
    try:
        p.parent.mkdir(parents=True, exist_ok=True)
    except OSError as error:
        state_unwritable(error)
    # a name of its own per writer: two writers sharing one .tmp could swap halves of each other's files
    tmp = p.with_name(f".{p.name}.{os.getpid()}.{threading.get_ident()}.tmp")
    tmp.write_text(json.dumps(data, indent=1) + "\n")
    tmp.replace(p)


_LOCK_DEPTH = threading.local()


@contextlib.contextmanager
def state_lock():
    """One writer at a time for the device files (peers, keys, remote desktop grants, Sunshine clients, Wake on LAN):
    list, the pairing daemon's threads, pairing, unpair and a paired device's requests all change them, often at the
    same moment, and a read-change-write that overlaps another one silently undoes it. Never held across a network
    call. Taken again by the same thread, it's already held."""
    depth = getattr(_LOCK_DEPTH, "n", 0)
    if depth:
        _LOCK_DEPTH.n = depth + 1
        try:
            yield
        finally:
            _LOCK_DEPTH.n -= 1
        return
    try:
        STATE.mkdir(parents=True, exist_ok=True)
        fd = os.open(STATE / ".lock", os.O_RDWR | os.O_CREAT, 0o600)
    except OSError as error:
        state_unwritable(error)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX)
        _LOCK_DEPTH.n = 1
        try:
            yield
        finally:
            _LOCK_DEPTH.n = 0
    finally:
        os.close(fd)                                        # (closing it lets go of the lock)


# ---------------------------------------------------------------------------------------------- what the network sends
# Everything below can come from another device (its pairing hello, its status, its mDNS announcement), so it is
# checked before it is stored or used: a user name or address goes onto an ssh / moonlight command line (a leading
# "-" would be read as an option there), and a device name becomes a folder under Downloads.
USER_RE = re.compile(r"[a-z_][a-z0-9_-]{0,31}")          # a Linux login name (useradd's own rule, without the $)
ID_RE = re.compile(r"[0-9a-f]{16}")


def valid_user(u) -> bool:
    return isinstance(u, str) and bool(USER_RE.fullmatch(u))


def valid_ip(a) -> bool:
    if not isinstance(a, str) or not a or len(a) > 64:
        return False
    try:
        ipaddress.ip_address(a)
        return True
    except ValueError:
        return False


def valid_host(a) -> bool:
    """An address to reach a device at: an IP address, or a host name someone typed for `pair` (letters, digits,
    dots and dashes, never starting with "-")."""
    return valid_ip(a) or (isinstance(a, str) and len(a) <= 253
                           and bool(re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?", a)))


def safe_name(name, fallback: str = "a paired device") -> str:
    """A device name fit to show and to name a folder: no slashes, control or invisible characters, no leading dots
    or spaces, at most 40 characters."""
    s = "".join(c for c in str(name or "") if c not in "/\\" and not unicodedata.category(c).startswith("C"))
    s = s.strip().lstrip(". ").strip()[:40].strip()
    return s or fallback


def safe_kind(k) -> str:
    return k if isinstance(k, str) and re.fullmatch(r"[a-z-]{1,20}", k) else ""


def valid_peer(p) -> bool:
    return isinstance(p, dict) and isinstance(p.get("id"), str) and bool(ID_RE.fullmatch(p["id"])) and valid_user(p.get("user"))


def load_peers() -> list:
    """peers.json, with any entry that doesn't check out left out (and so never used on a command line)."""
    data = jread(PEERS, [])
    return [p for p in data if valid_peer(p)] if isinstance(data, list) else []


def peers_file_ok() -> bool:
    """peers.json reads as a list (or isn't there yet). False for a file that didn't read: then nobody may act on
    "this device isn't paired" (write the list back, drop a key), since every device would look unpaired."""
    if not PEERS.exists():
        return True
    return isinstance(jread(PEERS, None), list)


# ---------------------------------------------------------------------------------------------- identity
def ensure_identity() -> None:
    try:
        STATE.mkdir(parents=True, exist_ok=True)
        os.chmod(STATE, 0o700)
        if not KEY.exists():
            sh("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", f"starchaser-link:{socket.gethostname()}", "-f", str(KEY))
        if not IDFILE.exists():
            IDFILE.write_text(uuid.uuid4().hex[:16] + "\n")
    except OSError as error:
        state_unwritable(error)


def device_id() -> str:
    ensure_identity()
    return IDFILE.read_text().strip()


def pubkey() -> str:
    ensure_identity()
    return " ".join(KEY.with_suffix(".pub").read_text().split()[:2])


def hostkey() -> str:
    try:
        return " ".join(Path("/etc/ssh/ssh_host_ed25519_key.pub").read_text().split()[:2])
    except OSError:
        return ""


def kind() -> str:
    c = sh("hostnamectl", "chassis").stdout.strip()
    return c or "desktop"


# The pairing code's recipe. 2 = the code covers keys, personal key, access scope and generation (code_for). A hello
# without "proto" comes from a Starchaser that computes the older keys-only code: the two screens could never agree,
# so neither side shows a code to such a peer. (A fallback to the old code would drop the scope from what the code
# proves, and an attacker stripping "proto" could force it.)
PAIR_PROTO = 2


def peer_proto_ok(peer) -> bool:
    return type(peer.get("proto")) is int and peer["proto"] >= PAIR_PROTO


def hello() -> dict:
    return {"id": device_id(), "proto": PAIR_PROTO, "name": socket.gethostname(), "user": ME, "kind": kind(), "key": pubkey(), "hostkey": hostkey(),
            "managePub": fleet().ensure_personal_key()[0], "generation": fleet().load()["local"].get("selfGen", 0)}


def code_for(a: dict, b: dict, asker_nonce: str, accepter_nonce: str) -> str:
    """The 6-digit code both screens show, computed on each side (never shown as received): both devices' keys in
    a fixed order, the personal key and negotiated access scope, plus each side's random number."""
    def identity(peer):
        fields = [peer["key"], peer["hostkey"], peer.get("managePub", ""), peer.get("help") is True,
                  peer.get("intent", ""), peer.get("manage") is True, peer.get("askBack") is not False]
        if peer.get("generation", 0):
            fields.append(peer["generation"])
        return json.dumps(fields, separators=(",", ":"))
    keys = sorted([identity(a), identity(b)])
    n = int(hashlib.sha256("|".join(keys + [asker_nonce, accepter_nonce]).encode()).hexdigest(), 16) % 1_000_000
    return f"{n:06d}"


def new_nonce() -> str:
    return os.urandom(16).hex()


def commitment(nonce: str) -> str:
    return hashlib.sha256(("starchaser-pair|" + nonce).encode()).hexdigest()


def remote_login_on() -> bool:
    """Is this computer's SSH server (Remote login, Settings › Security) running? Paired devices talk over it."""
    out = sh("systemctl", "is-active", "sshd.service", "sshd.socket").stdout.split()
    return "active" in out


# ---------------------------------------------------------------------------------------------- status
def battery() -> dict:
    for b in sorted(Path("/sys/class/power_supply").glob("BAT*")):
        try:
            return {"percent": int((b / "capacity").read_text()), "status": (b / "status").read_text().strip()}
        except (OSError, ValueError):
            pass
    return {}


def lan_addresses() -> list:
    try:
        data = json.loads(sh("ip", "-j", "-4", "addr").stdout or "[]")
    except ValueError:
        return []
    return [a["local"] for d in data for a in d.get("addr_info", []) if a.get("scope") == "global"
            and not d["ifname"].startswith(("tailscale", "virbr", "docker", "vnet", "br-"))]


def tailscale_ip() -> str:
    if not shutil.which("tailscale"):
        return ""
    return (sh("tailscale", "ip", "-4", timeout=4).stdout.strip().splitlines() or [""])[0]


def wake_info() -> list:
    """Wired network cards that can wake this computer: their MAC and whether NetworkManager keeps magic-packet
    wake on (\"default\" leaves the card's own setting, usually on, but not guaranteed)."""
    out = []
    for dev in sorted(Path("/sys/class/net").iterdir()):
        if (dev / "wireless").exists() or not (dev / "device").exists():
            continue
        try:
            if (dev / "type").read_text().strip() != "1":
                continue
            mac = (dev / "address").read_text().strip()
        except OSError:
            continue
        conn = sh("nmcli", "-g", "GENERAL.CONNECTION", "device", "show", dev.name).stdout.strip()
        wol = sh("nmcli", "-g", "802-3-ethernet.wake-on-lan", "connection", "show", conn).stdout.strip() if conn else ""
        out.append({"iface": dev.name, "mac": mac, "nm": wol or "unknown"})
    return out


def pending_update_cache() -> dict:
    """Fleet cards use the same installed-version reconciliation as Settings and Mission Control."""
    cache = jread(HOME / ".cache/starchaser/updates.json", {})
    if not isinstance(cache, dict):
        return {}
    try:
        import importlib.machinery
        import importlib.util
        path = Path(__file__).resolve().with_name("starchaser-updates")
        loader = importlib.machinery.SourceFileLoader("fleet_pending_updates", str(path))
        spec = importlib.util.spec_from_loader(loader.name, loader)
        updates = importlib.util.module_from_spec(spec)
        loader.exec_module(updates)
        return updates.current_pending(cache, updates.installed())
    except (OSError, ValueError, ImportError, subprocess.SubprocessError):
        return cache


def self_status() -> dict:
    up = float(Path("/proc/uptime").read_text().split()[0])
    upd = pending_update_cache()
    upd_rows = upd.get("updates")
    osr = dict(l.split("=", 1) for l in Path("/etc/os-release").read_text().splitlines() if "=" in l)
    model = ""
    about = shutil.which("starchaser") or tool_path("starchaser-about")   # (a forced command has a bare PATH)
    if Path(about).exists():                                 # the friendly name About shows
        try:
            model = json.loads(sh(about, timeout=8).stdout).get("model", "")
        except ValueError:
            pass
    for f in ([] if model else ["/sys/class/dmi/id/product_name", "/sys/class/dmi/id/board_name"]):
        try:
            model = Path(f).read_text().strip()
            if model and model.lower() not in ("default string", "to be filled by o.e.m."):
                break
        except OSError:
            pass
    return {"id": device_id(), "name": socket.gethostname(), "user": ME, "kind": kind(), "model": model,
            "addresses": lan_addresses(), "tailscale": tailscale_ip(), "wake": wake_info(),
            "os": osr.get("PRETTY_NAME", "").strip('"'), "uptime": int(up), "battery": battery(),
            "updates": len(upd_rows) if isinstance(upd_rows, list) else None, "updatesChecked": upd.get("checked"),
            "time": int(time.time()), "settings_sync": settings_capability(), "recovery": fleet().recovery_client().capability()}


# ---------------------------------------------------------------------------------------------- finding
# did the last look (nearby()) finish a whole browse? A browse that timed out, or couldn't run, returns [] too, and
# that must never read as "nobody is here" (the welcome starts a fleet only after a whole browse found nobody)
NEARBY_DONE = False
# how stale a paired computer's lastSeen may get before a look that reached it stamps a new one
LAST_SEEN_STEP = 300


def nearby() -> list:
    """Starchaser devices announcing themselves on the local network (not this one)."""
    global NEARBY_DONE
    NEARBY_DONE = False
    if not shutil.which("avahi-browse"):
        return []
    me, seen, hosts = device_id(), {}, {}
    r = sh("avahi-browse", "-rpt", "-k", SERVICE, timeout=6)
    NEARBY_DONE = r.returncode == 0
    for l in r.stdout.splitlines():
        f = l.split(";")
        if len(f) < 10 or f[0] != "=":
            continue
        txt = dict(re.findall(r'"(\w+)=([^"]*)"', f[9]))
        if txt.get("id") == me or not txt.get("id"):
            continue
        addr = f[7]
        if not ID_RE.fullmatch(txt["id"]) or not valid_ip(addr):
            continue
        if txt["id"] in seen and ":" in addr:               # prefer IPv4
            continue
        # one row per computer and account: a computer that announces itself twice ("Starchaser qa-vm (qa)" and
        # "... #2", each with its own id) is still one computer, and two rows read as two (QA r691)
        who = (f[6].lower(), txt.get("user", ""))
        if hosts.setdefault(who, txt["id"]) != txt["id"]:
            continue
        port = int(txt["pair"]) if txt.get("pair", "").isdigit() and 1 <= int(txt["pair"]) <= 65535 else PORT
        # fleet / size: which fleet it is in and how many computers that fleet has (what it says about itself, only
        # to group the screen: trust never comes from it)
        tag = txt.get("fleet", "") if re.fullmatch(r"[0-9a-f]{8}", txt.get("fleet", "")) else ""
        size = int(txt["size"]) if tag and txt.get("size", "").isdigit() and 1 <= int(txt["size"]) <= 999 else (1 if tag else 0)
        seen[txt["id"]] = {"id": txt["id"], "name": safe_name(txt.get("name", f[3]), "A device"),
                           "user": txt.get("user", "") if valid_user(txt.get("user", "")) else "",
                           "kind": safe_kind(txt.get("kind", "")), "address": addr, "port": port,
                           "fleet": tag, "size": size}
    # a steady order (by name, then address): the list refreshes every few seconds, and rows that swap places
    # under the pointer put a click on the wrong device's Pair. Addresses in number order (.54 before .254),
    # IPv4 before IPv6.
    def where(n):
        ip = ipaddress.ip_address(n["address"].split("%")[0])
        return ip.version, int(ip)
    return sorted(seen.values(), key=lambda n: (n["name"].lower(), *where(n)))


def fleet_badge() -> tuple:
    """(tag, size): this computer's fleet as it is announced: its tag ("" when it is in none) and how many computers
    the fleet has, this one included."""
    try:
        doc = fleet().load()
        tag = (doc.get("fleet") or {}).get("tag") or ""
        if doc["local"].get("left") or not re.fullmatch(r"[0-9a-f]{8}", tag):
            return "", 0
        return tag, 1 + len(doc["machines"])
    except Exception:                                       # (announcing never stops over the list)
        return "", 0


def announce() -> subprocess.Popen:
    """The nearby-computers announcement: the computer's name, a kind and the fleet badge. Never the account name."""
    txt = announce_txt()
    # -f: wait for avahi-daemon instead of giving up when it isn't up (yet)
    return subprocess.Popen(["avahi-publish-service", "-f", announce_name(), SERVICE, "22", *txt],
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def announce_name() -> str:
    return f"Starchaser {socket.gethostname()}"


def announce_txt(tag_size: tuple | None = None) -> list:
    txt = [f"id={device_id()}", f"name={socket.gethostname()}", f"kind={kind()}", f"pair={PORT}"]
    tag, size = fleet_badge() if tag_size is None else tag_size
    if tag:
        txt += [f"fleet={tag}", f"size={size}"]
    return txt


# Finding and pairing are off until the person joins a fleet or turns them on (Settings > Fleet > "Let nearby
# computers find this one"); a switch they set is always kept. The announcement goes out only on a network the
# firewall marks as trusted (or Tailscale): never on public Wi-Fi, and never on a network it can't place.
DISCOVERY = Path(os.environ.get("XDG_CONFIG_HOME") or HOME / ".config") / "starchaser/link.json"
ANNOUNCE_ZONES = ("trusted", "tailscale")
LISTENING = threading.Event()                           # set while the pairing port is open


def discovery_setting():
    """The person's choice: True (on), False (off), or None (not chosen yet: on once in a fleet)."""
    value = jread(DISCOVERY, {}).get("discoverable")
    return value if isinstance(value, bool) else None


def set_discovery(value) -> None:
    if value not in (True, False, None):
        raise ValueError("Choose on, off or auto.")
    data = jread(DISCOVERY, {})
    data = data if isinstance(data, dict) else {}
    if value is None:
        data.pop("discoverable", None)
    else:
        data["discoverable"] = value
    jwrite(DISCOVERY, data)


def discovery_on(setting=None, in_fleet=None) -> bool:
    """Finding and pairing wanted: the person's switch, else whether this computer is in a fleet."""
    setting = discovery_setting() if setting is None else setting
    if setting in (True, False):
        return setting
    return bool(fleet_badge()[0]) if in_fleet is None else in_fleet


def discovery_status() -> dict:
    """What Settings > Fleet shows: the person's choice, whether finding is on now, and whether this network gets it."""
    setting = discovery_setting()
    zone = fleet().network_zone()
    return {"setting": {True: "on", False: "off", None: "auto"}[setting], "on": discovery_on(),
            "inFleet": bool(fleet_badge()[0]), "zone": zone, "announcing": discovery_on() and zone in ANNOUNCE_ZONES}


def listening_wanted() -> bool:
    """The pairing port is open only while finding is on, or a pairing window the person opened is."""
    return discovery_on() or pairing_mode() != ""


def announce_wanted(zone: str | None = None) -> bool:
    zone = fleet().network_zone() if zone is None else zone
    return LISTENING.is_set() and zone in ANNOUNCE_ZONES


def keep_unpairing() -> None:
    """A device unpaired while Sunshine was down keeps its Moonlight pairing until Sunshine answers again: check
    every minute, so Sunshine starting by itself (at login) doesn't let it back in."""
    while True:
        time.sleep(60)
        try:
            sunshine_unpair_waiting()
        except Exception:
            pass


def keep_announcing() -> None:
    """The publisher exits when Avahi restarts (or isn't there): start it again, so this computer never quietly
    drops out of Nearby while everything else looks fine. A rename starts it again too: with -f the publisher
    outlives an Avahi restart and would keep announcing the old name (the host name changed, the fleet's didn't).
    The same when this computer's fleet changes (it joined one, started one, or the fleet grew). It stops while
    finding is off or the network isn't one marked as trusted, and starts again when that changes."""
    pub, name, badge, zone_at, zone = None, "", ("", 0), 0.0, ""
    while True:
        with contextlib.suppress(Exception):            # (a Sunshine file that can't be read never stops announcing)
            sunshine_name_after_rename()
        if pub is None and not LISTENING.is_set():
            LISTENING.wait(60)                          # (nothing is announced while finding is off: wait for it)
            continue
        try:
            if time.monotonic() - zone_at > 10:         # (an `ip route` call at most every 10 seconds)
                zone, zone_at = fleet().network_zone(), time.monotonic()
            now_name, now_badge = socket.gethostname(), fleet_badge()
            want = announce_wanted(zone)
            if pub is not None and (pub.poll() is not None or not want or now_name != name or now_badge != badge):
                if pub.poll() is None:
                    pub.terminate()
                    pub.wait()
                pub = None
            if pub is None and want:
                name, badge, pub = now_name, now_badge, announce()
        except OSError:
            pub = None
        time.sleep(5)


SCHEDULED = Path("/run/systemd/shutdown/scheduled")


def scheduled_shutdown() -> tuple:
    """logind's ScheduledShutdown (a restart or shutdown set with `shutdown +N`, from Mission Control or a
    terminal): (mode, when in microseconds since the epoch), or ("", 0) when none is scheduled. logind keeps the
    same answer in /run/systemd/shutdown/scheduled (USEC=, MODE=; there only while one is scheduled), which is read
    here so the check every 15 s starts no process; D-Bus is asked only when that file can't be understood."""
    try:
        fields = dict(line.split("=", 1) for line in SCHEDULED.read_text().splitlines() if "=" in line)
        return fields["MODE"], int(fields["USEC"])
    except FileNotFoundError:
        return "", 0
    except (OSError, KeyError, ValueError):
        pass
    r = sh("busctl", "--json=short", "get-property", "org.freedesktop.login1", "/org/freedesktop/login1",
           "org.freedesktop.login1.Manager", "ScheduledShutdown", timeout=5)
    try:
        mode, usec = json.loads(r.stdout)["data"]
        return str(mode), int(usec)
    except (ValueError, KeyError, TypeError):
        return "", 0


def shutdown_words(mode: str, usec: int, now: float) -> tuple | None:
    """The notice for a scheduled restart or shutdown: (stage, icon, title, body), or None when there is none. The
    stage (0, then 1 at 5 minutes left, 2 at 1 minute) says when to show it again."""
    what = {"reboot": "restart", "kexec": "restart", "soft-reboot": "restart",
            "poweroff": "shut down", "halt": "shut down"}.get(mode)
    if not what or usec <= 0:
        return None
    left = usec / 1e6 - now
    at = time.strftime("%I:%M %p", time.localtime(usec / 1e6)).lstrip("0")
    mins = max(1, int(-(-left // 60)))
    when = "In less than a minute" if left < 60 else f"In {mins} minute{'s' if mins != 1 else ''}"
    stage = 2 if left <= 60 else 1 if left <= 300 else 0
    verb = "restarts" if what == "restart" else "shuts down"
    return (stage, "system-reboot" if what == "restart" else "system-shutdown", f"This computer {verb} at {at}",
            f"{when}. Save your work now: apps that are still open will close.")


# the shutdown notice on screen now (its id, and the restart it is about): this service restarts after every update,
# and a new one that started from nothing posted a second card and left the first saying a canceled restart was coming
SHUTDOWN_NOTICE = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-shutdown-notice.json"


# (Mission Control's probe looks for this function's name in this file to know the notice is shown here: keep it)
def keep_warning_shutdown() -> None:
    """The wall message `shutdown +N` sends reaches only terminals: say it on the desktop too, in a notice that
    stays up, shown again at 5 minutes and at 1 minute left, and taken back when it is canceled."""
    seen, stage, note = None, -1, ""
    saved = jread(SHUTDOWN_NOTICE, {})
    if isinstance(saved, dict) and str(saved.get("id", "")).isdigit():
        note = str(saved["id"])
        with contextlib.suppress(TypeError, ValueError):
            seen, stage = (str(saved["mode"]), int(saved["usec"])), int(saved["stage"])
    while True:
        with contextlib.suppress(Exception):            # (logind not answering never stops the link service)
            mode, usec = scheduled_shutdown()
            words = shutdown_words(mode, usec, time.time())
            if words is None:
                if note:
                    sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-r", note, "-a", "Starchaser", "-i", "dialog-information", "-t", "8000",
                       "Canceled", "This computer won't restart or shut down after all.", env=session_env())
                    SHUTDOWN_NOTICE.unlink(missing_ok=True)
                seen, stage, note = None, -1, ""
            elif (mode, usec) != seen or words[0] > stage:
                again = ["-r", note] if note else []
                r = sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-p", *again, "-a", "Starchaser", "-i", words[1], "-u", "critical", "-t", "0",
                       words[2], words[3], env=session_env())
                if r.returncode == 0 and r.stdout.strip().isdigit():
                    note = r.stdout.strip()
                seen, stage = (mode, usec), words[0]
                if note:
                    jwrite(SHUTDOWN_NOTICE, {"id": note, "mode": mode, "usec": usec, "stage": stage})
        time.sleep(15)


# ---------------------------------------------------------------------------------------------- trust
def authorize(peer: dict) -> None:
    """Let the peer's key run `starchaser link serve` as this user, and nothing else."""
    if not re.fullmatch(r"ssh-ed25519 [A-Za-z0-9+/=]+", peer["key"]) or not re.fullmatch(r"[0-9a-f]{16}", peer["id"]):
        raise ValueError("bad key or id")
    with state_lock(), fleet().ssh_lock():                 # (the lock every authorized_keys writer shares)
        AUTH.parent.mkdir(mode=0o700, exist_ok=True)
        lines = AUTH.read_text().splitlines() if AUTH.exists() else []
        lines = [l for l in lines if f"starchaser-link:{peer['id']}" not in l]
        expiry = f'expiry-time="{help_expiry()}",' if peer.get("role") == "helper" else ""
        lines.append(f'{expiry}command="{SELF_BIN} serve {peer["id"]}",restrict {peer["key"]} starchaser-link:{peer["id"]}')
        fleet().write_atomic(AUTH, "\n".join(lines) + "\n", 0o600)


def pairing_mode() -> str:
    data = jread(STATE / "pairing-mode.json", {})
    try:
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
        return data["mode"] if (data.get("boot") == boot and data.get("mode") in ("fleet", "help")
                                and 0 <= time.monotonic() - data["opened"] < 600) else ""
    except (OSError, KeyError, TypeError):
        return ""


def pairing_window_open() -> bool:
    return pairing_mode() == "fleet" and jread(STATE / "pairing-mode.json", {}).get("window") is True


def set_pairing_mode(mode: str, window: bool = False) -> None:
    if mode not in ("fleet", "help", "off"):
        raise ValueError("Choose fleet, help or off.")
    jwrite(STATE / "pairing-mode.json", {"mode": mode, "window": bool(window), "opened": time.monotonic(),
                                       "boot": Path("/proc/sys/kernel/random/boot_id").read_text().strip()})


HELP_LEASE = STATE / "help-lease.json"
HELP_END_NOTICE = STATE / "help-ended-notice.json"
HELP_SECONDS = 2 * 60 * 60


def help_status() -> dict:
    """A grant lasts this boot only. A corrupt/missing lease fails closed, including legacy help grants."""
    lease = jread(HELP_LEASE, {})
    helpers = [p for p in load_peers() if p.get("role") == "helper"]
    try:
        elapsed = time.monotonic() - lease["started"]
        valid = (lease["boot"] == Path("/proc/sys/kernel/random/boot_id").read_text().strip()
                 and 0 <= elapsed < HELP_SECONDS and any(p["id"] == lease["id"] for p in helpers))
    except (OSError, KeyError, TypeError):
        valid, elapsed = False, HELP_SECONDS
    if helpers and not valid:
        end_help()
    return {"active": valid, "name": safe_name(lease.get("name")) if valid else "",
            "remaining": max(0, int(HELP_SECONDS - elapsed)) if valid else 0}


def help_visible() -> dict:
    status = help_status()
    if status["active"]:
        with state_lock():
            lease = jread(HELP_LEASE, {})
            lease["visibleAt"] = time.monotonic()
            jwrite(HELP_LEASE, lease)
    return status


def help_tick() -> dict:
    status = help_status()
    if status["active"]:
        lease = jread(HELP_LEASE, {})
        stamp = lease.get("visibleAt", lease.get("started", 0))
        if not 0 <= time.monotonic() - stamp < 20:
            end_help()
            return {"active": False, "name": "", "remaining": 0}
    if not status["active"] and HELP_END_NOTICE.exists():
        # A remote End help may have terminated its own SSH session before it could
        # announce completion. The local daemon finishes that durable notice.
        finish_help_notice(fleet().end_fleet_sessions())
    return status


def help_shell(pid: str) -> None:
    """Check every helper SSH sign-in before its command, including during boot before the daemon starts."""
    status = help_tick()
    lease = jread(HELP_LEASE, {})
    if not status["active"] or lease.get("id") != pid:
        raise ValueError("Help ended. Ask for help again on that computer.")
    shell = pwd.getpwuid(os.getuid()).pw_shell or "/bin/sh"
    command = os.environ.get("SSH_ORIGINAL_COMMAND", "")
    fleet().record_activity(pid, status["name"], "Signed in")
    os.execv(shell, [shell, "-c", command] if command else [shell, "-l"])



def help_targets_tick() -> None:
    for target in [p for p in load_peers() if p.get("role") == "help-target"]:
        # Internet help owns its own authenticated heartbeat and temporary local tunnel.
        entry = next((e for e in fleet().load()["machines"] if e.get("helpOwner") and e["id"] == target.get("helpEntry")), None)
        if entry and (entry.get("port", 22) != 22 or entry.get("hostname", "").endswith(".invalid")):
            continue
        ended = time.time() - target.get("helpStarted", time.time()) >= HELP_SECONDS
        if not ended:
            result = ssh_to(target, "status", timeout=5)
            # An authenticated refusal means its helper keys were revoked. A network outage
            # is not evidence of revocation: retain the target until expiry or a later check.
            ended = result.returncode != 0 and ("Permission denied (" in (result.stderr or "") or '"not paired"' in (result.stdout or ""))
        if ended:
            entries = [e for e in fleet().load()["machines"] if e.get("helpOwner") and e["id"] == target.get("helpEntry")]
            # The target owns the access. Remove only this local, managed-only entry, never membership.
            for entry in entries:
                fleet().remove_flow(entry["id"])
            forget(target["id"])

def keep_help_temporary() -> None:
    """Every 2 seconds while help is under way (either way, or a notice is waiting to be finished). Otherwise a grant
    or a pairing only starts with a write to the devices folder, so the loop waits for one (a minute at most)."""
    changes = FolderChanges(STATE)
    while True:
        busy = True
        try:
            busy = help_tick()["active"] or HELP_END_NOTICE.exists()
            help_targets_tick()
            busy = busy or any(p.get("role") == "help-target" for p in load_peers())
        except Exception as error:
            print(f"starchaser link: couldn't check help expiry: {error}", file=sys.stderr)
        if busy:
            time.sleep(2)
        else:
            changes.wait(60)


def help_expiry() -> str:
    lease = jread(HELP_LEASE, {})
    expiry = lease.get("expires", 0)
    if type(expiry) is not int or expiry <= time.time():
        raise ValueError("Help ended. Ask for help again on this computer.")
    return time.strftime("%Y%m%d%H%M%SZ", time.gmtime(expiry))


def trust_help(peer: dict, address: str) -> dict | None:
    """Help is one-way account access, never membership in either household's fleet."""
    F = fleet()
    if F.get("dev-" + peer["id"]):
        raise ValueError("Remove this computer from the shared fleet before setting up one-way help.")
    if peer["role"] == "helper":
        key = " ".join(str(peer.get("managePub") or "").split()[:2])
        if not F.KEY_RE.fullmatch(key) or key == peer.get("key"):
            raise ValueError("The helper needs a personal sign-in key. Update it and try again.")
        if any(p.get("role") == "helper" for p in load_peers()):
            end_help()
        jwrite(HELP_LEASE, {"id": peer["id"], "name": safe_name(peer.get("name")),
                           "boot": Path("/proc/sys/kernel/random/boot_id").read_text().strip(),
                           "started": time.monotonic(), "expires": int(time.time()) + HELP_SECONDS})
        authorize(peer)
        remember(peer, address, registry=False)
        F.authkeys("add", "starchaser-help:" + peer["id"] + ":" + peer["id"], key,
                   options=f'command="{SELF_BIN} help-shell {peer["id"]}",expiry-time="{help_expiry()}",no-agent-forwarding,no-port-forwarding,no-X11-forwarding')
    else:
        peer = dict(peer, helpStarted=int(time.time()))
        remember(peer, address, registry=False)             # no inbound link key and no reciprocal management
        relay = peer.get("relayPort")
        if relay is not None and (type(relay) is not int or not 1 <= relay <= 65535 or address != "127.0.0.1"):
            raise ValueError("That help connection isn't a local authenticated forward.")
        e = F.add_machine("help-" + peer["id"] + ".invalid" if relay else address, user=peer["user"],
                          port=relay or 22, label=safe_name(peer.get("name")), via="pairing")
        with F.editing() as doc:
            e = F.find(doc, e["id"])
            if relay:
                e["chosenAddress"] = e["addresses"]["last"] = address
            e.update(checkedHostKeys=[peer["hostkey"]], helpOwner=device_id(), fleetAccess="mine",
                     onlyMineManages=True, addedBy=device_id(), managers=[device_id()],
                     manage={"state": "ready", "since": int(time.time())})
        remember(dict(peer, helpEntry=e["id"]), address, registry=False)
        F.reconcile_known_hosts()
        return e
    return None


def end_help() -> dict:
    # Serialize grant teardown so concurrent expiry, locking and End help notify once.
    with state_lock():
        return _end_help()


def _end_help() -> dict:
    set_pairing_mode("off")
    F = fleet()
    helpers = [p for p in load_peers() if p.get("role") == "helper"]
    for p in helpers:
        forget(p["id"])
    with F.ssh_lock():
        lines = AUTH.read_text().splitlines() if AUTH.exists() else []
        tagged = [l for l in lines if re.search(r"starchaser-help:[0-9a-f]{16}:[0-9a-f]{16}\s*$", l)]
        keys = {key for l in tagged if (key := F.authorized_key_public(l))}
        # Other computers in the helper's fleet arrived through the one-way key relay, not peers.json.
        # Capture their actual public keys before deleting the tagged lines, then revoke every copy.
        keep = [l for l in lines if l not in tagged and F.authorized_key_public(l) not in keys]
        if lines != keep:
            F.write_atomic(AUTH, "\n".join(keep) + ("\n" if keep else ""), 0o600)
    HELP_LEASE.unlink(missing_ok=True)
    if helpers:
        jwrite(HELP_END_NOTICE, {"names": ", ".join(safe_name(p.get("name")) for p in helpers)})
    result = F.end_fleet_sessions() if helpers or tagged or HELP_END_NOTICE.exists() else {"complete": True, "ended": 0}
    finish_help_notice(result)
    return result


def finish_help_notice(result: dict) -> None:
    with state_lock():
        notice = jread(HELP_END_NOTICE, {})
        if not notice.get("names"):
            return
        body = f"{notice['names']} can no longer reach this computer." if result.get("complete") else "Their keys were removed, but some connections couldn't be ended. Turn off Remote login in Settings › Security."
        notify_desktop(session_env(), "network-workgroup", "Help ended.", html.escape(body))
        HELP_END_NOTICE.unlink(missing_ok=True)


def trust(peer: dict, address: str, registry: bool = True) -> None:
    """Both halves of pairing at once (its key may log in, and it's a paired device), so nothing that tidies keys
    without a device (listing) ever sees one half without the other. registry: also put it in the fleet list (not
    when the list itself is what asked)."""
    if peer.get("role") in ("helper", "help-target"):
        return trust_help(peer, address)
    with state_lock():
        authorize(peer)
        remember(peer, address, registry)


def adopt(peer: dict, address: str, quiet: bool = False) -> None:
    """A computer another fleet computer paired: trust it here too (the fleet list carries its link key and the host
    key that pairing verified, over the paired link). Said on screen, so it is never silent; quiet: on the computer
    that just joined, about a computer that was in the fleet already (it didn't "just join": the join box lists it)."""
    with state_lock():
        try:
            member = fleet().is_member(peer["id"], peer.get("key") or "")
        except Exception:                                   # (an unreadable list trusts nobody new)
            member = False
        if not member:
            return
        known = any(p["id"] == peer["id"] for p in load_peers())
        trust(peer, address, registry=False)
    if not known and not quiet:
        notify_desktop(session_env(), "network-workgroup", f"{html.escape(safe_name(peer.get('shown') or peer.get('name')))} joined your fleet",
                       "It was added on another of your computers. It's in Settings > Fleet.")


def forget_device(pid: str, revoked: bool = False) -> None:
    """The fleet removed a device: drop every trust in it here. When it was the last device allowed to see this
    screen, ask (once) whether to turn remote desktop off."""
    with state_lock():
        old = next((p for p in load_peers() if p["id"] == pid), None)
        had_remote = remote_allowed(pid)
    forget(pid)
    left = jread(REMOTE_OK, {})
    if had_remote and not (isinstance(left, dict) and left) and shutil.which("sunshine"):
        spawn_self("rd-off-ask", safe_name((old or {}).get("name")))


def drop_orphan_keys(ids: set) -> None:
    """A link key in authorized_keys whose device isn't paired any more (a pairing that was lost half-way) can't be
    used (serve refuses it); take it out too. Call with the state lock held."""
    with fleet().ssh_lock():                                # read and write under one lock: no other writer's line lost
        if not AUTH.exists():
            return
        lines = AUTH.read_text().splitlines()
        keep = [l for l in lines
                if not ((m := re.search(r"starchaser-link:([0-9a-f]{16})\s*$", l)) and " serve " in l and m.group(1) not in ids)]
        if keep != lines:
            fleet().write_atomic(AUTH, "\n".join(keep) + "\n", 0o600)


def remember(peer: dict, address: str, registry: bool = True) -> None:
    with state_lock():
        old = next((p for p in load_peers() if p["id"] == peer["id"]), None)
        entry = {k: peer.get(k, "") for k in ("id", "name", "user", "kind", "key", "hostkey", "role", "managePub", "helpStarted", "helpEntry")}
        entry.update(name=safe_name(entry["name"], "A device"), kind=safe_kind(entry["kind"]))
        changed = bool(old and (old.get("key") != peer.get("key") or old.get("hostkey") != peer.get("hostkey")))
        if changed:
            # the same device id with other keys is, as far as anyone can tell, another device: what the person here
            # allowed the old one (remote desktop, its Moonlight pairing) does not carry over to it
            drop_grants(peer["id"], old)
        # this same device paired again on purpose: a by-name Moonlight removal still waiting from its earlier unpair
        # must not catch the pairing it may make from now on. Another device that only shares the name (another
        # id, or this id with other keys) leaves it waiting.
        clients = jread(SUN_CLIENTS, {})
        name = moonlight_name(entry["name"])
        if not changed and isinstance(clients, dict) and name in (clients.get("_unpair_names") or []):
            ids = clients.get("_unpair_name_ids") if isinstance(clients.get("_unpair_name_ids"), dict) else {}
            if set(ids.get(name) or [peer["id"]]) <= {peer["id"]}:
                clients["_unpair_names"] = [n for n in clients["_unpair_names"] if n != name]
                ids.pop(name, None)
                clients["_unpair_name_ids"] = ids
                jwrite(SUN_CLIENTS, clients)
        peers = [p for p in load_peers() if p["id"] != peer["id"]]
        # adopted: trusted because the fleet list has it (never checked by a code here), so it goes with its entry
        peers.append({k: v for k, v in entry.items() if k != "adopted"} | {"address": address, "paired": int(time.time())}
                     | ({} if registry else {"adopted": True}))
        jwrite(PEERS, peers)
        if peer.get("hostkey"):
            known = [l for l in (KNOWN.read_text().splitlines() if KNOWN.exists() else []) if not l.startswith(f"starchaser-{peer['id']} ")]
            known.append(f"starchaser-{peer['id']} {peer['hostkey']}")
            KNOWN.write_text("\n".join(known) + "\n")
        if registry:                                        # the fleet list (lock order: devices, then the list)
            fleet().upsert_paired(peer, address)


def forget(pid: str) -> bool:
    """Drop every trust in a device: its key, its host key, its remote desktop permission and the Moonlight pairing
    it made with this computer's Sunshine. False when that pairing couldn't be removed yet (Sunshine isn't
    running): the pairing daemon tries again every minute, and so do list and the next remote desktop."""
    with state_lock():
        old = next((p for p in load_peers() if p["id"] == pid), None)
        jwrite(PEERS, [p for p in load_peers() if p["id"] != pid])
        (PAIRCHECK / f"{pid}.json").unlink(missing_ok=True)  # a pairing check left over can never bring it back
        revoked_keys = {k for k in (old.get("key"), old.get("managePub")) if k} if old else set()
        if AUTH.exists():
            with fleet().ssh_lock():
                fleet().write_atomic(AUTH, "\n".join(l for l in AUTH.read_text().splitlines()
                                                     if f"starchaser-link:{pid}" not in l
                                                     and not l.rstrip().endswith(f"starchaser-manage:{pid}")
                                                     and fleet().authorized_key_public(l) not in revoked_keys) + "\n", 0o600)
        if KNOWN.exists():
            KNOWN.write_text("\n".join(l for l in KNOWN.read_text().splitlines() if not l.startswith(f"starchaser-{pid} ")) + "\n")
        drop_grants(pid, old)
    with contextlib.suppress(OSError):
        fleet().set_local(sessionRevokePending=True)
    if old and old.get("role") == "help-target":
        notify_desktop(session_env(), "network-workgroup", "Help ended.", html.escape(safe_name(old.get("name"))) + " ended help.")
    return sunshine_unpair_waiting()


def moonlight_name(name) -> str:
    """The name a device's Moonlight pairing gets on this Sunshine (rd-pin passes the asker's host name, cleaned)."""
    return re.sub(r"[^\w.-]", "", str(name or ""))[:40]


def drop_grants(pid: str, old=None) -> None:
    """Take back what the person here allowed a device (remote desktop, the Wake on LAN set-up note, its Moonlight
    pairing with this Sunshine), keeping the pairing itself. A Moonlight pairing made before Starchaser noted them
    (sunshine-clients.json) is found by the device's name in Sunshine's own list instead; a device that never
    paired Moonlight here has nothing taken away (and Unpair doesn't claim it had)."""
    with state_lock():
        for f in (REMOTE_OK, STATE / "remote-used.json", WAKE):
            d = jread(f, {})
            if isinstance(d, dict) and pid in d:
                d.pop(pid)
                jwrite(f, d)
        clients = jread(SUN_CLIENTS, {})
        if not isinstance(clients, dict):
            clients = {}
        name = moonlight_name(old.get("name")) if old else ""
        if clients.get(pid):
            clients["_unpair"] = list(dict.fromkeys(list(clients.get("_unpair") or []) + list(clients.pop(pid))))
        elif name and shutil.which("sunshine"):
            saved = sunshine_saved_clients()
            if saved is None:                               # can't tell from here: ask Sunshine by name when it answers
                clients["_unpair_names"] = list(dict.fromkeys(list(clients.get("_unpair_names") or []) + [name]))
                ids = clients.get("_unpair_name_ids") if isinstance(clients.get("_unpair_name_ids"), dict) else {}
                ids[name] = list(dict.fromkeys(list(ids.get(name) or []) + [pid]))  # (whose removal it is)
                clients["_unpair_name_ids"] = ids
            else:
                found = sorted(u for u, n in saved.items() if n == name)
                if not found:
                    return
                clients["_unpair"] = list(dict.fromkeys(list(clients.get("_unpair") or []) + found))
        else:
            return
        jwrite(SUN_CLIENTS, clients)


def sunshine_saved_clients():
    """The Moonlight pairings this computer's Sunshine has saved, as {uuid: name}, read from its own state file (so
    it works while Sunshine isn't running): {} when it has none (or Sunshine never ran here), None when the file
    doesn't say (an older Sunshine that kept no names)."""
    f = SUN / "sunshine_state.json"
    try:                                                    # (sunshine.conf may keep it somewhere else)
        conf = (SUN / "sunshine.conf").read_text()
    except OSError:
        conf = ""
    for line in conf.splitlines():
        k, eq, v = line.partition("=")
        if eq and k.strip() == "file_state" and v.strip():
            v = Path(v.strip()).expanduser()
            f = v if v.is_absolute() else SUN / v
    if not f.exists():
        return {}
    try:
        root = json.loads(f.read_text()).get("root")
    except (OSError, ValueError, AttributeError):
        return None
    if not isinstance(root, dict):
        return None
    named = root.get("named_devices")
    if named in ("", None, []):                             # (an empty list is written as "")
        return None if root.get("devices") else {}
    if not isinstance(named, list):
        return None
    return {x["uuid"]: str(x.get("name") or "") for x in named if isinstance(x, dict) and isinstance(x.get("uuid"), str)}


def peer(pid: str) -> dict:
    p = next((p for p in load_peers() if p["id"] == pid), None)
    if not p:
        sys.exit(f"no paired device {pid}")
    return p


def learn_addresses(pid: str, chosen: str, found: list, tailscale: str) -> bool:
    """Addresses the fleet list knows for a paired computer that this one hasn't seen it at (another computer found
    it there, or the person typed one): link calls try them too, instead of only where this computer last reached
    it. A typed address (chosen) is tried first. Returns whether peers.json changed."""
    with state_lock():
        if not peers_file_ok():
            return False
        peers = load_peers()
        q = next((x for x in peers if x["id"] == pid), None)
        if q is None:
            return False
        before = json.dumps(q, sort_keys=True)
        if chosen and valid_host(chosen):
            q["address"] = chosen
        have = candidates(q)
        q["addresses"] = (list(q.get("addresses") or []) + [a for a in found if a and valid_host(a) and a not in have])[:8]
        if tailscale and valid_ip(tailscale) and not q.get("tailscale"):
            q["tailscale"] = tailscale
        if json.dumps(q, sort_keys=True) == before:
            return False
        jwrite(PEERS, peers)
        return True


def candidates(p: dict) -> list:
    """Where to reach a paired device: its current local address first, then other addresses it had, then its
    Tailscale address (works away from home). Only values that are plainly addresses."""
    out = []
    for a in [p.get("address")] + list(p.get("addresses") or []) + [p.get("tailscale")]:
        if a and valid_host(a) and a not in out:
            out.append(a)
    return out


def ssh_to(p: dict, command: str, timeout=8, input=None, binary_in=None, data=None) -> subprocess.CompletedProcess:
    """Run a link verb on a paired device, trying each address it might be at (ssh exits 255 when it can't connect)."""
    addrs = candidates(p) or [""]
    r = changed = None
    for addr in addrs:
        r = ssh_once(p, addr, command, timeout, input, binary_in, data)
        if r.returncode != 255 or binary_in is not None:
            if r.returncode != 255:
                p["address"] = addr
            return r
        # the computer itself answered (its pinned host key checked out) and turned this one away: no other address
        # will say otherwise, and the caller needs that answer, not a later "no route"
        err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
        if "Permission denied (" in err:
            return r
        if "Host key verification failed" in err or "IDENTIFICATION HAS CHANGED" in err:
            changed = r                                     # (kept: a later address that doesn't answer hides it)
    return changed or r


def ssh_command(p: dict, addr: str, command: str) -> list:
    # the user goes in with -l and the address after "--": neither can ever be read as an ssh option
    cmd = ["ssh", "-i", str(KEY), "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=3",
           "-o", f"UserKnownHostsFile={KNOWN}", "-o", f"HostKeyAlias=starchaser-{p['id']}", "-o", "StrictHostKeyChecking=yes",
           "-o", "LogLevel=ERROR", "-l", p.get("user", ""), "--", addr, command]
    return cmd


def ssh_once(p: dict, addr: str, command: str, timeout=8, input=None, binary_in=None, data=None) -> subprocess.CompletedProcess:
    cmd = ssh_command(p, addr, command)
    if not valid_peer(p) or not valid_host(addr):
        binary = data is not None or binary_in is not None
        bad = "not a usable user name or address"
        return subprocess.CompletedProcess(cmd, 255, b"" if binary else "", bad.encode() if binary else bad)
    if data is not None:
        try:
            return subprocess.run(cmd, input=data, capture_output=True, timeout=30)
        except subprocess.TimeoutExpired:
            return subprocess.CompletedProcess(cmd, 124, b"", TIMED_OUT.encode())
        except OSError as e:
            return subprocess.CompletedProcess(cmd, 1, b"", str(e).encode())
    if binary_in is not None:
        try:
            return subprocess.run(cmd, stdin=binary_in, capture_output=True, timeout=None)
        except OSError as e:
            return subprocess.CompletedProcess(cmd, 1, b"", str(e).encode())
    return sh(*cmd, timeout=timeout, input=input)


# ---------------------------------------------------------------------------------------------- pairing
def port_owner():
    """The account (uid) listening on the pairing port, or None when that can't be told."""
    want = f"{PORT:04X}"
    for table in ("/proc/net/tcp6", "/proc/net/tcp"):
        try:
            lines = Path(table).read_text().splitlines()[1:]
        except OSError:
            continue
        for line in lines:
            f = line.split()
            if len(f) > 7 and f[3] == "0A" and f[1].rsplit(":", 1)[-1] == want:
                try:
                    return int(f[7])
                except ValueError:
                    return None
    return None


def fleet_owner() -> dict:
    uid = port_owner()
    if uid is None or uid == os.getuid():
        return {}
    try:
        account = pwd.getpwuid(uid)
        name = safe_name(account.pw_gecos.split(",", 1)[0] or account.pw_name)
        return {"uid": uid, "user": account.pw_name, "name": name}
    except KeyError:
        return {"uid": uid, "name": "another account"}


def daemon() -> None:
    ensure_identity()
    fleet().reconcile(THIS)
    security_sync()
    fleet().reconcile(THIS)
    help_status()
    threading.Thread(target=keep_help_temporary, daemon=True).start()
    threading.Thread(target=keep_unpairing, daemon=True).start()
    threading.Thread(target=keep_syncing, daemon=True).start()
    threading.Thread(target=keep_warning_shutdown, daemon=True).start()
    if shutil.which("avahi-publish-service"):
        threading.Thread(target=keep_announcing, daemon=True).start()
    while True:
        # the pairing port opens only after this computer joins a fleet or the person turns finding on: both are a
        # write to a file in one of these folders (fleet.json and link.json, pairing-mode.json)
        changes = FolderChanges(DISCOVERY.parent, STATE)
        try:
            while not listening_wanted():
                changes.wait(60)
        finally:
            changes.close()
        srv = open_pairing_port()
        LISTENING.set()
        try:
            serve_pairing(srv)
        finally:
            LISTENING.clear()
            srv.close()


def open_pairing_port() -> socket.socket:
    said = False
    while True:
        srv = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srv.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
        try:
            srv.bind(("::", PORT))
            srv.listen(4)
            break
        except OSError as e:
            srv.close()
            # a second copy (or something else on the port): say so plainly, and leave the running copy's
            # pairing requests alone
            if e.errno != errno.EADDRINUSE:
                print(f"starchaser link: device pairing could not start: {e.strerror or e}", file=sys.stderr)
                sys.exit(1)
            if not said:
                print("starchaser link: device pairing can't start because its network port is already in use "
                      "(it may already be running; it starts by itself with your session).", file=sys.stderr)
                said = True
            if port_owner() in (os.getuid(), None):
                sys.exit(1)                                 # this account's own copy (or unknown): as before
            # another account on this computer holds it: keep this account's catch-up running, and take the port
            # over when that account lets it go (before, the service restarting every few seconds did that)
            time.sleep(30)
    # only now that this copy owns the port: requests left over from the last run are stale
    PENDING.mkdir(parents=True, exist_ok=True)
    for f in PENDING.glob("*"):
        with contextlib.suppress(FileNotFoundError):
            f.unlink()
    return srv


def serve_pairing(srv: socket.socket) -> None:
    """Answer pairing requests until finding is turned off (the caller then closes the port)."""
    srv.settimeout(5)
    while listening_wanted():
        try:
            conn, addr = srv.accept()
        except socket.timeout:
            continue
        conn.settimeout(None)
        src = addr[0].replace("::ffff:", "")
        # anyone on the network can knock: at most a few requests at once, one waiting per address
        if not _SLOTS.acquire(blocking=False):
            _busy(conn)
            continue
        with _BUSY_LOCK:
            if src in _BUSY:
                _SLOTS.release()
                _busy(conn)
                continue
            _BUSY.add(src)
        threading.Thread(target=_handle_slot, args=(conn, addr[0], src), daemon=True).start()


_SLOTS = threading.BoundedSemaphore(8)
_PAIR_SLOT = threading.BoundedSemaphore(1)
_BUSY: set = set()
_BUSY_LOCK = threading.Lock()
# A request the person here declined: the same device (by id) or the same address (an IPv6 /64) gets a quiet
# "busy" for a while, growing with each decline (1 min, 2, 4 ... up to an hour), so nobody can keep a pairing
# notification on screen by asking again and again.
_DECLINED: dict = {}
# An older Starchaser that asked to pair (it doesn't know this version's steps, so its own screen only says it
# failed): the person here is told once per asker (by id and by address) per hour, and at most once a minute overall.
_OLDER_TOLD: dict = {}
OLDER_EVERY = 3600


def older_should_tell(dev_id: str, src: str, now_: float | None = None) -> bool:
    """Is this the first older-Starchaser request from this asker in the last hour (and the first from anyone in the
    last minute)? Records it when it is."""
    t = time.time() if now_ is None else now_
    keys = _decline_keys(dev_id, src)
    with _BUSY_LOCK:
        if any(t - _OLDER_TOLD.get(k, -1e12) < OLDER_EVERY for k in keys) or t - _OLDER_TOLD.get("any", -1e12) < 60:
            return False
        for k in keys + ["any"]:
            _OLDER_TOLD[k] = t
        if len(_OLDER_TOLD) > 512:                              # (a flood of made-up ids can't grow it forever)
            for k in [k for k, v in _OLDER_TOLD.items() if t - v >= OLDER_EVERY]:
                _OLDER_TOLD.pop(k, None)
        return True


def older_words(shown: str) -> tuple:
    """The notification for an older Starchaser that asked to pair (shown: its name, already escaped)."""
    return (f"{shown} needs an update to pair",
            f"{shown} needs an update before it can pair with this computer. Update it (Settings > Updates), then try again.")


def _busy(conn) -> None:
    try:
        conn.settimeout(2)
        conn.sendall(b'{"result": "busy"}\n')
    except OSError:
        pass
    conn.close()


def _decline_keys(dev_id: str, src: str) -> list:
    try:
        ip = ipaddress.ip_address(src)
        net = str(ipaddress.ip_network(f"{ip}/64", strict=False)) if ip.version == 6 else str(ip)
    except ValueError:
        net = src
    return ["id:" + dev_id, "net:" + net]


def _cooling(dev_id: str, src: str) -> bool:
    with _BUSY_LOCK:
        return any(_DECLINED.get(k, (0, 0))[1] > time.time() for k in _decline_keys(dev_id, src))


def _declined(dev_id: str, src: str) -> None:
    with _BUSY_LOCK:
        for k in _decline_keys(dev_id, src):
            n = _DECLINED.get(k, (0, 0))[0] + 1
            _DECLINED[k] = (n, time.time() + min(60 * 2 ** (n - 1), 3600))


def _handle_slot(conn, addr: str, src: str) -> None:
    try:
        first = json.loads(readline(conn, limit=4 * 1024 * 1024, deadline=time.time() + 3))
        if isinstance(first, dict) and "security" in first:
            F = fleet()
            if F.accept_security(first["security"]):
                F.reconcile(THIS)
            tell(conn, {"security": F.security_payload()})
        elif isinstance(first, dict) and first.get("fleetJoin") == 1:
            fleet_join_hello(conn, src, first)
        elif not _PAIR_SLOT.acquire(blocking=False):
            _busy(conn)
        else:
            try:
                handle_pair(conn, addr, first=first)
            finally:
                _PAIR_SLOT.release()
    except (OSError, ValueError, TypeError):
        pass
    finally:
        conn.close()
        with _BUSY_LOCK:
            _BUSY.discard(src)
        _SLOTS.release()


FLEET_SOCK = Path("/run/starchaser/fleet/people.sock")
FLEET_JOIN_LONGEST = 25 * 60               # a code join waits up to 10 minutes, plus More time once, plus answers


def fleet_join_hello(conn, src: str, first: dict) -> None:
    """Fleet v2 (docs/fleet/rules.md 16.12): this daemon owns port 47744, so it hands a join hello to this computer's
    fleet service and passes the conversation through unchanged. The fleet service decides everything; with no
    fleet here (no service socket) the hello gets no answer at all."""
    if not FLEET_SOCK.exists():
        return
    try:
        svc = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        svc.connect(str(FLEET_SOCK))
        svc.sendall((json.dumps({"op": "hello", "address": src, "first": first}) + "\n").encode())
    except OSError:
        return
    end = time.time() + FLEET_JOIN_LONGEST
    try:
        conn.setblocking(True)
        while time.time() < end:
            r, _, _ = select.select([conn, svc], [], [], 30)
            if not r:
                continue
            done = False
            for s_ in r:
                data = s_.recv(65536)
                if not data:
                    done = True
                    break
                (svc if s_ is conn else conn).sendall(data)
            if done:
                break
    except OSError:
        pass
    finally:
        with contextlib.suppress(OSError):
            svc.close()


def fleet_invite_send(name: str, flagship: str) -> int:
    """Fleet v2 (rule 36.2): an invite's token, read from standard input, sent to a paired computer over the pairing
    link. It is never printed or logged here."""
    token = sys.stdin.readline(4097).strip()
    p = next((x for x in load_peers() if safe_name(x.get("name")).lower() == name.lower()), None)
    if not p or not token:
        return 1
    r = ssh_to(p, "fleet-invite", timeout=20, input=json.dumps({"token": token, "from": flagship}) + "\n")
    return 0 if r.returncode == 0 and '"ok": true' in (r.stdout or "") else 1


def serve_fleet_invite(pid: str, name: str, env: dict) -> dict:
    """The invited computer (rule 36.2): the invite goes to this computer's fleet service, and the person here is told.
    Root here says yes with `sudo starchaser fleet join --paired NAME`."""
    try:
        doc = json.loads(sys.stdin.readline(4097))
    except ValueError:
        return {"ok": False}
    if not FLEET_SOCK.exists() or not isinstance(doc, dict):
        return {"ok": False}
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as svc:
            svc.settimeout(20)
            svc.connect(str(FLEET_SOCK))
            svc.sendall((json.dumps({"op": "invite-received", "token": str(doc.get("token", "")),
                                     "from": str(doc.get("from", "")), "address": ""}) + "\n").encode())
            answer = json.loads(readline(svc, limit=65536, deadline=time.time() + 20) or "{}")
    except (OSError, ValueError, TimeoutError):
        return {"ok": False}
    if answer.get("ok"):
        flag = safe_name(doc.get("from"))
        notify_desktop(env, "network-workgroup", f"{flag} invites this computer to your fleet",
                       f"Join in Settings > Fleet, or run: sudo starchaser fleet join --paired {flag}")
    return {"ok": bool(answer.get("ok"))}


def valid_hello(them) -> bool:
    """A pairing hello from the network: only the fields we use, of the shapes we expect."""
    if not isinstance(them, dict):
        return False
    for k in ("key", "hostkey"):
        if not isinstance(them.get(k), str) or not re.fullmatch(r"ssh-ed25519 [A-Za-z0-9+/=]+", them[k]):
            return False
    for k in ("name", "kind"):
        if not isinstance(them.get(k, ""), str):
            return False
    if not valid_user(them.get("user")):                    # it goes onto ssh's command line later
        return False
    if "proto" in them and (type(them["proto"]) is not int or not 0 <= them["proto"] < 1000):
        return False
    if type(them.get("generation", 0)) is not int or not 0 <= them.get("generation", 0) < fleet().MAX_COUNTER:
        return False
    return bool(ID_RE.fullmatch(str(them.get("id", ""))))


def readline(conn, limit=8192, deadline=None) -> str:
    """One line from the socket; with a deadline (time.time()), the whole line must arrive by then."""
    buf = b""
    while not buf.endswith(b"\n") and len(buf) < limit:
        if deadline is not None:
            left = deadline - time.time()
            if left <= 0:
                raise TimeoutError("too slow")
            conn.settimeout(left)
        c = conn.recv(1)
        if not c:
            break
        buf += c
    return buf.decode(errors="replace").strip()


def tell(conn, msg: dict) -> None:
    conn.sendall((json.dumps(msg) + "\n").encode())


def read_msg(conn, seconds: float) -> dict:
    """The next message, or {} if the connection closed or sent something that isn't one."""
    try:
        m = json.loads(readline(conn, deadline=time.time() + seconds) or "{}")
    except ValueError:
        return {}
    return m if isinstance(m, dict) else {}


def closed(conn) -> bool:
    """Has the other side hung up? (Nothing else arrives while it waits for an answer.)"""
    try:
        r, _, _ = select.select([conn], [], [], 0)
        return bool(r) and conn.recv(1, socket.MSG_PEEK) == b""
    except OSError:
        return True


def request_kind(intent, dev: str) -> tuple:
    """(ask, again): what a request to pair means for this computer. ask: "join" (it joins this computer's fleet),
    "add" (it adds this computer to its fleet), "start" (neither is in a fleet yet: the two of them start one) or
    "merge" (both are in fleets: they become one). again: it was removed from this fleet before. intent is what the
    asker says it is doing ("join" or "invite"; an older asker says nothing)."""
    try:
        doc = fleet().load()
    except Exception:                                       # (the question is still asked)
        return "join", False
    alone = not any(e.get("link") for e in doc["machines"])
    tagged = bool((doc.get("fleet") or {}).get("tag")) and not doc["local"].get("left")
    if intent == "invite":
        ask = "add" if alone else "merge"
    elif intent == "join":
        ask = "start" if alone and not tagged else "join"
    else:
        ask = "add" if alone and not tagged else "join"
    try:
        again = fleet().is_removed(dev)
    except Exception:
        again = False
    return ask, again


def manage_words(root: bool) -> str:
    """What the one Allow at pairing also gives when the asker wants to manage this computer (Derek 2026-10-19 #17:
    one approval sets up management both ways, no second question). Said in the pairing question itself, so the
    Allow never gives more than the person read."""
    return ("Allow also gives your fleet full control of this account from Mission Control"
            + (" and as administrator" if root else "") + ". Turn it off any time in Settings > Fleet.")


def ask_words(ask: str, again: bool, shown: str, code: str, manage: bool = False, root: bool = False) -> tuple:
    """The notification's title and text for a request to pair (shown: the asker's name, already escaped). manage:
    the asker will manage this computer too, so the Allow is also that consent and the text says so."""
    extra = (" " + manage_words(root)) if manage else ""
    title, then = {
        "add": (f"{shown} wants to add this computer to your fleet", "This computer then joins your fleet, and every computer in it trusts this one."),
        "start": (f"{shown} wants to start your fleet with this computer", "The two of them are then your fleet."),
        "merge": (f"{shown} wants to make your two fleets one", "Every computer in both fleets then trusts every other one."),
    }.get(ask, (f"{shown} wants to join your fleet", "Every computer in your fleet will trust it."))
    if again:
        return title, f"{shown} was removed from your fleet before. If it's yours again, read them this code: {code}. Press Allow after they type it. {then}{extra}"
    return title, f"Read this code to the person at {shown}: {code}. Press Allow after they type it. {then}{extra}"


def handle_pair(conn: socket.socket, addr: str, first=None) -> None:
    """Someone asks to pair. The steps, so neither side can be fooled by a device in the middle:
      them -> hello              us -> our hello + a commitment to our random number
      them -> their number       us -> our number (they check it against the commitment)
    Both now compute the same code. The person here answers Allow / Don't allow (2 minutes), and the person there
    Join (or Pair); only when we said yes AND they confirm do we trust their key. That one OK is the only one: every
    other computer in the fleet adopts the new one from the list (reconcile), saying so in a notification."""
    mode = pairing_mode()
    if not mode:
        _busy(conn)
        return
    src = addr.replace("::ffff:", "")
    notice_done, note = None, None
    notice_guard = threading.Lock()
    req = answer = more = waiting = None
    try:
        them = first if first is not None else json.loads(readline(conn, deadline=time.time() + 10))     # the hello comes at once; don't hold a slot for a trickle
        if not valid_hello(them):
            tell(conn, {"result": "failed"})
            return
        them.pop("role", None)
        if _cooling(them["id"], src):
            tell(conn, {"result": "busy"})
            return
        if not remote_login_on():
            tell(conn, {"result": "needs-remote-login-there"})
            return
        them["name"] = safe_name(them.get("name"), "A device")
        them["kind"] = safe_kind(them.get("kind"))
        shown = html.escape(them["name"])                       # notifications render markup
        if not peer_proto_ok(them):
            # an asker that computes the older code: both screens would show different codes. Stop before any code.
            tell(conn, {"result": "needs-update"})
            if older_should_tell(them["id"], src):
                title, body = older_words(shown)
                sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "network-workgroup", title, body)
            return
        me, mine = hello(), new_nonce()
        me["help"] = mode == "help"
        tell(conn, {"hello": me, "commit": commitment(mine)})
        got = read_msg(conn, 30)
        theirs = got.get("nonce")
        if not isinstance(theirs, str) or not re.fullmatch(r"[0-9a-f]{32}", theirs):
            # an older Starchaser (its hello says nothing about joining or inviting, and it hung up on our hello
            # instead of sending its number): its screen only says "failed", so say here what to do
            if "intent" not in them and "nonce" not in got and older_should_tell(them["id"], src):
                title, body = older_words(shown)
                sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "network-workgroup", title, body)
            return
        tell(conn, {"nonce": mine})
        code = code_for(them, me, theirs, mine)
        rid = uuid.uuid4().hex[:8]
        req = PENDING / f"{rid}.json"
        jwrite(req, {"id": rid, "from": {k: them.get(k) for k in ("id", "name", "user", "kind")}, "address": src,
                     "code": code, "time": int(time.time())})
        answer = PENDING / f"{rid}.answer"
        # a notification with the code; Settings › Fleet shows the same request. -p prints the notification's
        # number first (line-buffered), so it can be replaced or closed when the request ends some other way
        # (canceled on the asking side, nobody answered, answered in Settings): stopping notify-send leaves it up. Answered
        # in the notification itself, it is closed already (the cockpit takes its buttons out of the history then), and
        # a replacement would only come as a second notification.
        # one OK here is trusted by every computer in the fleet (they adopt it from the list), so the question says so
        ask, again = request_kind(them.get("intent"), them["id"])
        # the asker will manage this computer (its "Also manage it" switch): this one Allow is that consent too
        # (decided 2026-10-19 #17), so the question says so, admin access included when sudo needs no password here
        manage = mode != "help" and pair_grants_manage(them)
        root = (manage or mode == "help") and sh("sudo", "-n", "true", timeout=5).returncode == 0
        title, body = ask_words(ask, again, shown, f"{code[:3]} {code[3:]}", manage, root)

        if mode == "help":
            title = f"Let {shown} help with this computer?"
            body = (f"Read this code to the person at {shown}: {code[:3]} {code[3:]}. Press Allow after they type it. Allow gives their computer full control of "
                    f"this account from Mission Control{' and administrator access' if root else ''}. This computer gets no access to theirs. Your households stay "
                    "separate. Choose End help in Settings > Fleet to stop it.")
        jwrite(req, dict(jread(req, {}), ask=ask, again=again, manage=manage, root=root, help=mode == "help"))     # (Settings > Fleet asks the same question)

        cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-p", "-a", "Starchaser", "-i", "network-workgroup", "-u", "critical", "-t", "130000", "-A", "yes=Allow",
               "-A", "no=Don't allow", "-A", "more=More time", title, body]
        if shutil.which("stdbuf"):
            cmd = ["stdbuf", "-oL"] + cmd
        try:
            # The open pairing window owns this request and its consent controls.
            note = None if pairing_window_open() else subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
        except OSError:
            note = None                                         # (Settings › Fleet still shows the request)
        note_id, in_note = [], []
        more = PENDING / f"{rid}.more"
        notice_done = threading.Event()

        def from_notification():
            nonlocal note
            try:
                while note and not notice_done.is_set():
                    extend = False
                    for line in note.stdout:
                        w = line.strip()
                        with notice_guard:
                            if notice_done.is_set():
                                return
                            if w.isdigit() and not note_id:
                                note_id.append(w)
                            elif w == "more" and not answer.exists():
                                fleet().write_atomic(more, "more", 0o600)
                                extend = True
                            elif w in ("yes", "no") and not answer.exists():
                                in_note.append(w)               # (answered in the notification itself)
                                fleet().write_atomic(answer, w, 0o600)
                    with notice_guard:
                        if not extend or answer.exists() or notice_done.is_set():
                            return
                        # An action closes the old notification. More time asks again,
                        # replacing its history entry and keeping both consent choices.
                        note = subprocess.Popen(cmd[:-2] + (["-r", note_id[0]] if note_id else []) + [title, body],
                                                stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
            except (OSError, ValueError, AttributeError):
                pass
        threading.Thread(target=from_notification, daemon=True).start()
        t0, gone = time.time(), False
        while time.time() - t0 < 120 and not answer.exists():
            if pairing_mode() != mode or closed(conn):                                    # they canceled: take the request off this screen
                gone = True
                break
            if more.exists():
                more.unlink(missing_ok=True)
                t0 = time.time()
                tell(conn, {"more": True})
            if select.select([conn], [], [], 0)[0]:
                extension = read_msg(conn, 2)
                if extension.get("more") is True:
                    t0 = time.time()
            time.sleep(0.3)
        with notice_guard:
            notice_done.set()
        if more.exists() and not gone:
            tell(conn, {"more": True})
        more.unlink(missing_ok=True)
        said = answer.read_text().strip() if answer.exists() else ""
        if said == "yes" and not gone:
            # Publish the handshake before removing the request, so a list never sees a gap
            # between local Allow and the helper's confirmation (notification cleanup can take time).
            waiting = PENDING / f"{rid}.waiting"
            jwrite(waiting, {"id": them["id"], "name": them["name"]})
        req.unlink(missing_ok=True)
        answer.unlink(missing_ok=True)
        if note and note.poll() is None and not in_note:
            note.terminate()
            if note_id and (gone or not said):
                # its Pair / Decline would do nothing now: the same notification, without them, says what happened
                sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-r", note_id[0], "-a", "Starchaser", "-i", "network-workgroup", "-t", "5000",
                   f"{shown} stopped asking to join" if gone else f"{shown}'s request to join ran out",
                   "Nothing changed." if gone else "Nobody answered in 2 minutes, so nothing changed.")
            elif note_id:                                       # answered in Settings, which shows what happens next
                sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-r", note_id[0], "-a", "Starchaser", "-i", "network-workgroup", title,
                   "You pressed " + ("Allow" if said == "yes" else "Don't allow") + " in Settings > Fleet.")
                sh("busctl", "--user", "call", "org.freedesktop.Notifications", "/org/freedesktop/Notifications",
                   "org.freedesktop.Notifications", "CloseNotification", "u", note_id[0], timeout=5)
        if gone:
            return
        if said != "yes":
            # declined, or nobody answered: either way the same asker waits before it can ask again (an unanswered
            # request repeated would keep a notification on screen)
            _declined(them["id"], src)
            tell(conn, {"result": "declined"})
            return
        tell(conn, {"result": "accepted"})
        try:
            ok = False
            deadline = time.monotonic() + 130
            while pairing_mode() == mode and time.monotonic() < deadline:
                if not select.select([conn], [], [], min(1, max(0, deadline - time.monotonic())))[0]:
                    continue
                confirmation = read_msg(conn, min(2, max(0, deadline - time.monotonic())))
                if confirmation.get("more") is True:
                    deadline = time.monotonic() + 130
                    continue
                ok = confirmation.get("result") == "confirmed" and pairing_mode() == mode
                break
            if ok:
                # The typed-code confirmation may narrow the return permission chosen on the code card.
                if confirmation.get("askBack") is False:
                    them["askBack"] = False
                if mode == "help":
                    them["role"] = "helper"
                trust(them, src)                                # (before the marker goes: the list shows it paired)
                if manage:
                    consent_from_pairing()                      # (before "paired": the asker's request comes next)
        finally:
            waiting.unlink(missing_ok=True)
        if not ok:
            return
        tell(conn, {"result": "paired"})
        if mode == "help":
            return
        sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "network-workgroup", f"{shown} joined your fleet",
           "Every computer in your fleet trusts it now: Settings > Fleet.")
        if them.get("askBack") is not False and fleet().load()["local"].get("askBothWays", True):
            ask_back(them["id"])
    except (OSError, ValueError, KeyError, TypeError, AttributeError):
        try:
            tell(conn, {"result": "failed"})
        except OSError:
            pass
    finally:
        with notice_guard:
            if notice_done:
                notice_done.set()
            if note and note.poll() is None:
                note.terminate()
        for marker in (req, answer, more, waiting):
            if marker:
                marker.unlink(missing_ok=True)
        conn.close()


def unreachable_words(address: str, e: Exception) -> str:
    """Why a computer couldn't be reached, in plain words (the socket error's own text is a Python errno string)."""
    if isinstance(e, UnicodeError):
        return f"'{address}' is not a valid address."
    if isinstance(e, socket.gaierror):
        return f"Couldn't find a computer called {address}. Check the address, and that it is on the same network."
    return f"Couldn't reach {address}. Check that it is on and on the same network."


def pair_code_matches(expected: str, typed: str) -> bool:
    return bool(re.fullmatch(r"[0-9]{6}", str(expected)) and str(typed).replace(" ", "") == expected)


def pair_confirmation(conn: socket.socket, code: str, choices=None) -> tuple:
    """Wait for both answers; Settings keeps its exact yes/no pipe protocol and deadline."""
    terminal = sys.stdin.isatty()
    if terminal:
        print("Type the six-digit code shown on the other computer and press Enter "
              "(anything else cancels). You have 2 minutes: ", end="", file=sys.stderr, flush=True)
    ours, verdict, buf, t0 = None, None, b"", time.time()
    stdin_open = True
    limit = 120 if terminal else 130
    while time.time() - t0 < limit and (ours is None or verdict is None):
        if ours is False or verdict not in (None, "accepted"):
            break
        watch = [conn] + ([sys.stdin] if stdin_open and ours is None else [])
        r, _, _ = select.select(watch, [], [], 1)
        if sys.stdin in r:
            line = sys.stdin.readline()
            if not line:
                stdin_open, ours = False, False
            elif line.strip() == "more":
                tell(conn, {"more": True})
                t0 = time.time()
                if terminal:
                    print("More time added. Type the six-digit code: ", end="", file=sys.stderr, flush=True)
                continue
            elif terminal:
                ours = pair_code_matches(code, line.strip())
            elif line.strip().startswith("code:"):
                typed, _, preference = line.strip()[5:].partition("|manage:")
                if choices is not None and preference in ("on", "off"):
                    choices["manage"] = preference == "on"
                ours = pair_code_matches(code, typed)
            elif line.strip() in ("yes", "no"):
                ours = line.strip() == "yes"
            if terminal:
                print("Confirmed. Joining..." if ours else "Canceled: nothing changed.", file=sys.stderr, flush=True)
        if conn in r:
            c = conn.recv(4096)
            if not c:
                verdict = verdict or "unreachable"
                break
            buf += c
            if len(buf) > 8192:                             # an answer is a short line: more is not one
                verdict = "failed"
                break
            while b"\n" in buf:
                line, buf = buf.split(b"\n", 1)
                try:
                    m = json.loads(line.decode(errors="replace"))
                except ValueError:
                    m = {}
                if isinstance(m, dict) and m.get("more") is True:
                    t0 = time.time()
                    continue
                verdict = m.get("result") if isinstance(m, dict) and isinstance(m.get("result"), str) else "failed"
    if terminal and ours is not False:
        if verdict == "declined":
            print("The other computer declined or timed out: nothing changed.", file=sys.stderr, flush=True)
        elif verdict == "unreachable":
            print("The other computer closed the connection or timed out: nothing changed.", file=sys.stderr, flush=True)
        elif verdict not in (None, "accepted"):
            print("The other computer could not complete pairing: nothing changed.", file=sys.stderr, flush=True)
        elif ours is None or verdict is None:
            print("Timed out after 2 minutes: nothing changed.", file=sys.stderr, flush=True)
    return ours, verdict


def pair(address: str, port: int = PORT, manage: bool = True, intent: str = "", ask_me: bool = True, help_only: bool = False) -> dict:
    """Ask a nearby device to pair (the steps are in handle_pair). Prints {"code"} once both numbers are in, then
    waits for this person's answer on stdin ("yes" / "no") and the other person's over the network. manage ("Also
    manage it from Mission Control", on unless --no-manage): once paired, ask the other computer to let the fleet
    manage it (asked there, in the background; the fleet list's manage.state follows it). intent: "join" (this
    computer joins the other one's fleet) or "invite" (it adds the other one to this computer's fleet); by default
    "join" when this computer is on its own. Said in the hello, so the other screen asks the right question.
    An older Starchaser on the other side (it answers with a bare code, "already", or a word this version doesn't
    know): {"result": "older"}, and nothing is kept here; if the older one trusts this computer anyway (its person
    pressed Pair there, or it still lists this one from an earlier try), it is asked to forget it (old_forget).
    Returns the last line."""
    last = {}

    def say(**kw):
        last.clear()
        last.update(kw)
        print(json.dumps(kw), flush=True)
    owner = fleet_owner()
    if owner:
        say(result="fleet-owner", error=f"This computer's fleet belongs to {owner['name']}. Sign in to that account to add a computer.")
        return last
    if not remote_login_on():
        say(result="needs-remote-login")
        return
    me, mine = hello(), new_nonce()
    if intent not in ("join", "invite"):
        try:
            intent = "invite" if any(e.get("link") for e in fleet().load()["machines"]) else "join"
        except Exception:
            intent = "join"
    me["intent"] = intent
    # Both ways is the default. Either computer can turn the return question off in Fleet, and --no-manage
    # suppresses it for this pairing too.
    me["askBack"] = bool(ask_me and manage and fleet().load()["local"].get("askBothWays", True))
    # this computer will manage the other one: the other screen's pairing question says its Allow covers that too
    me["manage"] = bool(manage)
    try:
        conn = socket.create_connection((address, port), timeout=6)
    except (OSError, UnicodeError) as e:
        say(result="unreachable", error=unreachable_words(address, e))
        return last
    try:
        tell(conn, me)
        first = read_msg(conn, 30)
        if "hello" not in first:
            if help_only:
                say(result="help-not-ready", name=address)
                return last
            word = first.get("result") if isinstance(first.get("result"), str) else ""
            if word == "needs-update" and "code" not in first:
                say(result="needs-update", name=address)
                return last
            if word in ("busy", "failed", "declined", "needs-remote-login-there") and "code" not in first:
                say(result=word)
                return
            if word == "already" and "code" not in first:
                # only an older Starchaser says this: it lists this computer. Paired with it here too, they are
                # simply paired: exchange the lists again instead of failing
                p = next((x for x in load_peers() if x.get("address") == address), None)
                if p is not None:
                    # only when the exchange really reached it, signed in both ways with the keys pairing pinned
                    # (an address alone proves nothing: another computer may have it now)
                    r = {}
                    with contextlib.suppress(Exception):
                        r = fleet_sync(wait=True)
                    if p["id"] in (r.get("reachedIds") or []):
                        say(result="accepted", manage="off", already=True, id="dev-" + p["id"])
                        return
                    # paired on both sides, but the lists don't get across (an older list, or not reachable now):
                    # update it; nothing is undone, it trusts this computer and this one trusts it
                    say(result="older")
                    return
            # an older Starchaser (a bare code, "already" from a pairing it kept on its own, or a word this version
            # doesn't know): update it first. Nothing is kept here, and the older one forgets this computer again
            say(result="older")
            if "code" in first or word == "already":
                old_forget_later(conn, address, me, first)
            return
        them, commit = first["hello"], first.get("commit")
        if not valid_hello(them) or not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{64}", commit):
            say(result="failed")
            return
        if not peer_proto_ok(them):
            # it computes the older code, so the two screens would never agree: no nonce, no code. It sees the
            # connection close before anything was asked of its person (it asks only after our number).
            say(result="needs-update", name=safe_name(them.get("name"), address))
            return last
        tell(conn, {"nonce": mine})
        theirs = read_msg(conn, 30).get("nonce")
        if not isinstance(theirs, str) or not re.fullmatch(r"[0-9a-f]{32}", theirs) or commitment(theirs) != commit:
            say(result="mismatch")                              # it changed its number after seeing ours
            return
        them["name"] = safe_name(them.get("name"), "A device")
        them.pop("role", None)
        helping = them.get("help") is True
        if help_only and not helping:
            say(result="help-not-ready", name=them["name"])
            return last
        if helping:
            them["role"] = "help-target"
        code = code_for(me, them, mine, theirs)
        if helping:
            me["askBack"] = False
        say(code=code, name=them["name"], help=helping)
        choices = {"manage": manage}
        ours, verdict = pair_confirmation(conn, code, choices)
        if not choices["manage"]:
            me["askBack"] = False
        if ours is False or (verdict == "accepted" and ours is not True):     # this person said no, or nothing
            say(result="canceled")
            return
        if verdict != "accepted":
            say(result=verdict or "declined")
            return
        # From here the other side may trust us before its "paired" reaches us. A note first, so a lost last message
        # is finished later (pair_check) instead of leaving the pairing on one side only.
        mark = PAIRCHECK / f"{them['id']}.json"
        jwrite(mark, {"hello": them, "address": address, "time": int(time.time()), "manage": manage,
                      "askBack": me["askBack"], "intent": intent, "manageLocal": choices["manage"]})
        if intent == "join" and not helping and choices["manage"] is False:
            # Revocation must not depend on the last send/reply, or on the join caller staying alive.
            set_join_management(False)
        tell(conn, {"result": "confirmed", "askBack": bool(me["askBack"])})
        try:
            paired = read_msg(conn, 30).get("result") == "paired"
        except OSError:
            paired = False                                  # the peer may have committed before its reply was lost
        if not paired:
            say(result="checking", manageLocal=choices["manage"], help=helping, id="dev-" + them["id"])
            threading.Timer(3, lambda: pair_check(mark)).start()
            return last
        help_entry = trust(them, address)
        mark.unlink(missing_ok=True)
        if me["askBack"]:
            consent_from_pairing()                          # (this person's Pair, with "both ways" on, said yes)
        if manage and not helping:
            start_manage_request(them["id"])
        say(result="accepted", manageLocal=choices["manage"], help=helping, manage="ready" if helping else "asking" if manage else "off",
            id=help_entry["id"] if helping and help_entry else "dev-" + them["id"])
    except OSError as e:
        say(result="unreachable", error=unreachable_words(address, e))
    except (ValueError, KeyError, TypeError):
        say(result="failed")
    finally:
        conn.close()                                        # (a background copy keeps its own, old_forget_later)
    return last


def old_code(a: dict, b: dict) -> str:
    """The code an older Starchaser (before the random numbers) shows: both devices' keys only."""
    keys = sorted([a["key"] + a["hostkey"], b["key"] + b["hostkey"]])
    return f"{int(hashlib.sha256('|'.join(keys).encode()).hexdigest(), 16) % 1_000_000:06d}"


def old_forget(user: str, address: str, hostkey: str = "") -> bool:
    """Ask an older Starchaser that trusts this computer (and this one doesn't trust it) to forget it: its own verb
    for that, `unpair`, over this computer's link key (which it lets in, locked to that program). With its host key
    when this computer has one (from its answer); without, the verb is all that's sent: it can't make this computer
    trust anything."""
    if not valid_user(user) or not valid_host(address):
        return False
    with tempfile.TemporaryDirectory() as d:
        kh = Path(d) / "known_hosts"
        if hostkey:
            kh.write_text(f"starchaser-old {hostkey}\n")
        cmd = ["ssh", "-i", str(KEY), "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=4",
               "-o", f"UserKnownHostsFile={kh if hostkey else '/dev/null'}", "-o", "LogLevel=ERROR",
               "-o", "HostKeyAlias=starchaser-old" if hostkey else "CheckHostIP=no",
               "-o", "StrictHostKeyChecking=" + ("yes" if hostkey else "no"), f"{user}@{address}", "unpair"]
        try:
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=20)
        except (OSError, subprocess.TimeoutExpired):
            return False
    return r.returncode == 0 and '"ok": true' in r.stdout


def old_forget_later(conn, address: str, me: dict, first: dict) -> bool:
    """After {"result": "older"}: in the background (the caller's screen has its answer already), make sure the
    older Starchaser doesn't keep this computer on its side. It said "already": it lists this computer from an
    earlier try, so it is asked to forget it now. It showed a code: its person may still press Pair there, and an
    older one trusts the asker on that alone, before anything comes back here; so the connection is kept open until
    it answers (2 minutes), and if it said yes, it is asked to forget this computer again. Said on screen only when
    that didn't work, with what to do. True when the background part started."""
    if os.environ.get("STARCHASER_FLEET_NO_SPAWN") == "1":
        old_forget_wait(conn, address, me, first)          # (the tests: no background process)
        return False
    try:
        pid = os.fork()
    except OSError:
        return False
    if pid:
        return True
    try:                                                    # the background part: no output to the caller
        os.setsid()
        null = os.open(os.devnull, os.O_RDWR)
        for fd in (0, 1, 2):
            os.dup2(null, fd)
        old_forget_wait(conn, address, me, first)
    finally:
        os._exit(0)


def old_forget_wait(conn, address: str, me: dict, first: dict) -> str:
    """old_forget_later's background part. Returns what happened: "nothing" (it said no, or nobody answered),
    "forgot" (it was asked to forget this computer, and did) or "told" (that didn't work: said on screen)."""
    name, user, hostkey = address, "", ""
    with contextlib.suppress(Exception):
        n = next((x for x in nearby() if x["address"] == address), None)
        if n:
            name, user = n["name"], n["user"]
    if "code" in first:
        res = read_msg(conn, 130)
        them = res.get("hello") if res.get("result") == "accepted" else None
        if not valid_hello(them) or old_code(me, them) != first.get("code"):
            return "nothing"                                # it said no, or nobody answered: nothing to undo
        name, user, hostkey = safe_name(them.get("name"), name), them["user"], them["hostkey"]
    with contextlib.suppress(OSError):
        conn.close()
    if old_forget(user or ME, address, hostkey):
        return "forgot"
    notify_desktop(session_env(), "network-workgroup", f"{html.escape(name)} has an older Starchaser",
                   f"It still lists this computer, but this computer doesn't trust it. Update it (Settings > Updates), "
                   f"then join again; or remove this computer there now, in Settings > Fleet on {html.escape(name)}.")
    return "told"


# ---------------------------------------------------------------------------------------------- joining a fleet
def set_join_management(enabled: bool) -> None:
    """Apply the final local join choice, including removing access from an earlier join."""
    F = fleet()
    F.set_local(manageConsent=enabled)
    if enabled:
        F.ensure_personal_key()                             # so Mission Control here can manage the fleet too
    F.reconcile(THIS)


def join(address: str, port: int = PORT, manage: bool = True, wait: int = 60) -> None:
    """Join the fleet a nearby member belongs to, in one step: the same code check as pair (the one human OK, on that
    member), then no second question. manage (on unless --no-manage): this computer lets the fleet manage it (its
    person said so with the welcome's switch); the members that let the fleet manage them let this one in by
    themselves once the list reaches them. Then it waits (up to `wait` seconds) while the rest of the fleet picks
    the new computer up from the list, printing {"members": [...]} as that changes, and ends with {"done": true,
    "members": [...]} (join_wait)."""
    # "may I manage you?" both ways (decided 2026-10-09): this computer asks the member it paired with, and the member
    # asks this one back (this one's switch, on by then, answers with no question). The welcome's switch covers both
    # directions ("this one every computer in your fleet that allows it"), so "Join only" (--no-manage) asks neither
    res = pair(address, port, manage=manage, intent="join", ask_me=manage) or {}
    # "checking": the last message got lost; pair_check finishes it in a moment (it needs no second question either)
    if res.get("result") not in ("accepted", "checking"):
        if res.get("result") in ("unreachable", "failed"):
            sys.exit(1)
        return
    if res.get("help"):
        return
    try:
        # The final join choice replaces consent from any earlier join, including an explicit opt-out.
        set_join_management(bool(res.get("manageLocal", manage)))
    except (OSError, ValueError):
        pass
    join_wait(wait)


def member_states() -> list:
    """Every computer in the fleet list and whether it has taken this one in yet: [{id, name, state}] with state
    "joined" (it lets this one in: it adopted it), "waiting" (on, but it hasn't heard yet), "off" (didn't answer;
    it picks this one up from the list once it's on), and for a computer that isn't a paired Starchaser one,
    "managed" (Mission Control here can sign in there) or "later" (one of the fleet's computers passes this one's key
    on as soon as it reaches it)."""
    F = fleet()
    doc = F.load()
    peers = {p["id"]: p for p in load_peers()}
    me = device_id()

    def one(e):
        row = {"id": e["id"], "name": F.display_name(e)}
        if not e.get("link"):
            row["state"] = "managed" if me in (e.get("managers") or []) else "later"
            return row
        p = peers.get(e["link"]["device"])
        if p is None:
            row["state"] = "waiting"
            return row
        r = ssh_to(p, "status", timeout=6)
        err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
        row["state"] = "joined" if r.returncode == 0 else "waiting" if "Permission denied (" in err else "off"
        return row
    with ThreadPoolExecutor(max_workers=8) as ex:
        rows = list(ex.map(one, doc["machines"]))
    return sorted(rows, key=lambda r: (r["name"].lower(), r["id"]))


def join_wait(seconds: int = 60, every: float = 4.0) -> list:
    """After joining: exchange the list (the member this one paired with already passes it on), and watch each
    member take the new computer in. Stops when nobody that's on is still waiting, or after `seconds`. Members that
    are off join when they're next on (their list exchange at start); one still waiting at the end joins on its next
    exchange (within 10 minutes)."""
    say = lambda **kw: print(json.dumps(kw), flush=True)
    t0, shown, rows = time.time(), None, []
    while True:
        with contextlib.suppress(Exception):                # (a sync that fails still lets the states be read)
            fleet_sync(wait=True)
        rows = member_states()
        if rows != shown:
            say(members=rows)
            shown = rows
        if not any(r["state"] == "waiting" for r in rows) or time.time() - t0 >= seconds:
            break
        time.sleep(every)
    say(done=True, members=rows)
    return rows


def pair_check(mark: Path) -> None:
    """A pairing whose last message got lost: if the other side let this computer in, it finished there, so finish
    it here; if it plainly refuses, it never finished there either, so drop the note. Unreachable: try again later
    (each list), for a day."""
    d = jread(mark, {})
    them, address = d.get("hello"), d.get("address")
    if not valid_hello(them) or not valid_host(address) or time.time() - d.get("time", 0) > 86400:
        mark.unlink(missing_ok=True)
        return
    try:                                                    # removed from the fleet after this pairing: never finished
        t = next((t for t in fleet().load()["removed"] if t["id"] == "dev-" + them["id"]), None)
    except Exception:
        t = None
    if t and t.get("removed", 0) >= d.get("time", 0):
        mark.unlink(missing_ok=True)
        return
    with state_lock():                                      # pin the host key the code verified, to ask over SSH
        known = [l for l in (KNOWN.read_text().splitlines() if KNOWN.exists() else []) if not l.startswith(f"starchaser-{them['id']} ")]
        KNOWN.write_text("\n".join(known + [f"starchaser-{them['id']} {them['hostkey']}"]) + "\n")
    r = ssh_once(dict(them, address=address), address, "status", timeout=6)
    if r.returncode == 0:
        join_choice = d.get("intent") == "join" and isinstance(d.get("manageLocal"), bool)
        if join_choice and them.get("role") != "help-target":
            set_join_management(d["manageLocal"])
        trust(them, address)
        mark.unlink(missing_ok=True)
        if them.get("role") == "help-target":
            return
        if not join_choice and d.get("askBack") is True:
            consent_from_pairing()
        if d.get("manage"):
            start_manage_request(them["id"])
        return
    if "Permission denied (" in (r.stderr or ""):
        mark.unlink(missing_ok=True)
        with state_lock():
            if not any(p["id"] == them["id"] for p in load_peers()):
                known = [l for l in (KNOWN.read_text().splitlines() if KNOWN.exists() else []) if not l.startswith(f"starchaser-{them['id']} ")]
                KNOWN.write_text("\n".join(known) + "\n")


def pair_checks() -> None:
    """From the list (every few seconds while Settings is open): each note at most once a minute, so a computer
    that's off doesn't slow every list down."""
    for mark in sorted(PAIRCHECK.glob("*.json")) if PAIRCHECK.exists() else []:
        try:
            if time.time() - mark.stat().st_mtime < 60:
                continue
            mark.touch()
            pair_check(mark)
        except Exception:                                   # (one bad note never stops the list)
            pass


# ---------------------------------------------------------------------------------------------- the fleet over the link
def spawn_self(*args: str) -> None:
    """This program again, in the background, on its own (it outlives the caller: a paired device's SSH session,
    Settings' pairing call). Never from the tests (STARCHASER_FLEET_NO_SPAWN=1)."""
    if os.environ.get("STARCHASER_FLEET_NO_SPAWN") == "1":
        return
    with contextlib.suppress(OSError):
        subprocess.Popen([sys.executable, os.path.realpath(__file__), *args], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def pair_grants_manage(them: dict) -> bool:
    """Whether this computer's Allow on a pairing question also lets the asker manage it: only when the asker will
    manage it (its hello says so) AND this computer's own "Manage each other after pairing" switch is on. Off, the
    question doesn't name management, and the asker's manage request is asked here on its own (serve_manage_request),
    so "Off: only this computer manages" stays true."""
    if them.get("manage") is not True:
        return False
    try:
        return fleet().load()["local"].get("askBothWays", True) is not False
    except Exception:
        return False


def consent_from_pairing() -> None:
    """The one approval at pairing covers management both ways (Derek 2026-10-19 #17, superseding 10-09 #2's second
    question): turn "let the fleet manage this computer" on, so the other computer's manage-request is let in with
    no question here. Only called when this person's own answer said so: Allow on a question that named it
    (ask_words with manage), or Pair with "Also manage it" and "both ways" on."""
    with contextlib.suppress(OSError, ValueError):
        fleet().set_local(manageConsent=True)


def start_manage_request(pid: str, after_pair: bool = False) -> None:
    spawn_self("manage-request", pid, *(["--after-pair"] if after_pair else []))


def ask_back(pid: str) -> None:
    """Paired: this computer asks the other one "may I manage you?" too (Derek 2026-10-09: both ways, on every pairing).
    The asker asks from pair() (unless --no-manage) and join(); the computer that pressed Allow asks from here. The
    other side answers by its own consent: on, it lets this one in without a question; off, its person is asked
    (serve_manage_request). Started in the background, a few seconds later, so the other side has finished trusting
    this computer (its "paired" arrives a moment after ours is sent) and a joining computer has turned its switch on."""
    if fleet().load()["local"].get("askBothWays", True):
        start_manage_request(pid, after_pair=True)


def manage_request_after_pair(pid: str, settle: float = 5, tries: int = 6, every: float = 5) -> dict:
    """manage_request right after a pairing: the other computer may not let this one in for a few seconds yet (it
    trusts this one once our last message reaches it), so a request that couldn't get in is tried again a few times.
    Only a refusal before anything ran there is tried again: a request that may have reached the person there (no
    answer in time, a dropped connection) is never asked again, so nobody gets the same question twice."""
    time.sleep(settle)
    res = {}
    for i in range(tries):
        res = manage_request(pid)
        if not res.get("retry"):
            break
        if i < tries - 1:
            time.sleep(every)
    return res


def manage_request(pid: str) -> dict:
    """Ask a paired computer to let the fleet manage it (Mission Control). The person there answers; this account's
    personal sign-in key is made first if it has none. The answer lands in the fleet list (manage.state).
    One question at a time per computer: pairing starts one in the background and the welcome or Settings may ask
    at the same moment to show the answer, so a second caller waits for the first and reports its answer instead of
    putting the question on the other screen twice."""
    if not ID_RE.fullmatch(pid.removeprefix("dev-")):
        return {"ok": False, "state": "unknown", "error": "not a device id"}
    pid = pid.removeprefix("dev-")
    STATE.mkdir(parents=True, exist_ok=True)
    fd = os.open(STATE / f".manage-{pid}.lock", os.O_RDWR | os.O_CREAT, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            fcntl.flock(fd, fcntl.LOCK_EX)                  # the first caller's question is on screen: wait for it
            e = fleet().get("dev-" + pid) or {}
            state = (e.get("manage") or {}).get("state") or "unknown"
            return {"ok": state in ("ready", "asked", "declined"), "state": state, "madeKey": False}
        return _manage_request(pid)
    finally:
        os.close(fd)


def _manage_request(pid: str) -> dict:
    F = fleet()
    p = peer(pid)
    fid = "dev-" + pid
    pub, made = F.ensure_personal_key()
    if not pub:
        F.manage_state(fid, "needs-key")
        return {"ok": False, "state": "needs-key", "error": "Couldn't make a sign-in key for this account."}
    F.manage_state(fid, "asked")
    r = ssh_to(p, "manage-request", timeout=650, input=json.dumps({"managePub": pub}) + "\n")
    try:
        res = json.loads(r.stdout or "{}") if r.returncode == 0 else {}
    except ValueError:
        res = {}
    if r.returncode != 0:
        try:
            if json.loads(r.stdout or "{}").get("error") == "not allowed":
                F.manage_state(fid, "none")
                return {"ok": False, "state": "none", "error": f"{p['name']} needs a Starchaser update before it can be managed."}
        except ValueError:
            pass
        err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
        # "retry": it turned this computer away before anything ran there (ssh's own refusal), so nobody was asked;
        # right after a pairing that only means it hasn't finished trusting this one yet (manage_request_after_pair)
        return {"ok": False, "state": "asked", "error": why_not(p, r),
                "retry": r.returncode == 255 and "Permission denied (" in err}
    if isinstance(res.get("self"), dict):
        F.observe(fid, res["self"], by=pid)
    if res.get("allowed"):
        F.reconcile()                                       # its host keys into known_hosts, state ready
        e = F.get(fid) or {}
        state = (e.get("manage") or {}).get("state") or "ready"
        F.changed()
        return {"ok": True, "state": state, "madeKey": made}
    state = "declined" if res.get("answered") == "no" else "none" if res.get("answered") == "none" else "asked"
    F.manage_state(fid, state)
    return {"ok": True, "state": state, "madeKey": made}


def serve_manage_request(pid: str, name: str, env: dict) -> dict:
    """A paired computer asks to manage this one. Asked here, once: Allow turns on "let the fleet manage this
    computer", which lets every computer in the fleet sign in with its owner's personal key."""
    F = fleet()
    try:
        d = json.loads(sys.stdin.readline() or "{}")
    except ValueError:
        d = {}
    pub = " ".join(str(d.get("managePub") or "").split()[:2]) if isinstance(d, dict) else ""
    if not F.KEY_RE.fullmatch(pub):
        return {"ok": False, "error": "bad key"}
    F.observe("dev-" + pid, {"managePub": pub}, by=pid)     # (its own key, from its own link: trusted as a fact about it)
    doc = F.load()
    allowed_here = False
    if not doc["local"].get("manageConsent"):
        shown = html.escape(name)
        root = sh("sudo", "-n", "true", timeout=5).returncode == 0
        # the card shows about four lines: what it means comes first, the details after
        body = ("Full control of this account from Mission Control, like signing in with your password"
                + (" (and as administrator, since this computer asks for no password)" if root else "")
                + f". Allow only if you're setting this up from {shown}. Every computer in your fleet gets it; turn it "
                "off any time in Settings > Fleet.")
        rid = secrets.token_hex(4)
        request = PENDING / (rid + ".json")
        jwrite(request, {"id": rid, "management": True, "from": {"id": pid, "name": name}, "body": body, "time": int(time.time())})
        try:
            said = ask_person(env, "network-workgroup", f"{shown} wants to manage this computer", body, "Allow", "Don't allow", 75, rid)
        finally:
            for suffix in (".json", ".answer", ".more"):
                (PENDING / (rid + suffix)).unlink(missing_ok=True)
        if said != "yes":
            return {"ok": True, "allowed": False, "answered": said or "none"}
        F.set_local(manageConsent=True)
        allowed_here = True
    F.reconcile()
    F.changed()
    if allowed_here and doc["local"].get("askOnceForFleet") is True:
        spawn_self("manage-fleet-allow")
    return {"ok": True, "allowed": True, "self": F.self_facts(THIS)}


def share_manage_allow() -> dict:
    """Tell paired members about an Allow here. Consent and keys never travel over discovery or pairing hello;
    only the pinned, forced-command SSH link carries this request. Receivers make their own choice."""
    F = fleet()
    doc = F.load()
    if doc["local"].get("askOnceForFleet") is not True or not doc["local"].get("manageConsent"):
        return {"ok": True, "sent": []}
    sent = []
    for p in load_peers():
        if not F.is_member(p["id"], p.get("key") or ""):
            continue
        r = ssh_to(p, "manage-fleet-allow", timeout=90)
        if r.returncode == 0:
            sent.append(p["id"])
    return {"ok": True, "sent": sent}


def doc_entry(doc: dict, mid: str):
    return next((e for e in doc["machines"] if e["id"] == mid), None)


def serve_manage_allow(pid: str, name: str, env: dict) -> dict:
    """A paired member passed on an Allow. Both switches must be on to skip the question here. Do not pass this
    on again: only a person's Allow on the original manage request starts the fanout."""
    F = fleet()
    doc = F.load()
    if not doc["local"].get("manageConsent"):
        # Skip the question only when this switch is on AND that computer's own report says it allows management
        # (a shared Allow can't be proven, so a sender that is not allowing itself is always asked about).
        sender = doc_entry(doc, "dev-" + pid)
        if doc["local"].get("askOnceForFleet") is not True or not (sender and sender.get("manageable")):
            shown = html.escape(name)
            said = ask_person(env, "network-workgroup", "Let your fleet manage this computer?",
                              f"{shown} allowed fleet management. Allow here too for full control of this account "
                              "from Mission Control on your fleet's computers. Turn it off any time in Settings > Fleet.",
                              "Allow", "Don't allow", 75)
            if said != "yes":
                return {"ok": True, "allowed": False, "answered": said or "none"}
        F.set_local(manageConsent=True)
    F.reconcile()
    F.changed()
    return {"ok": True, "allowed": True}


def ask_person(env: dict, icon: str, title: str, body: str, yes: str, no: str, seconds: int, request_id: str = "") -> str:
    """Urgent, extendable questions. More time is never consent; total waiting is bounded."""
    for _ in range(8):
        answer = _ask_person_once(env, icon, title, body, yes, no, seconds, request_id)
        if answer != "more":
            return answer
    return ""


def _ask_person_once(env: dict, icon: str, title: str, body: str, yes: str, no: str, seconds: int, request_id: str = "") -> str:
    cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-p", "-a", "Starchaser", "-i", icon, "-u", "critical", "-t", str(seconds * 1000),
           "-A", f"yes={yes}", "-A", f"no={no}", "-A", "more=More time", title, body]
    if shutil.which("stdbuf"):
        cmd = ["stdbuf", "-oL"] + cmd
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, env=env)
    except OSError:
        return ""
    try:
        deadline = time.monotonic() + seconds + 5
        while request_id and proc.poll() is None and time.monotonic() < deadline:
            answer = PENDING / (request_id + ".answer")
            more = PENDING / (request_id + ".more")
            if answer.exists() or more.exists():
                result = answer.read_text().strip() if answer.exists() else "more"
                more.unlink(missing_ok=True)
                proc.terminate()
                proc.communicate(timeout=5)
                return result
            time.sleep(0.1)
        out, _ = proc.communicate(timeout=max(0.1, deadline - time.monotonic()))
    except subprocess.TimeoutExpired:
        proc.kill()
        out, _ = proc.communicate()
    words = out.split()
    if "more" in words:
        return "more"
    if "yes" in words:
        return "yes"
    if words[:1] and words[0].isdigit():
        sh("busctl", "--user", "call", "org.freedesktop.Notifications", "/org/freedesktop/Notifications",
           "org.freedesktop.Notifications", "CloseNotification", "u", words[0], timeout=5, env=env)
    return "no" if "no" in words else ""


_SYNC_LOCK = STATE / ".sync.lock"
_SYNC_AGAIN = STATE / ".sync-again"


def security_once(address: str, bundle: dict) -> dict:
    """Bounded, unauthenticated courier. accept_security verifies every signature before using anything."""
    with socket.create_connection((address, PORT), timeout=3) as conn:
        tell(conn, {"security": bundle})
        reply = json.loads(readline(conn, limit=4 * 1024 * 1024, deadline=time.time() + 5))
        return reply.get("security", {}) if isinstance(reply, dict) else {}


def security_sync() -> None:
    F = fleet()
    doc = F.load()
    if doc.get("unreadable") or doc["local"].get("left"):
        return
    bundle = F.security_payload()
    addresses = []
    for e in doc["machines"]:
        if not e.get("link"):
            continue
        a = e.get("addresses") or {}
        addresses.extend([e.get("chosenAddress"), a.get("last"), *(a.get("lan") or []),
                          a.get("mdns"), a.get("tailscale"), e.get("hostname")])
    # A former LAN address may now belong to another computer. Even a reply there cannot prove delivery to
    # the intended member: try every saved route, including names and Tailscale, once each.
    addresses = list(dict.fromkeys(a for a in addresses if a and valid_host(a)))
    for address in addresses:
        try:
            reply = security_once(address, bundle)
            if F.accept_security(reply):
                F.reconcile(THIS)
        except (OSError, ValueError):
            continue


def fleet_sync(wait: bool = False, exclude: str = "") -> dict:
    """Exchange the fleet list with every paired computer in the fleet, in parallel, and pass on what came back
    until nothing new arrives. One run at a time: a change while one runs makes it go round once more."""
    F = fleet()
    F.reconcile(THIS)
    security_sync()
    F.reconcile(THIS)
    STATE.mkdir(parents=True, exist_ok=True)
    fd = os.open(_SYNC_LOCK, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
        except BlockingIOError:
            _SYNC_AGAIN.touch()
            return {"ok": True, "queued": True, "reached": [], "reachedIds": [], "unreached": [], "unreachedIds": [],
                    "needsUpdate": [], "needsUpdateIds": [], "needsUpdateSides": {}}
        reached, reached_ids, unreached, unreached_ids, targets, denied = [], [], [], [], [], []
        needs_update, needs_update_ids, refused, errors = [], [], [], []
        update_sides = {}
        for _ in range(6):
            _SYNC_AGAIN.unlink(missing_ok=True)
            doc = F.load()
            if doc["local"].get("left"):
                break
            live = {e["link"]["device"] for e in doc["machines"] if e.get("link")}
            targets = [p for p in load_peers() if p["id"] in live and p["id"] != exclude]
            if not targets:
                # nobody to exchange with (no fleet, or only the computer that just sent its list): this computer's
                # facts (ip, nmcli and hostnamectl runs, twice a round) would be gathered for no one
                break
            facts = F.self_facts(THIS)
            data = (json.dumps(F.payload(facts)) + "\n").encode()

            denied = []                                     # fleet computers that turned this one away

            def one(p):
                r = ssh_to(dict(p), "fleet-sync", data=data)
                try:
                    raw = r.stdout.decode(errors="replace") if isinstance(r.stdout, bytes) else r.stdout
                    reply = json.loads(raw or "null")
                except ValueError:
                    reply = None
                err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
                if "Permission denied (" in err or (isinstance(reply, dict) and reply.get("error") in ("removed", "not paired", "refused")):
                    denied.append(p["id"])
                return p, reply, r
            news = False
            with ThreadPoolExecutor(max_workers=8) as ex:
                results = list(ex.map(one, targets))
            reached, reached_ids, unreached, unreached_ids = [], [], [], []
            needs_update, needs_update_ids, refused, errors = [], [], [], []
            update_sides = {}
            for p, reply, transport in results:
                if p["id"] in denied:
                    refused.append(p["id"])
                    continue
                if isinstance(reply, dict) and ("v" in reply and reply.get("v") != F.VERSION
                        or reply.get("error") in ("not allowed", "needs-update", "version")
                        or reply.get("state") == "needs-update"
                        or isinstance(reply.get("result"), dict) and reply["result"].get("state") == "needs-update"):
                    needs_update.append(p["name"])
                    needs_update_ids.append(p["id"])
                    version = reply.get("v")
                    update_sides[p["id"]] = "this" if type(version) is int and version > F.VERSION else "peer"
                    detail = reply.get("result", reply)
                    if isinstance(detail, dict) and detail.get("older") in ("this", "peer"):
                        update_sides[p["id"]] = "peer" if detail["older"] == "this" else "this"
                    continue
                if isinstance(reply, dict) and (reply.get("v") != F.VERSION or reply.get("error") or transport.returncode):
                    errors.append(p["id"])
                    continue
                if not isinstance(reply, dict) and transport.returncode not in (124, 255):
                    errors.append(p["id"])
                    continue
                if not isinstance(reply, dict):
                    unreached.append(p["name"])
                    unreached_ids.append(p["id"])
                    continue
                reached.append(p["name"])
                reached_ids.append(p["id"])
                try:
                    news = F.merge_in(reply, p["id"]) or news
                except (F.Refused, ValueError):
                    pass
            F.reconcile(THIS)
            exclude = ""
            # round again when something new came back, or when what this computer says about itself changed
            # (it now lets another one manage it, say)
            if not news and not _SYNC_AGAIN.exists() and F.self_facts(THIS) == facts:
                break
        shut_out = bool(targets) and not reached and len(denied) == len(targets)
        if shut_out:
            say_shut_out()
        return {"ok": True, "reached": reached, "reachedIds": reached_ids, "unreached": unreached, "unreachedIds": unreached_ids,
                "needsUpdate": needs_update, "needsUpdateIds": needs_update_ids, "needsUpdateSides": update_sides,
                "refusedIds": refused, "errorIds": errors, "shutOut": shut_out}
    finally:
        os.close(fd)


SHUT_OUT = STATE / "shut-out-noted"


def say_shut_out() -> None:
    """Every fleet computer this one tried turned it away: most likely it was removed from the fleet while it was
    off, so it never heard (a removed computer's key is dropped everywhere, which also means nobody can tell it).
    Said plainly, at most once a day; it stays as it is until the person pairs it again or removes the others."""
    try:
        if time.time() - SHUT_OUT.stat().st_mtime < 86400:
            return
    except OSError:
        pass
    SHUT_OUT.touch()
    notify_desktop(session_env(), "network-workgroup", "Your other computers no longer let this one in",
                   "It was probably removed from your fleet while it was off. To use it with them again, join it to "
                   "your fleet again in Settings > Fleet.")


def tell_leaving(pid: str) -> bool:
    """Tell a device it was removed from the fleet (it then leaves: forgets every fleet computer). An older Starchaser
    that has no fleet is asked to unpair this one instead."""
    p = next((x for x in load_peers() if x["id"] == pid), None)
    if p is None:
        return False
    F = fleet()
    data = (json.dumps(F.payload(F.self_facts(THIS))) + "\n").encode()
    r = ssh_to(dict(p), "fleet-sync", data=data)
    if r.returncode == 0:
        return True
    try:
        reply = json.loads(r.stdout.decode(errors="replace") or "{}")
        if reply.get("left") is True:
            return True
        old = reply.get("error") == "not allowed"
    except ValueError:
        old = False
    return old and ssh_to(dict(p), "unpair", timeout=6).returncode == 0


def serve_fleet_sync(pid: str) -> None:
    """A fleet computer sent its list: take in what's new, answer with this computer's list (both sides end up
    with the same), and pass anything new on to the rest of the fleet."""
    F = fleet()
    raw = sys.stdin.buffer.read(8 * 1024 * 1024 + 1)
    try:
        data = json.loads(raw.decode(errors="replace")) if len(raw) <= 8 * 1024 * 1024 else None
        news = F.merge_in(data, pid)
    except F.Refused:
        print(json.dumps({"error": "removed"}))
        sys.stdout.flush()
        F.reconcile(THIS)
        sys.exit(1)
    except ValueError:
        print(json.dumps({"error": "not a fleet list"}))
        sys.exit(1)
    if F.load()["local"].get("left"):
        # Acknowledge the stored, verified removal before revoking this very SSH session.
        print(json.dumps({"left": True}), flush=True)
        F.reconcile(THIS)
        return
    F.reconcile(THIS)                                       # first, so the answer says what this computer allows now
    print(json.dumps(F.payload(F.self_facts(THIS))))
    sys.stdout.flush()
    if news:
        spawn_self("fleet-sync", "--except", pid)


def keep_syncing() -> None:
    """One user worker, including when another account owns the pairing listener. If the settings worker can't run
    (its state directory is unsafe, say), the fleet list still catches up on the old schedule."""
    delay = 30
    while True:
        try:
            settings_worker()
        except Exception:                                   # notification/tool/watcher failures cannot stop catch-up
            pass
        time.sleep(delay)
        try:
            fleet_sync()
        except Exception:                                   # (never take the pairing daemon down)
            pass
        delay = 600


def shared_agents(text: str) -> str:
    """The AI helper sessions a paired computer may see: state and project only, unless the person here chose to
    share prompt text (Settings > Fleet). Prompts, permission requests and folders can hold anything."""
    try:
        d = json.loads(text or "{}")
    except ValueError:
        return '{"sessions": []}'
    try:
        share = bool(fleet().load()["local"].get("sharePrompts"))
    except Exception:                                       # (can't tell: share nothing)
        share = False
    rows = d.get("sessions") if isinstance(d, dict) and isinstance(d.get("sessions"), list) else []
    if not share:
        # no stand-in text: the state badge already says it, and the AI helpers list quotes a message as what was
        # typed ("Working" in quotes read as the prompt)
        rows = [{k: v for k, v in r.items() if k not in ("task", "message", "cwd", "prompt")} for r in rows if isinstance(r, dict)]
    return json.dumps({"sessions": rows})


def rd_off_ask(name: str) -> None:
    """The last computer allowed to see this screen left the fleet: ask whether to turn remote desktop off here."""
    env = session_env()
    shown = html.escape(safe_name(name))
    said = ask_person(env, "preferences-desktop-remote-desktop", "Turn remote desktop off on this computer?",
                      f"{shown} was the last computer allowed to see this screen. Turning it off stops Sunshine, keeps it "
                      "from starting at sign-in and takes out the firewall rule Starchaser added for it.",
                      "Turn off", "Keep on", 120)
    if said != "yes":
        return
    with state_lock():
        if jread(REMOTE_OK, {}):                            # a device was allowed meanwhile: keep it on
            return
    fw = sh("pkexec", "/usr/local/lib/starchaser/starchaser-remote-desktop", "disallow", timeout=60)
    # Sunshine runs under either of its two unit names (the package's and the Flatpak-style one)
    units = sh("systemctl", "--user", "list-unit-files", "--no-legend", env=env).stdout
    for unit in ("app-dev.lizardbyte.app.Sunshine.service", "sunshine.service"):
        if unit in units:
            sh("systemctl", "--user", "disable", "--now", unit, timeout=30, env=env)
    if shutil.which("pkill"):
        sh("pkill", "-x", "sunshine")                       # (one started by hand, outside its unit)
    if fw.returncode != 0:
        notify_desktop(env, "preferences-desktop-remote-desktop", "Remote desktop is off",
                       "Sunshine is stopped, but its firewall rule couldn't be taken out. Turn it off in Settings > "
                       "Firewall if you like; nothing answers on it now.")


def ask_big_file(name: str, fname: str, size: int, env: dict) -> bool:
    shown = html.escape(name)
    return ask_person(env, "folder-download", f"{shown} wants to send you a big file",
                      f"{html.escape(fname)} ({human_size(size)}). It goes to Downloads > From {shown}.",
                      "Accept", "Decline", 60) == "yes"


# ---------------------------------------------------------------------------------------------- settings transport
SETTINGS_CATEGORIES = ("look", "notifications", "clock-bar", "input", "power-profiles", "shortcuts-profile")
SETTINGS_LABELS = dict(zip(SETTINGS_CATEGORIES, ("Look", "Notifications", "Clock and bar", "Input", "Power profiles", "Shortcuts profile")))
# the bell's grammar: plural names take "match" ("Notifications now match qa"); said alone, a name may read better
# as a phrase ("Your shortcuts profile now matches qa")
SETTINGS_PLURAL = {"notifications", "power-profiles"}
SETTINGS_ALONE = {"shortcuts-profile": "Your shortcuts profile"}


def settings_changed_words(changed):
    """The subject and verb of the bell's "... now match(es) ..." sentence for these categories."""
    cats = [c for c in SETTINGS_CATEGORIES if c in changed]
    if len(cats) == 1:
        c = cats[0]
        return SETTINGS_ALONE.get(c, SETTINGS_LABELS[c]), "match" if c in SETTINGS_PLURAL else "matches"
    labels = [SETTINGS_LABELS[c] for c in cats]
    return ", ".join(labels[:-1]) + " and " + labels[-1], "match"
SETTINGS_STATES = {"off", "same", "different", "pending", "waiting-sign-in", "needs-update", "offline", "refused",
                   "unavailable", "error", "repair-needed", "revision-limit"}
SETTINGS_LIMIT = 256 * 1024
SETTINGS_DEADLINE = 12
SETTINGS_BIN = Path(__file__).resolve().with_name("starchaser-fleet-settings")
# the forced command and the user service must agree on this path: a session without XDG_RUNTIME_DIR still uses the
# user's runtime directory, where the worker looks for requests
SETTINGS_RUN = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser/fleet-settings"
SETTINGS_STATE = Path(os.environ.get("XDG_STATE_HOME", str(HOME / ".local/state"))) / "starchaser/fleet-settings/transport"


class SettingsFailure(ValueError):
    def __init__(self, state="error", reason="invalid-message", older=None):
        self.result = {"state": state, "reason": reason}
        if older:
            self.result["older"] = older
        super().__init__(reason)


def settings_capability() -> dict:
    """What this computer tells peers it can read: it has to match what starchaser fleet settings reads and
    writes, or records it produces are sent to nobody. Clock and bar has a second schema (the border width,
    min_reader 2); the others are still schema 1."""
    return {"protocol": 1, "reader": 2,
            "schemas": {c: ([1, 2] if c == "clock-bar" else [1]) for c in SETTINGS_CATEGORIES}}


def settings_json(raw):
    """Strict JSON at both IPC boundaries; the engine owns category payload validation."""
    if isinstance(raw, str):
        raw = raw.encode("utf-8")
    if len(raw) > SETTINGS_LIMIT:
        raise SettingsFailure(reason="message-too-large")

    def pairs(items):
        out = {}
        for key, value in items:
            if key in out:
                raise ValueError("duplicate key")
            out[key] = value
        return out

    def constant(_):
        raise ValueError("non-finite number")

    def depth(value, n=0):
        if n > 24:
            raise ValueError("too deeply nested")
        if isinstance(value, dict):
            for v in value.values():
                depth(v, n + 1)
        elif isinstance(value, list):
            for v in value:
                depth(v, n + 1)
        elif isinstance(value, float) and not (-float("inf") < value < float("inf")):
            raise ValueError("non-finite number")

    try:
        obj = json.loads(raw.decode("utf-8"), object_pairs_hook=pairs, parse_constant=constant)
        depth(obj)
        if not isinstance(obj, dict):
            raise ValueError("object required")
        return obj
    except (ValueError, UnicodeError, RecursionError, OverflowError):
        raise SettingsFailure() from None


def settings_bytes(obj) -> bytes:
    try:
        # UTF-8, as the engine prints and measures it: escaping non-ASCII would make a record the engine accepted
        # (e.g. accented app names in Notifications) too large to send.
        raw = (json.dumps(obj, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
    except (ValueError, TypeError, RecursionError):
        raise SettingsFailure() from None
    if len(raw) > SETTINGS_LIMIT:
        raise SettingsFailure(reason="message-too-large")
    return raw


def settings_version(obj):
    for key in ("protocol", "reader"):
        if type(obj.get(key)) is not int or obj[key] < 1:
            raise SettingsFailure()
    if obj["protocol"] != 1 or obj["reader"] < 1:
        raise SettingsFailure("needs-update", "protocol", "this" if obj["protocol"] > 1 else "peer")


def settings_envelope(obj, sender, response=False):
    settings_version(obj)
    if set(obj) - {"verb", "protocol", "reader", "user", "from", "records", "result"}:
        raise SettingsFailure()
    if obj.get("verb") != "settings-sync" or obj.get("from") != sender:
        raise SettingsFailure("refused", "sender")
    if obj.get("user") != ME:
        raise SettingsFailure("refused", "different-account")
    if not response and "result" in obj:
        raise SettingsFailure()
    records = obj.get("records")
    if not isinstance(records, list) or len(records) > 6:
        raise SettingsFailure()
    seen = set()
    for r in records:
        if not isinstance(r, dict) or set(r) != {"category", "rev", "writer", "digest", "payload", "schema", "min_reader"}:
            raise SettingsFailure()
        c = r["category"]
        if not isinstance(c, str) or c not in SETTINGS_CATEGORIES or c in seen:
            raise SettingsFailure()
        seen.add(c)
        if (type(r["rev"]) is not int or not 0 <= r["rev"] < 2**31
                or not isinstance(r["writer"], str) or not re.fullmatch(r"dev-[0-9a-f]{16}", r["writer"])
                or any(type(r[k]) is not int or r[k] < 1 for k in ("schema", "min_reader"))
                or not isinstance(r["payload"], dict) or not isinstance(r["digest"], str)):
            raise SettingsFailure()
        content = {k: r[k] for k in ("category", "payload", "schema", "min_reader")}
        digest = hashlib.sha256(json.dumps(content, sort_keys=True, ensure_ascii=True, allow_nan=False).encode()).hexdigest()
        if r["digest"] != digest:
            raise SettingsFailure(reason="digest")
    if response:
        result = obj.get("result")
        if (not isinstance(result, dict) or not isinstance(result.get("state"), str) or result.get("state") not in SETTINGS_STATES
                or not isinstance(result.get("state"), str)
                or set(result) - {"state", "categories", "older"}
                or not isinstance(result.get("categories", {}), dict)):
            raise SettingsFailure()
        if result["state"] == "needs-update" and result.get("older") not in ("this", "peer"):
            raise SettingsFailure()
        for c, state in result.get("categories", {}).items():
            if c not in SETTINGS_CATEGORIES or not isinstance(state, str) or state not in SETTINGS_STATES:
                raise SettingsFailure()
    return obj


def bounded_read(stream, seconds=SETTINGS_DEADLINE):
    """Read to EOF (the sender closes stdin), including a deadline for a peer that stops mid-message."""
    end, chunks, size = time.monotonic() + seconds, [], 0
    try:
        fd = stream.fileno()
    except (AttributeError, OSError):                       # in-memory streams used by module tests
        raw = stream.read(SETTINGS_LIMIT + 1)
        if len(raw) > SETTINGS_LIMIT:
            raise SettingsFailure(reason="message-too-large") from None
        return raw
    while True:
        left = end - time.monotonic()
        if left <= 0 or not select.select([fd], [], [], left)[0]:
            raise SettingsFailure(reason="read-timeout")
        chunk = os.read(fd, min(65536, SETTINGS_LIMIT + 1 - size))
        if not chunk:
            return b"".join(chunks)
        size += len(chunk)
        if size > SETTINGS_LIMIT:
            raise SettingsFailure(reason="message-too-large")
        chunks.append(chunk)


def bounded_command(cmd, data=b"", seconds=SETTINGS_DEADLINE, env=None):
    """Drain output while writing input. Bound memory, time, and both pipes, even for a faulty remote command."""
    try:
        proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
    except OSError:
        return subprocess.CompletedProcess(cmd, 1, b"", b"unavailable")
    out, err, offset, end = bytearray(), bytearray(), 0, time.monotonic() + seconds
    with selectors.DefaultSelector() as sel:
        for pipe in (proc.stdin, proc.stdout, proc.stderr):
            os.set_blocking(pipe.fileno(), False)
        sel.register(proc.stdout, selectors.EVENT_READ, out)
        sel.register(proc.stderr, selectors.EVENT_READ, err)
        if data:
            sel.register(proc.stdin, selectors.EVENT_WRITE, None)
        else:
            proc.stdin.close()
        try:
            while sel.get_map():
                left = end - time.monotonic()
                if left <= 0:
                    raise TimeoutError()
                for key, _ in sel.select(min(left, .25)):
                    if key.data is None:
                        try:
                            offset += os.write(key.fd, data[offset:offset + 8192])
                        except BrokenPipeError:
                            offset = len(data)
                        if offset == len(data):
                            sel.unregister(key.fileobj)
                            key.fileobj.close()
                    else:
                        chunk = os.read(key.fd, 65536)
                        if not chunk:
                            sel.unregister(key.fileobj)
                        else:
                            key.data.extend(chunk)
                            if len(key.data) > SETTINGS_LIMIT:
                                raise SettingsFailure(reason="message-too-large")
            proc.wait(timeout=max(.01, end - time.monotonic()))
            return subprocess.CompletedProcess(cmd, proc.returncode, bytes(out), bytes(err))
        except (TimeoutError, subprocess.TimeoutExpired):
            return subprocess.CompletedProcess(cmd, 124, b"", TIMED_OUT.encode())
        except SettingsFailure:
            return subprocess.CompletedProcess(cmd, 1, b'{"error":"message-too-large"}', b"")
        finally:
            if proc.poll() is None:
                proc.terminate()
                try:
                    proc.wait(timeout=1)
                except subprocess.TimeoutExpired:
                    proc.kill()
                    proc.wait()
            for pipe in (proc.stdin, proc.stdout, proc.stderr):
                pipe.close()


def settings_tool(*args, envelope=None, env=None):
    r = bounded_command([str(SETTINGS_BIN), *args], settings_bytes(envelope) if envelope is not None else b"",
                        seconds=20, env=env)
    try:
        obj = settings_json(r.stdout)
    except SettingsFailure:
        raise SettingsFailure("unavailable" if r.stderr == b"unavailable" else "error", "settings-tool") from None
    if args[:1] == ("apply",) and (not isinstance(obj.get("pending", {}), dict)
            or any(not isinstance(obj.get(k, []), list) for k in ("changed", "applied", "unchanged"))):
        raise SettingsFailure(reason="settings-tool")
    if r.returncode:
        result = obj.get("result", obj)
        if not isinstance(result, dict):
            raise SettingsFailure(reason="settings-tool")
        state = result.get("state", "needs-update" if r.returncode == 3 else "error")
        raise SettingsFailure(state if isinstance(state, str) and state in SETTINGS_STATES else "error", "settings-tool",
                              "this" if state == "needs-update" else None)
    return obj


def settings_private_dir(path):
    # Do not follow symlinks inside the engine's own tree (from the starchaser directory down, including an engine
    # directory above the transport's own). Above it is the person's own layout, e.g. a symlinked ~/.local or /home.
    for parent in [path, *path.parents]:
        if parent.is_symlink():
            raise OSError("unsafe settings directory")
        if parent.name == "starchaser":
            break
    missing = []
    parent = path
    while not parent.exists():
        missing.append(parent)
        parent = parent.parent
    for directory in reversed(missing):
        directory.mkdir(mode=0o700, exist_ok=True)
    for directory in [path, *path.parents]:
        st = directory.stat()
        if st.st_uid != os.getuid() or not stat.S_ISDIR(st.st_mode):
            raise OSError("unsafe settings directory")
        if directory.name == "starchaser":
            break
    path.chmod(0o700)


@contextlib.contextmanager
def settings_lock(path, blocking=True):
    settings_private_dir(path.parent)
    fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
    try:
        st = os.fstat(fd)
        if st.st_uid != os.getuid() or not stat.S_ISREG(st.st_mode):
            raise OSError("unsafe settings lock")
        os.fchmod(fd, 0o600)
        fcntl.flock(fd, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
        yield
    finally:
        os.close(fd)


def settings_read_file(path, default):
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
    except FileNotFoundError:
        return default
    with os.fdopen(fd, "rb") as f:
        st = os.fstat(f.fileno())
        if st.st_uid != os.getuid() or not stat.S_ISREG(st.st_mode):
            raise OSError("unsafe settings file")
        return settings_json(f.read(SETTINGS_LIMIT + 1))


def settings_write_file(path, obj):
    settings_private_dir(path.parent)
    if path.is_symlink() or (path.exists() and path.stat().st_uid != os.getuid()):
        raise OSError("unsafe settings file")
    fd, tmp = tempfile.mkstemp(prefix=".transport-", dir=path.parent)
    try:
        with os.fdopen(fd, "wb") as f:
            f.write(settings_bytes(obj))
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
        directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(directory)
        finally:
            os.close(directory)
    finally:
        Path(tmp).unlink(missing_ok=True)


def request_settings_sync():
    """Local IPC: the engine can also atomically replace `request` after follow, match, or publication."""
    settings_write_file(SETTINGS_RUN / "request", {"request": uuid.uuid4().hex})


def settings_members():
    try:
        F = fleet()
        doc = F.load()
    except Exception:
        raise SettingsFailure("refused", "membership unreadable") from None
    if not isinstance(doc, dict) or doc.get("unreadable"):
        raise SettingsFailure("refused", "membership unreadable")
    if doc.get("local", {}).get("left"):
        raise SettingsFailure("refused", "removed")
    return {e["link"]["device"]: e for e in doc["machines"] if e.get("link")}


def settings_member(pid):
    live = settings_members()
    if not peers_file_ok():
        raise SettingsFailure("refused", "not paired")
    p = next((p for p in load_peers() if p["id"] == pid), None)
    e = live.get(pid)
    if not p or not e or e["link"].get("key") != p.get("key"):
        raise SettingsFailure("refused", "not a fleet member")
    if p.get("user") != ME or e.get("user") != ME:
        raise SettingsFailure("refused", "different-account")
    return p, e


def settings_candidates(p):
    """Shared route ordering for the status probe and settings exchange, without changing trust or other verbs."""
    old = candidates(p)
    zone = fleet().network_zone()
    if zone == "":
        return old
    tunnel = p.get("tailscale")
    lan = [a for a in old if a != tunnel]
    if zone != "trusted":
        try:
            zones = json.loads(Path("/run/starchaser/firewall-zones.json").read_text()).get("zones", {})
        except (OSError, ValueError, AttributeError):
            zones = {}
        allowed = {card for z in ("vpn", "tailscale", "trusted") for card in zones.get(z, [])
                   if isinstance(zones.get(z), list) and isinstance(card, str)} if isinstance(zones, dict) else set()
        routed = []
        for address in lan:
            r = sh("ip", "-j", "route", "get", address, timeout=3)
            try:
                routes = json.loads(r.stdout) if r.returncode == 0 else []
                if isinstance(routes, list) and routes and all(isinstance(x, dict) and x.get("dev") in allowed for x in routes):
                    routed.append(address)
            except ValueError:
                pass
        lan = routed
    return lan + ([tunnel] if tunnel and valid_host(tunnel) else [])


def settings_ssh(p, verb, data=b""):
    r = subprocess.CompletedProcess([], 255, b"", b"no route")
    for address in settings_candidates(p):
        if not valid_peer(p) or not valid_host(address):
            continue
        r = bounded_command(ssh_command(p, address, verb), data)
        if r.returncode != 255:
            return r
        err = r.stderr.decode(errors="replace")
        if any(s in err for s in ("Permission denied (", "Host key verification failed", "IDENTIFICATION HAS CHANGED")):
            return r
    return r


def settings_reply(r):
    obj = None
    if r.stdout:
        obj = settings_json(r.stdout)
    if obj is None:
        if r.returncode in (124, 255):
            err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
            state = "refused" if any(s in err for s in ("Permission denied (", "Host key verification failed", "IDENTIFICATION HAS CHANGED")) else "offline"
            raise SettingsFailure(state, "transport")
        raise SettingsFailure()
    error = obj.get("error")
    result = obj.get("result", {})
    if not isinstance(result, dict):
        raise SettingsFailure()
    if error in ("not allowed", "needs-update", "version") or ("records" not in obj and result.get("state") == "needs-update"):
        # The responder's 'this' is our peer, so reverse it on receipt.
        older = "this" if result.get("older") == "peer" else "peer"
        raise SettingsFailure("needs-update", "version", older)
    if error in ("removed", "not paired", "not a fleet member", "refused", "membership unreadable") or result.get("state") == "refused":
        raise SettingsFailure("refused", "membership")
    if error or r.returncode:
        raise SettingsFailure()
    return obj


def settings_probe(p):
    obj = settings_reply(settings_ssh(p, "status"))
    cap = obj.get("settings_sync")
    if cap is None:
        raise SettingsFailure("needs-update", "capability", "peer")
    if not isinstance(cap, dict):
        raise SettingsFailure()
    if obj.get("id") != p["id"] or obj.get("user") != ME:
        raise SettingsFailure("refused", "different-account")
    settings_version(cap)
    schemas = cap.get("schemas")
    if (not isinstance(schemas, dict) or any(not isinstance(v, list) or not v
            or any(type(n) is not int or n < 1 for n in v) for v in schemas.values())):
        raise SettingsFailure()
    return cap


def settings_export(refresh=False, publish=False):
    obj = settings_tool("export", *(["--publish"] if publish else ["--refresh"] if refresh else []))
    # IPC contains local metadata; construct a fresh wire envelope rather than forwarding it.
    try:
        ident = IDFILE.read_text().strip()
    except OSError:
        raise SettingsFailure("unavailable", "device-identity") from None
    if not ID_RE.fullmatch(ident):
        raise SettingsFailure("unavailable", "device-identity")
    wire = {"verb": "settings-sync", "protocol": obj.get("protocol", 1), "reader": obj.get("reader", 1),
            "user": obj.get("user"), "from": "dev-" + ident, "records": obj.get("records")}
    settings_envelope(wire, "dev-" + ident)
    settings_bytes(wire)
    return wire


def settings_result(applied):
    categories = {}
    for c, state in applied.get("pending", {}).items():
        if c in SETTINGS_CATEGORIES:
            state = state.get("state") if isinstance(state, dict) else state
            categories[c] = state if isinstance(state, str) and state in SETTINGS_STATES else "pending"
    result = {"state": "pending" if categories else "same", "categories": categories}
    if "needs-update" in categories.values():
        result.update(state="needs-update", older="this")
    return result


def settings_provenance(envelope, p, winners=None):
    # Retain authenticated sender context, never payloads. Writers in a relayed record are not proof of origin.
    _, entry = settings_member(p["id"])
    name = safe_name(entry.get("label") or entry.get("hostname") or p.get("name"))
    if winners is None:
        winners = settings_export()["records"]
    accepted = {r["category"]: r for r in winners}
    with settings_lock(SETTINGS_STATE / "metadata.lock"):
        saved = settings_read_file(SETTINGS_STATE / "sources.json", {})
        changed = False
        for r in envelope["records"]:
            winner = accepted.get(r["category"])
            # A alone selects winners. Exact identity only attaches authenticated context to its selection.
            if not winner or any(winner[k] != r[k] for k in ("rev", "writer", "digest")):
                continue
            before = saved.get(r["category"], {})
            changed = changed or any(before.get(k) != r[k] for k in ("rev", "digest", "writer"))
            saved[r["category"]] = {"rev": r["rev"], "digest": r["digest"], "writer": r["writer"],
                                    "from": envelope["from"], "name": name}
        settings_write_file(SETTINGS_STATE / "sources.json", saved)
        return changed


def serve_settings_sync(pid, paired=None):
    try:
        p, _ = settings_member(pid)
        data = settings_json(bounded_read(sys.stdin.buffer))
        settings_envelope(data, "dev-" + pid)
        p, _ = settings_member(pid)                        # membership can change while the peer is writing
        status = settings_tool("status", "--json")
        follow = status.get("follow")
        if not isinstance(follow, dict) or any(type(follow.get(c)) is not bool for c in SETTINGS_CATEGORIES):
            raise SettingsFailure(reason="settings-tool")
        if not any(follow.values()):
            reply = settings_export()
            reply.update(records=[], result={"state": "off", "categories": {}})
        else:
            result = settings_tool("apply", "--stdin", "--defer", envelope=data)
            reply = settings_export()
            newer = settings_provenance(data, p, reply["records"])
            reply["result"] = settings_result(result)
            if newer:
                request_settings_sync()
        sys.stdout.write(settings_bytes(reply).decode())
    except SettingsFailure as e:
        print(json.dumps({"error": e.result["reason"], "result": e.result}))
    except OSError:
        print(json.dumps({"error": "settings unavailable", "result": {"state": "error"}}))
    sys.stdout.flush()


def settings_sync(exclude="", publish=False):
    try:
        with settings_lock(SETTINGS_STATE / "exchange.lock", blocking=False):
            settings_members()
            paired = load_peers()
            # with no paired computer there is nobody to send the records to: the engine isn't started to read them
            # (a pending apply and an explicit publication still read; pairing starts a pass that does)
            wire = settings_export(refresh=not publish, publish=publish) if paired or publish else {"records": []}
            peers, reached, unreached, updates = {}, [], [], []
            newer = False
            for p in paired:
                if p["id"] == exclude:
                    continue
                now = int(time.time())
                try:
                    settings_member(p["id"])
                    cap = settings_probe(p)                # probe each pass, including after reconnect/build changes
                    # A category the peer can't read stays pending here (needs-update); the others still exchange,
                    # and the peer's own winners still come back.
                    skipped, records = {}, []
                    for record in wire["records"]:
                        supported = cap["schemas"].get(record["category"], [])
                        if record["schema"] not in supported or record["min_reader"] > cap["reader"]:
                            skipped[record["category"]] = "this" if supported and record["schema"] < min(supported) else "peer"
                        else:
                            records.append(record)
                    settings_member(p["id"])
                    reply = settings_reply(settings_ssh(p, "settings-sync", settings_bytes({**wire, "records": records})))
                    settings_envelope(reply, "dev-" + p["id"], response=True)
                    settings_member(p["id"])
                    request = {k: v for k, v in reply.items() if k != "result"}
                    result = settings_tool("apply", "--stdin", "--defer", envelope=request)
                    accepted = settings_export()
                    newer = settings_provenance(request, p, accepted["records"]) or newer
                    if result.get("pending"):
                        result = settings_result(result)
                    else:
                        result = dict(reply["result"])
                        if result.get("state") == "needs-update":
                            result["older"] = "this" if result.get("older") == "peer" else "peer"
                    if skipped:
                        result = {**result, "categories": {**result.get("categories", {}),
                                                           **{c: "needs-update" for c in skipped}}}
                        if result.get("state") != "needs-update":
                            result.update(state="needs-update",
                                          older="this" if all(v == "this" for v in skipped.values()) else "peer")
                    if result.get("state") == "needs-update":
                        updates.append(p["id"])
                    if result.get("state") != "needs-update":
                        reached.append(p["id"])
                    # what the peer holds for each category it follows (a peer sends records only for those), so
                    # the Fleet page claims "Same" only for a record both computers really hold
                    held = {r["category"]: r["digest"] for r in reply.get("records") or []
                            if isinstance(r, dict) and r.get("category") in SETTINGS_CATEGORIES}
                    peers[p["id"]] = {**result, "held": held, "lastAttempt": now, "lastSuccess": now}
                except SettingsFailure as e:
                    peers[p["id"]] = {**e.result, "lastAttempt": now}
                    if e.result["state"] == "needs-update":
                        peers[p["id"]]["lastSuccess"] = now
                        updates.append(p["id"])
                    elif e.result["state"] == "offline":
                        unreached.append(p["id"])
            with settings_lock(SETTINGS_STATE / "metadata.lock"):
                old = settings_read_file(SETTINGS_STATE / "peers.json", {})
                for pid, result in peers.items():
                    if "lastSuccess" not in result and old.get(pid, {}).get("lastSuccess"):
                        result["lastSuccess"] = old[pid]["lastSuccess"]
                if peers or old:                           # (nobody now and nobody before: nothing to write)
                    settings_write_file(SETTINGS_STATE / "peers.json", peers)
            if newer:
                request_settings_sync()
            names = {p["id"]: safe_name(p.get("name")) for p in load_peers()}
            return {"ok": not any(p["state"] in ("error", "offline", "unavailable") for p in peers.values()), "peers": peers,
                    "reachedIds": reached, "reached": [names[p] for p in reached], "unreachedIds": unreached,
                    "unreached": [names[p] for p in unreached], "needsUpdateIds": updates,
                    "needsUpdate": [names[p] for p in updates]}
    except BlockingIOError:
        request_settings_sync()
        return {"ok": True, "queued": True}
    except SettingsFailure as e:
        return {"ok": False, "result": e.result}
    except OSError:
        return {"ok": False, "result": {"state": "error", "reason": "settings unavailable"}}


def settings_session_env():
    """logind establishes ownership; only this UID's compositor supplies its display environment."""
    listed = sh("loginctl", "list-sessions", "--no-legend", "--no-pager", timeout=4)
    if listed.returncode:
        return None
    for line in listed.stdout.splitlines():
        fields = line.split()
        if len(fields) < 3 or fields[1] != str(os.getuid()) or fields[2] != ME:
            continue
        shown = sh("loginctl", "show-session", fields[0], "--property=User", "--property=Active", "--property=Type",
                   "--property=Leader", timeout=4)
        values = dict(x.split("=", 1) for x in shown.stdout.splitlines() if "=" in x)
        if shown.returncode or values.get("User") != str(os.getuid()) or values.get("Active") != "yes" or values.get("Type") not in ("wayland", "x11"):
            continue
        if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", fields[0]):
            continue
        env = session_env()
        # The engine proves sign-in from logind's record for this session; a user service has no XDG_SESSION_ID.
        env["XDG_SESSION_ID"] = fields[0]
        # The service can retain a previous session's signature. Always discover the live instance anew.
        env.pop("HYPRLAND_INSTANCE_SIGNATURE", None)
        run = Path(env["XDG_RUNTIME_DIR"])
        for lock in sorted((run / "hypr").glob("*/hyprland.lock"), reverse=True):
            try:
                if lock.stat().st_uid != os.getuid():
                    continue
                pid, display, *_ = lock.read_text().splitlines()
                if Path(f"/proc/{int(pid)}").stat().st_uid != os.getuid():
                    continue
                if not (lock.parent / ".socket.sock").is_socket():
                    continue
                env.update(HYPRLAND_INSTANCE_SIGNATURE=lock.parent.name, WAYLAND_DISPLAY=display)
                return env
            except (OSError, ValueError):
                continue
        # No verified compositor instance: A will not apply against a stale or guessed display.
    return None


class SettingsNotifier:
    """Only the single user worker owns notification actions. Tokens never cross the network."""
    def __init__(self):
        self.proc = None
        self.notice = None
        self.guard = threading.Lock()
        self.generation = 0

    def recover(self, env):
        previous = settings_read_file(SETTINGS_RUN / "notification.json", {})
        notice = previous.get("id")
        if isinstance(notice, str) and notice.isdigit():
            self.notice = notice
            self.close(env)

    def close(self, env):
        with self.guard:
            self.generation += 1
            if self.notice:
                sh("busctl", "--user", "call", "org.freedesktop.Notifications", "/org/freedesktop/Notifications",
                   "org.freedesktop.Notifications", "CloseNotification", "u", self.notice, timeout=4, env=env)
                self.notice = None
                settings_write_file(SETTINGS_RUN / "notification.json", {})
            if self.proc and self.proc.poll() is None:
                self.proc.terminate()
            self.proc = None

    def post(self, result, env):
        changed = result.get("changed", [])
        token = result.get("undo_token")
        if (result.get("ok") is not True or result.get("notify") is not True or not changed
                or not isinstance(changed, list) or any(c not in SETTINGS_CATEGORIES for c in changed)
                or not isinstance(token, str) or not 1 <= len(token) <= 256 or any(ord(c) < 32 for c in token)):
            return
        attempted = SETTINGS_STATE / "notification.json"
        previous = settings_read_file(attempted, {})
        if previous.get("attempted") == token:
            return
        # Durable before any delivery, including closing the superseded notification.
        settings_write_file(attempted, {"attempted": token})
        self.close(env)
        words, verb = settings_changed_words(changed)
        origin = None
        sources = settings_read_file(SETTINGS_STATE / "sources.json", {})
        accepted = {r["category"]: r for r in settings_export()["records"]}
        for category in changed:
            r, source = accepted.get(category), sources.get(category, {})
            if (not r or any(source.get(k) != r[k] for k in ("rev", "writer", "digest"))
                    or source.get("writer") != source.get("from")):
                origin = None
                break
            candidate = (source["from"], source.get("name"))
            if origin is not None and candidate != origin:
                origin = None
                break
            origin = candidate
        body = (f"{words} now {verb} {html.escape(safe_name(origin[1]))}" if origin
                else f"{words} now {verb} your other computers")
        cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-p", "-w", "-a", "Starchaser", "-u", "normal", "-t", "0",
               "-h", "boolean:x-starchaser-bell-only:true", "-h", "boolean:suppress-sound:true",
               "-A", "undo=Undo", "Your fleet settings changed", body]
        if shutil.which("stdbuf"):
            cmd = ["stdbuf", "-oL", *cmd]
        try:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, env=env)
        except OSError:
            return
        with self.guard:
            self.proc = proc
            generation = self.generation
        threading.Thread(target=self.listen, args=(proc, token, generation, env), daemon=True).start()

    def listen(self, proc, token, generation, env):
        try:
            for line in proc.stdout:
                word = line.strip()
                with self.guard:
                    if generation != self.generation:
                        # Delivery may have raced with replacement before its ID reached the old listener.
                        if word.isdigit():
                            sh("busctl", "--user", "call", "org.freedesktop.Notifications", "/org/freedesktop/Notifications",
                               "org.freedesktop.Notifications", "CloseNotification", "u", word, timeout=4, env=env)
                        break
                    if word.isdigit():
                        self.notice = word
                        settings_write_file(SETTINGS_RUN / "notification.json", {"id": word})
                if word == "undo":                         # fixed action; never execute notification-supplied text
                    with settings_lock(SETTINGS_STATE / "apply.lock"):
                        with self.guard:
                            current = generation == self.generation
                        if current:
                            settings_tool("undo", "--token", token, env=env)
                    break
        except (OSError, SettingsFailure):                   # a superseded token leaves settings unchanged in A
            pass
        finally:
            with self.guard:
                if generation == self.generation:
                    self.notice = None
                    with contextlib.suppress(OSError):
                        settings_write_file(SETTINGS_RUN / "notification.json", {})
                    # Idle means the saved notice is settled too; another recovery must not have its ID erased.
                    self.proc = None
            proc.stdout.close()
            if proc.poll() is None:
                proc.terminate()
            with contextlib.suppress(subprocess.TimeoutExpired):
                proc.wait(timeout=2)


class SettingsSchedule:
    """Clock-independent scheduling, with a single run-again bit for bursts during a pass."""
    RETRIES = (5, 15, 60)

    def __init__(self, now):
        self.due = now + 30
        self.running = False
        self.again = False
        self.event = False
        self.retry = 0
        self.pending = True
        self.pending_due = now
        self.fallback = False                   # the pass and the apply now due are the 10-minute fallback's
        self.guard = threading.Lock()
        self.session_monitor = threading.Event()
        self.session_changed = threading.Event()
        self.session_check = 0
        self.wake = threading.Event()           # set by every trigger, finish and session event: the worker looks now

    def idle_seconds(self, now):
        """How long the worker can wait before something is due (an exchange, a pending apply, the session look):
        at most 5 seconds, so a stop is still seen soon."""
        with self.guard:
            due = [5.0, self.session_check - now]
            if not self.running:
                due.append(self.due - now)
            if self.pending:
                due.append(self.pending_due - now)
        return max(0.05, min(due))

    def session_check_due(self, now):
        if now < self.session_check and not self.session_changed.is_set():
            return False
        self.session_changed.clear()
        # logind's own signals (the session monitor) say when a session comes or goes; with them, this look (two
        # loginctl runs) is only a backstop, every 10 minutes, so an idle desktop isn't running it every minute
        self.session_check = now + (600 if self.session_monitor.is_set() else 5)
        return True

    def trigger(self, now):
        self.wake.set()
        with self.guard:
            self.fallback = False
            self.pending = True
            self.pending_due = now + 2
            if self.running:
                self.again = True
            else:
                self.due = now + 2
                self.event = True
                self.retry = 0

    def take_pending(self, now):
        with self.guard:
            if self.pending and now < self.pending_due:
                return False
            pending, self.pending = self.pending, False
            return pending

    def begin(self, now):
        with self.guard:
            if self.running or now < self.due:
                return False
            self.running = True
            return True

    def finish(self, now, success):
        self.wake.set()
        with self.guard:
            self.running = False
            if self.again:
                self.again = False
                self.event = True
                self.retry = 0
                self.due = now + 2
            elif not success and self.event and self.retry < len(self.RETRIES):
                self.due = now + self.RETRIES[self.retry]
                self.pending = True
                self.pending_due = self.due
                self.retry += 1
            else:
                self.event = False
                self.retry = 0
                self.due = now + 600
                self.pending = True
                self.pending_due = self.due
                self.fallback = True


SETTINGS_WATCHERS = (
    (["gdbus", "monitor", "--system", "--dest", "org.freedesktop.login1"],
     ["gdbus", "call", "--system", "--dest", "org.freedesktop.login1", "--object-path", "/org/freedesktop/login1",
      "--method", "org.freedesktop.login1.Manager.ListSessions"]),
    (["gdbus", "monitor", "--system", "--dest", "org.freedesktop.NetworkManager"],
     ["gdbus", "call", "--system", "--dest", "org.freedesktop.NetworkManager", "--object-path", "/org/freedesktop/NetworkManager",
      "--method", "org.freedesktop.DBus.Properties.GetAll", "org.freedesktop.NetworkManager"]),
    (["ip", "-j", "monitor", "address", "link"], ["ip", "-j", "address", "show"]),
)


def settings_signal(kind, line):
    if kind == 0:
        # SessionNew wakes local validation only. Exchanging with peers here would make each incoming SSH
        # start another exchange. Only a changed graphical session schedules that exchange below.
        return "PrepareForSleep" in line and "false" in line.lower()
    if kind == 1:
        return ("StateChanged" in line
                or "PropertiesChanged" in line and any(s in line for s in ("State", "ActiveConnections", "PrimaryConnection")))
    return bool(line.strip())                              # includes non-NetworkManager tunnels


class AddressChanges:
    """`ip monitor address link`, reduced to what an exchange with the fleet depends on: the addresses this computer
    has and which network cards are up. The kernel announces an address again each time its lifetime is renewed
    (every DHCP renewal, every IPv6 router advertisement) and a card for every detail (wireless scans, a changed
    setting); none of those is a network change, and every line of each used to start a pass."""
    # ip monitor prints text even when asked for JSON (iproute2 6.19):
    #   [Deleted ]2: enp1s0    inet 192.168.1.20/24 brd 192.168.1.255 scope global dynamic noprefixroute enp1s0
    #          valid_lft 3600sec preferred_lft 3600sec
    #   [Deleted ]2: enp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default
    #       link/ether 52:54:00:12:34:56 brd ff:ff:ff:ff:ff:ff
    ADDRESS = re.compile(r"(Deleted )?\d+: (\S+)\s+(inet6?) (\S+)")
    CARD = re.compile(r"(Deleted )?\d+: ([^:@\s]+)(?:@\S+)?: <([^>]*)>(?:.* state (\S+))?")

    def __init__(self):
        self.addresses, self.links = set(), {}

    @staticmethod
    def _link(flags, state):
        return (state, "UP" in flags, "LOWER_UP" in flags)

    def load(self, text):
        """The state now (`ip -j address show`), so the first monitor lines are compared with something."""
        try:
            listed = json.loads(text)
        except ValueError:
            return
        for entry in listed if isinstance(listed, list) else []:
            if isinstance(entry, dict) and isinstance(entry.get("ifname"), str):
                self.links[entry["ifname"]] = self._link(entry.get("flags") or [], entry.get("operstate"))
                for a in entry.get("addr_info") or []:
                    if isinstance(a, dict):
                        self.addresses.add((entry["ifname"], a.get("family"), f"{a.get('local')}/{a.get('prefixlen')}"))

    def _address(self, key, gone):
        changed = gone == (key in self.addresses)
        (self.addresses.discard if gone else self.addresses.add)(key)
        return changed

    def _card(self, name, link, gone):
        if gone:
            return self.links.pop(name, None) is not None
        if self.links.get(name) == link:
            return False
        self.links[name] = link
        return True

    def changed(self, line):
        """True when a monitor line adds or removes an address or a card, or turns a card on or off. A line that
        can't be read counts as a change (as every line did before)."""
        if not line.strip():
            return False
        if line[0] in " \t":
            return False                                   # the second line of an entry: lifetimes, the card's address
        match = self.ADDRESS.match(line)
        if match:
            return self._address((match[2], match[3], match[4]), bool(match[1]))
        match = self.CARD.match(line)
        if match:
            return self._card(match[2], self._link(match[3].split(","), match[4]), bool(match[1]))
        try:                                               # an ip that does print JSON: one entry or a list per line
            said = json.loads(line.strip().lstrip("[,").rstrip("],") or "null")
        except ValueError:
            return True
        if said is None:
            return False                                   # (only the list's own brackets)
        changed = False
        for entry in said if isinstance(said, list) else [said]:
            if not isinstance(entry, dict):
                return True
            gone = entry.get("deleted") is True
            if "local" in entry and "dev" in entry:
                key = (entry["dev"], entry.get("family"), f"{entry['local']}/{entry.get('prefixlen')}")
                changed = self._address(key, gone) or changed
            elif isinstance(entry.get("ifname"), str):
                link = self._link(entry.get("flags") or [], entry.get("operstate"))
                changed = self._card(entry["ifname"], link, gone) or changed
            else:
                changed = True
        return changed


def settings_session_signal(line):
    return ("SessionNew" in line or "SessionRemoved" in line
            or "PropertiesChanged" in line and "Active" in line)


def settings_watch(schedule, kind, command, query, stop):
    if not shutil.which(command[0]):
        return
    connected = False
    while not stop.is_set():
        proc = None
        try:
            proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
            # Subscribe first, then query. A change during the query remains in the monitor's pipe.
            current = bounded_command(query, seconds=4)
            if kind == 0 and current.returncode == 0:
                schedule.session_monitor.set()
                schedule.session_changed.set()
                schedule.wake.set()
            if current.returncode == 0 and connected:
                schedule.trigger(time.monotonic())
            connected = True
            addresses = AddressChanges() if kind == 2 else None
            if addresses and current.returncode == 0:
                addresses.load(bytes(current.stdout or b"").decode(errors="replace"))
            fd, pending, owner_seen = proc.stdout.fileno(), b"", False
            while not stop.is_set() and proc.poll() is None:
                if not select.select([fd], [], [], 30)[0]:  # (the timeout only looks at stop)
                    continue
                chunk = os.read(fd, 8192)
                if not chunk:
                    break
                pending += chunk
                if len(pending) > SETTINGS_LIMIT:
                    pending = b""
                    schedule.trigger(time.monotonic())
                while b"\n" in pending:
                    raw, pending = pending.split(b"\n", 1)
                    line = raw.decode(errors="replace")
                    if kind == 0 and settings_session_signal(line):
                        schedule.session_changed.set()
                        schedule.wake.set()
                    if kind < 2 and line.startswith("The name ") and ("is owned by" in line or "does not have an owner" in line):
                        # gdbus monitor's own line for the service (re)starting under it. The first is printed at
                        # subscription and the query above already covered it; a later one is a restart.
                        if owner_seen and "is owned by" in line:
                            schedule.trigger(time.monotonic())
                        owner_seen = True
                    elif settings_signal(kind, line) and (addresses is None or addresses.changed(line)):   # (the line as printed: its indent matters)
                        schedule.trigger(time.monotonic())
        except OSError:                                    # missing service/bus is quiet, fallback remains active
            pass
        finally:
            if kind == 0:
                schedule.session_monitor.clear()
                schedule.session_changed.set()
                schedule.wake.set()
            if proc:
                if proc.poll() is None:
                    proc.terminate()
                with contextlib.suppress(subprocess.TimeoutExpired):
                    proc.wait(timeout=2)
                proc.stdout.close()
        stop.wait(5)                                      # reconnect after bus/service/tunnel daemon restarts


# `request` is the transport's own wakeup; the engine writes `catch-up.json` when Follow is turned on (follow, match).
SETTINGS_REQUESTS = ("request", "catch-up.json")


def settings_request_stamp():
    """The local request files are wakeups, never instructions to run a supplied command."""
    stamps = []
    for name in SETTINGS_REQUESTS:
        try:
            st = (SETTINGS_RUN / name).lstat()
            stamps.append((st.st_ino, st.st_mtime_ns) if stat.S_ISREG(st.st_mode) and st.st_uid == os.getuid() else None)
        except FileNotFoundError:
            stamps.append(None)
    return tuple(stamps)


def settings_pending(notifier):
    if not PEERS.exists():
        # Never paired: nothing can be waiting, and the engine refuses anyway without the list of paired accounts
        # (it fails closed). That refusal used to count as a failed pass, retried three times after every event.
        return
    env = settings_session_env()
    if env is None:
        return
    # The engine rechecks current membership and session before applying; this check also fails closed.
    settings_members()
    with settings_lock(SETTINGS_STATE / "apply.lock"):
        settings_tool("export", "--refresh", env=env)        # recover and observe before applying at sign-in
        result = settings_tool("apply", "--pending", env=env)
        if result.get("ok") is not True:
            raise SettingsFailure(reason="pending-apply")
        notifier.post(result, env)


def settings_worker(stop=None):
    stop = stop or threading.Event()
    try:
        with settings_lock(SETTINGS_RUN / "worker.lock", blocking=False):
            schedule = SettingsSchedule(time.monotonic())
            notifier = SettingsNotifier()
            notifier.recover(session_env())
            stamp = settings_request_stamp()
            last_session, seen = None, False   # (the first look is startup, not a sign-in)
            apply_ok = True
            try:
                settings_pending(notifier)
            except (SettingsFailure, OSError):
                apply_ok = False
            schedule.take_pending(time.monotonic())
            # The local polling thread also receives requests while a network pass is running.
            def requests():
                nonlocal stamp
                changes = FolderChanges(SETTINGS_RUN)
                while not stop.is_set():
                    changes.wait(30)                       # (a request is a write in this folder; 30 s: looks at stop)
                    try:
                        new = settings_request_stamp()
                        if new != stamp:
                            stamp = new
                            schedule.trigger(time.monotonic())
                    except OSError:
                        pass
                changes.close()
            threading.Thread(target=requests, daemon=True).start()
            for kind, (command, query) in enumerate(SETTINGS_WATCHERS):
                threading.Thread(target=settings_watch, args=(schedule, kind, command, query, stop), daemon=True).start()
            try:
                while not stop.is_set():
                    # Prompt pending application is independent of the 30-second network startup delay.
                    try:
                        pending = schedule.take_pending(time.monotonic())
                        # The 10-minute fallback is for a change no signal told of. With no paired computer there
                        # is nobody to catch up with and nobody who could have sent anything to apply: it costs
                        # nothing then. Starting, signing in, a network change and a request still do their work.
                        if pending and schedule.fallback and not load_peers():
                            pending = False
                        if schedule.session_check_due(time.monotonic()):
                            env = settings_session_env()
                            current = (env.get("HYPRLAND_INSTANCE_SIGNATURE"), env.get("WAYLAND_DISPLAY")) if env else None
                            if current is None:
                                # logind can announce a graphical sign-in before its compositor creates the socket.
                                schedule.session_check = time.monotonic() + 5
                            if current != last_session:
                                pending = True
                                if current is not None and seen:   # graphical sign-in: catch up with the fleet too
                                    schedule.trigger(time.monotonic())
                            last_session, seen = current, True
                        if pending:
                            settings_pending(notifier)
                            apply_ok = True
                    except (SettingsFailure, OSError):
                        apply_ok = False
                    began = schedule.begin(time.monotonic())
                    if began and schedule.fallback and not load_peers():
                        schedule.finish(time.monotonic(), True)     # (the fallback, with nobody: see above)
                        began = False
                    if began:
                        def exchange():
                            success = False
                            try:
                                result = fleet_sync(wait=True)  # reconcile before exchanging settings
                                exchanged = settings_sync()
                                software_requests_module().relay(__import__("types").SimpleNamespace(**globals()))
                                # Only a pass that had someone to talk to can fail: with no paired computer the
                                # retries (5, 15 and 60 s after every network event, each a whole pass) reach nobody,
                                # and the pending apply is looked at again with the next event.
                                success = not load_peers() or (apply_ok and not result.get("unreached")
                                                               and exchanged.get("ok", False))
                            except Exception:              # preserve pairing and unpair cleanup on any failure
                                pass
                            finally:
                                schedule.finish(time.monotonic(), success)
                        threading.Thread(target=exchange, daemon=True).start()
                    schedule.wake.wait(schedule.idle_seconds(time.monotonic()))
                    schedule.wake.clear()
            finally:
                stop.set()
                notifier.close(session_env())
    except BlockingIOError:
        stop.wait()                                        # another copy owns this user's worker
    except OSError:
        # The daemon's thread supervisor retries without disturbing pairing.
        raise


# ---------------------------------------------------------------------------------------------- serving a paired device
def session_env() -> dict:
    run = f"/run/user/{os.getuid()}"
    way = next((p.name for p in sorted(Path(run).glob("wayland-*")) if not p.name.endswith(".lock")), "wayland-1")
    return {**os.environ, "XDG_RUNTIME_DIR": run, "WAYLAND_DISPLAY": way,
            "DBUS_SESSION_BUS_ADDRESS": f"unix:path={run}/bus"}


def detach(cmd: list, env: dict | None = None) -> None:
    """Start a program that outlives this call (Sunshine, Moonlight, a terminal) in a scope of its own when the
    user's service manager is reachable. Started from the link service or a paired device's SSH session, it would
    otherwise go with them: the link service restarts after every update (and on every change to a checkout), and
    an open remote desktop session would end with it."""
    env = env or os.environ
    run = env.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    quiet = dict(stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                 start_new_session=True)
    if not (shutil.which("systemd-run") and os.path.exists(os.path.join(run, "bus"))):
        p = subprocess.Popen(cmd, env=env, **quiet)
        threading.Thread(target=p.wait, daemon=True).start()    # (no zombie left in the long-running daemon)
        return
    # In the scope, a tiny shell writes one byte to a pipe and then becomes the program. No byte means
    # systemd-run gave up before starting it (the service manager refused the scope), so start it plainly
    # instead of not at all. (SIGPIPE is ignored only for the byte, so a caller that has already gone can't
    # kill the shell before the program starts; the program itself gets the normal disposition back.)
    r, w = os.pipe()
    wrapped = ["systemd-run", "--user", "--scope", "--quiet", "--collect", "--", "sh", "-c",
               'trap "" PIPE; printf . >&"$0" 2>/dev/null; eval "exec $0>&-"; trap - PIPE; exec "$@"',
               str(w), *cmd]
    try:
        p = subprocess.Popen(wrapped, env=env, pass_fds=(w,), **quiet)
    except OSError:
        p = None
    finally:
        os.close(w)
    if p is None:
        p = subprocess.Popen(cmd, env=env, **quiet)
        threading.Thread(target=p.wait, daemon=True).start()
        return

    def settle() -> None:
        # No deadline: the byte, or the pipe closing without it, always comes (systemd-run either execs the shell
        # or exits; its own D-Bus call times out). A refusal that comes late still gets the plain start. Not a
        # daemon thread, so a short-lived caller (the CLI) stays until the program has really started.
        try:
            started = os.read(r, 1) == b"."
        except OSError:
            started = True                                  # (can't tell: leave it to systemd-run)
        finally:
            os.close(r)
        if started:                                         # (p is now the program itself: reap it, don't wait on it)
            threading.Thread(target=p.wait, daemon=True).start()
            return
        p.wait()                                            # (systemd-run is exiting, not running the program)
        q = subprocess.Popen(cmd, env=env, **quiet)
        threading.Thread(target=q.wait, daemon=True).start()    # (no zombie left in the long-running daemon)
    threading.Thread(target=settle, daemon=False).start()


def receive_file(name: str, fname: str, size, ask=None) -> Path:
    """Save what comes on stdin as Downloads/From <device>/<fname>. It goes into a hidden file of its own first and
    gets its name only once it all arrived (the size the sender gave, or a complete .tar), and a name already taken
    is never written over, even by a second transfer of the same name arriving at the same moment: that one gets
    "name (2).ext". Exits with a plain reason when it can't."""
    def fail(why: str):
        print(json.dumps({"ok": False, "error": why}))
        sys.exit(1)
    downloads = (HOME / "Downloads").resolve()
    dest = HOME / "Downloads" / f"From {name}"
    # whatever the names say, the file lands in Downloads/From <device>/ and nowhere else
    if dest.is_symlink() or dest.resolve().parent != downloads:
        fail("That isn't a place files may go.")
    dest.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(prefix=".incoming-", suffix=".part", dir=dest)
    mask = os.umask(0)
    os.umask(mask)
    os.fchmod(fd, 0o666 & ~mask)                            # an ordinary file once it's there (mkstemp makes it 0600)
    got, asked = 0, False
    try:
        with os.fdopen(fd, "wb") as f:
            while True:
                chunk = sys.stdin.buffer.read(1 << 20)
                if not chunk:
                    break
                if ask and not asked and got + len(chunk) > BIG_FILE:
                    # a folder (its size isn't known up front) that grows past 4 GB: the sender waits while asked
                    asked = True
                    if not ask(fname, got + len(chunk)):
                        fail(f"{socket.gethostname()} didn't accept a transfer this big.")
                f.write(chunk)
                got += len(chunk)
        whole = got == size if size is not None else (not fname.endswith(".tar") or tar_complete(tmp, got))
        if not whole:
            fail(f"The transfer was cut short ({human_size(got)} of {human_size(size)} arrived), so nothing was kept. "
                 "Send it again." if size is not None else "The transfer was cut short, so nothing was kept. Send it again.")
        stem, dot, ext = fname.partition(".")
        for i in range(1, 10000):
            target = dest / (fname if i == 1 else f"{stem} ({i}){dot}{ext}")
            if os.path.lexists(target):                     # taken (a file, a folder or a link, wherever it points)
                continue
            if target.resolve().parent != dest.resolve():
                fail("That isn't a place files may go.")
            try:
                os.link(tmp, target)                        # takes the name only if nobody has it (never overwrites)
                return target
            except FileExistsError:
                continue
            except OSError:
                pass                                        # a drive without hard links (exFAT, some network shares)
            # the same without a hard link: reserve the name (only if nobody has it), then move the file onto it
            try:
                os.close(os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600))
            except FileExistsError:
                continue
            try:
                os.replace(tmp, target)
            except OSError:
                with contextlib.suppress(OSError):
                    os.unlink(target)
                fail("Couldn't save it in Downloads here.")
            return target
        fail("There are too many files with that name already.")
    finally:
        try:
            os.unlink(tmp)
        except OSError:
            pass


def tar_complete(path: str, size: int) -> bool:
    """Whether a folder's .tar arrived whole: every entry's contents fit inside what arrived, and it ends with the two
    empty 512-byte blocks every tar archive ends with. (The end blocks alone aren't enough: a transfer cut off inside
    a file full of zeros looks the same.)"""
    if size < 1024 or size % 512:
        return False
    with open(path, "rb") as f:
        f.seek(-1024, os.SEEK_END)
        if f.read(1024) != bytes(1024):
            return False
    import tarfile
    try:
        with tarfile.open(path, "r:") as t:
            end = 0
            for m in t:
                end = max(end, m.offset_data + -(-m.size // 512) * 512)     # contents padded to whole blocks
    except (tarfile.TarError, OSError, EOFError):
        return False
    return end + 1024 <= size


def human_size(n) -> str:
    n = int(n or 0)
    for unit in ("bytes", "KB", "MB", "GB"):
        if n < 1024 or unit == "GB":
            return f"{n} {unit}" if unit == "bytes" else f"{n:.1f} {unit}"
        n /= 1024
    return str(n)


def software_requests_module():
    for lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
        if (lib / "software_fleet_requests.py").is_file():
            if str(lib) not in sys.path:                   # (asked on every pass: the list must not grow)
                sys.path.insert(0, str(lib))
            break
    import software_fleet_requests
    return software_fleet_requests


def serve(pid: str) -> None:
    help_status()
    cmd = os.environ.get("SSH_ORIGINAL_COMMAND", "")
    try:
        removed = fleet().is_removed(pid)
    except Exception:
        if cmd != "unpair":
            print(json.dumps({"error": "membership unreadable", "result": {"state": "refused"}}))
            sys.exit(1)
        removed = False
    if removed and cmd != "unpair":
        # removed from the fleet (or lost): refused, and its key goes now if it wasn't gone already
        forget(pid)
        print(json.dumps({"error": "removed"}))
        sys.exit(1)
    with state_lock():
        p = next((x for x in load_peers() if x["id"] == pid), None)
        if p is None and cmd != "unpair":
            # a key left behind for a device that isn't paired (any more): it gets nothing, and its key goes
            # (unless peers.json didn't read: then every key would look left behind)
            if peers_file_ok():
                drop_orphan_keys({x["id"] for x in load_peers()})
            print(json.dumps({"error": "not paired"}))
            sys.exit(1)
    if p is None:                                           # (unpair: it's gone here already; tidy up the rest)
        cleared = forget(pid)
        fleet().reconcile(THIS)
        print(json.dumps({"ok": True, "sunshine": cleared}))
        return
    if p.get("role") == "helper" and cmd == "unpair":
        end_help()
        print(json.dumps({"ok": True}))
        return
    if p.get("role") in ("helper", "help-target") and cmd not in ("status", "unpair"):
        print(json.dumps({"error": "not allowed"}))
        sys.exit(1)
    name = safe_name(p.get("name"))
    env = session_env()
    fleet().record_activity(pid, name, "Signed in")
    if cmd in ("recovery", "recovery-status"):
        print(json.dumps(fleet().recovery_client().receive(pid)))
    elif cmd == "health":
        health = sh(tool_path("starchaser-fleet-watch"), "local", timeout=15)
        print(health.stdout.strip() if not health.returncode else '{"error":"Health could not be checked"}')
    elif cmd == "status":
        print(json.dumps(self_status()))
    elif cmd.startswith("recv-file ") or re.match(r"recv-sized \d+ ", cmd):
        # recv-sized SIZE NAME: the sender says how big the file is, so a transfer cut short is never kept as if it
        # were whole. (recv-file NAME: an older sender; a folder's .tar is still checked for its ending.)
        size = None
        if cmd.startswith("recv-sized "):
            _, n, raw = cmd.split(" ", 2)
            size = int(n)
        else:
            raw = cmd[len("recv-file "):]
        fname = "".join("_" if c in "/\\" else c for c in raw
                        if not unicodedata.category(c).startswith("C")).strip().lstrip(". ")[:200] or "file"
        if size is not None and size > BIG_FILE and not ask_big_file(name, fname, size, env):
            print(json.dumps({"ok": False, "error": f"{socket.gethostname()} didn't accept a file this big."}))
            sys.exit(1)
        fleet().record_activity(pid, name, "Received a file")
        target = receive_file(name, fname, size, None if size is not None else (lambda f, n: ask_big_file(name, f, n, env)))
        print(json.dumps({"saved": str(target)}))
        body = html.escape(target.name)
        if target.suffix == ".tar":                         # a folder travels packed into one file
            body += "\nA folder packed into one file. Open it to unpack it."
        subprocess.Popen([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "folder-download", f"From {html.escape(name)}", body],
                         env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    elif cmd == "clipboard":
        if fleet().load()["local"].get("sharedClipboard") is False:
            print(json.dumps({"ok": False, "error": "Shared clipboard is off on this computer."}))
            return
        fleet().record_activity(pid, name, "Shared clipboard")
        data = sys.stdin.buffer.read(16 * 1024 * 1024)
        try:
            # wl-copy forks and keeps stderr open in the background: capturing it would hang until the timeout
            ok = subprocess.run(["wl-copy"], input=data, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                                timeout=10).returncode == 0
        except (OSError, subprocess.TimeoutExpired):
            ok = False
        if not ok:
            print(json.dumps({"ok": False, "error": "Couldn't put it on the clipboard here."}))
            return
        subprocess.Popen([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "edit-paste", f"Clipboard from {html.escape(name)}", "Paste it anywhere."],
                         env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        print('{"ok": true}')
    elif cmd == "unpair":
        # (an older Starchaser, which has no fleet, unpairing: it leaves the fleet)
        try:
            if fleet().get("dev-" + pid):
                fleet().tombstone("dev-" + pid)
        except (OSError, KeyError):
            pass
        cleared = forget(pid)
        fleet().reconcile(THIS)
        print(json.dumps({"ok": True, "sunshine": cleared}))
    elif cmd == "ai-use":
        sys.exit(subprocess.run([tool_path("starchaser-ask-fleet"), "accept-choice"]).returncode)
    elif cmd in ("ai-models", "ai-chat"):
        helper = tool_path("starchaser-ask-fleet")
        sys.exit(subprocess.run([helper, "serve", "models" if cmd == "ai-models" else "chat"]).returncode)
    elif cmd == "agents":
        agent = Path(tool_path("starchaser-agent"))
        print(shared_agents(sh(str(agent), "sessions", timeout=10).stdout) if agent.exists() else '{"sessions": []}')
    elif cmd in ("software-request", "software-request-cancel", "software-request-decline"):
        result = software_requests_module().receive(__import__("types").SimpleNamespace(**globals()), p, cmd, sys.stdin.read(8193), env)
        print(json.dumps(result))
    elif cmd == "fleet-sync":
        serve_fleet_sync(pid)
    elif cmd == "settings-sync":
        serve_settings_sync(pid, p)
    elif cmd == "manage-request":
        print(json.dumps(serve_manage_request(pid, name, env)))
    elif cmd == "manage-fleet-allow":
        if not fleet().is_member(pid, p.get("key") or ""):
            print(json.dumps({"error": "not a fleet member"}))
            sys.exit(1)
        print(json.dumps(serve_manage_allow(pid, name, env)))
    elif cmd == "wol-setup":
        r = sh("pkexec", "/usr/local/lib/starchaser/starchaser-remote-desktop", "wake-on-lan", timeout=30)
        try:
            res = json.loads(r.stdout or "{}")
        except ValueError:
            res = {}
        if res.get("changed"):                              # a change to this computer is never silent
            shown = html.escape(name)
            # the title stays short so a toast never cuts the key words off; who did it goes in the body
            title = "Wake from the network turned on"
            body = (f"{shown} turned on Wake on LAN for this computer's wired connections, so {shown} can turn it on "
                    "from Settings > Fleet.")
            prev = [f"{k}={v}" for k, v in (res.get("previous") or {}).items() if isinstance(v, str)]
            if prev:                                        # Undo puts back what each connection had (the helper checks each pair)
                detach(["sh", "-c", '[ "$(/bin/sh -c \'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi\' starchaser notify -a Starchaser -i network-wired -A undo=Undo "$1" "$2")" = undo ] && shift 2 && exec pkexec /usr/local/lib/starchaser/starchaser-remote-desktop undo-wake-on-lan "$@"',
                        "sh", title, body + " Undo puts back how it was.", *prev], env)
            else:
                notify_desktop(env, "network-wired", title, body)
        print(r.stdout.strip() or json.dumps({"ok": r.returncode == 0}))
    elif cmd == "fleet-invite":
        print(json.dumps(serve_fleet_invite(pid, name, env)))
    elif cmd == "phone-ca":
        result = sh(tool_path("starchaser-fleet-ca"), "serve", pid, input=sys.stdin.readline(65537), timeout=40)
        print(result.stdout.strip() or '{"ok": false}')
    elif cmd == "login-vnc":
        os.execv(tool_path("starchaser-login-remote"), [tool_path("starchaser-login-remote"), "stream", pid])
    elif cmd == "login-screen":
        document = sys.stdin.readline(65537)
        result = sh(tool_path("starchaser-login-remote"), "relay", pid, input=document, timeout=20)
        try:
            if json.loads(document).get("body", {}).get("action") == "start" and json.loads(result.stdout).get("ok"):
                fleet().record_activity(pid, name, "Requested login-screen remote desktop")
        except (ValueError, AttributeError): pass
        print(result.stdout.strip() or '{"ok": false}')
    elif cmd == "rd-prepare":
        fleet().record_activity(pid, name, "Remote desktop")
        print(json.dumps(rd_prepare(pid, name)))
    elif cmd == "rd-login":
        print(json.dumps(rd_login(pid, name)))
    elif cmd.startswith("rd-pin "):
        parts = cmd.split()
        if len(parts) >= 3 and re.fullmatch(r"\d{4}", parts[1]):
            print(json.dumps(rd_pin(pid, name, parts[1], re.sub(r"[^\w.-]", "", parts[2])[:40] or "starchaser")))
        else:
            print('{"ok": false, "error": "bad pin"}')
    else:
        print(json.dumps({"error": "not allowed"}))
        sys.exit(1)


# ---------------------------------------------------------------------------------------------- remote desktop
SUN = HOME / ".config/sunshine"
SUN_WEB = STATE / "sunshine-web"                         # the Sunshine web-UI login Starchaser manages (user:password)
REMOTE_OK = STATE / "remote-ok.json"                     # {device id: when}: the person here allowed its remote desktop
SUN_CLIENTS = STATE / "sunshine-clients.json"            # {device id: [Sunshine client uuid]}, "_unpair": still to remove
SUN_CSRF = STATE / "sunshine-csrf"                       # the csrf_allowed_origins line Starchaser last wrote
SUN_NAME = STATE / "sunshine-name"                       # the sunshine_name Starchaser last wrote (the computer's name)
WAKE = STATE / "wake-setup.json"                         # {device id: {"tried": when, "done": bool}}
PROFILES = [("Ultrawide 3840x1080 (32:9)", "3840x1080", "wide32.png"), ("Ultrawide 3440x1440 (21:9)", "3440x1440", "ultrawide.png"),
            ("iPad Pro 2048x1536 (4:3)", "2048x1536", "ipad.png")]
# Moonlight's app list: the three resolution profiles, each making a virtual screen of that size for the stream
# (bin/sun-vd), with this computer's real screens off while it streams. Missing entries are added back; other
# entries are kept, except old "Desktop" entries that ran a prep command.
STARCHASER_APPS = {"env": {"PATH": "$(PATH):$(HOME)/.local/bin"},
                   "apps": [{"name": n, "image-path": str(Path.home() / ".config/sunshine/boxart" / img),
                             "prep-cmd": [{"do": f"sun-vd start {res}", "undo": "sun-vd stop"}]} for n, res, img in PROFILES]}


def viewer_profile(env) -> str:
    """The standard profile that fits the screen we're watching on: its largest monitor's shape picks 32:9, 21:9, or
    4:3 (the iPad profile). 21:9 if it can't tell."""
    try:
        mons = [m for m in json.loads(sh("hyprctl", "monitors", "-j", env=env).stdout or "[]") if not m.get("disabled")]
        m = max(mons, key=lambda m: m["width"] * m["height"])
        w, h = (m["height"], m["width"]) if m.get("transform", 0) % 2 else (m["width"], m["height"])
        aspect = w / h
    except (ValueError, KeyError):
        return PROFILES[1][0]
    return PROFILES[0][0] if aspect >= 3 else PROFILES[1][0] if aspect >= 2 else PROFILES[2][0]


def sunshine_unit(env=None) -> str:
    out = sh("systemctl", "--user", "list-unit-files", "--no-legend", env=env).stdout
    for name in ("app-dev.lizardbyte.app.Sunshine.service", "sunshine.service"):
        if name in out:
            return name
    return ""


def main_monitor_name():
    """The screen to stream: the largest. By connector name (DP-3): Sunshine's live session ignores a numeric
    output_name and falls back to the first monitor, though its startup probe honors the number."""
    run = Path(f"/run/user/{os.getuid()}/hypr")
    sigs = sorted(run.glob("*/.socket.sock"), key=lambda x: x.stat().st_mtime, reverse=True) if run.exists() else []
    if not sigs:
        return None
    env = dict(session_env(), HYPRLAND_INSTANCE_SIGNATURE=sigs[0].parent.name)
    try:
        mons = json.loads(sh("hyprctl", "monitors", "-j", env=env).stdout or "[]")
    except ValueError:
        return None
    mons = sorted([m for m in mons if not m.get("disabled")], key=lambda m: m["id"])
    if len(mons) < 2:
        return None
    return max(mons, key=lambda m: m["width"] * m["height"])["name"]


SUN_RESTART_OWED = STATE / "sunshine-restart-owed"      # settings changed during a stream: restart Sunshine after it


def sun_vd_streaming() -> bool:
    """A Moonlight resolution profile is streaming right now (bin/sun-vd's mark): the real screens are off and the
    stream's own screen is the only one Hyprland lists."""
    state = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state")
    run = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
    # (the state file alone outlives a power cut mid-stream; the runtime mark doesn't)
    return (state / "sun-vd" / "active").exists() and (run / "sun-vd.active").exists()


def follow_sunshine_name(lines: list, host: str) -> list:
    """The name Moonlight shows for this computer follows a rename: a sunshine_name line Starchaser wrote (the name
    it recorded, or the computer's name as it is now, which an older version wrote) is dropped so the caller writes
    the new name; one the person chose stays."""
    ours = SUN_NAME.read_text().strip() if SUN_NAME.exists() else ""
    out = []
    for l in lines:
        m = re.match(r"\s*sunshine_name\s*=\s*(.*?)\s*$", l)
        if m and m.group(1) == host and not ours:
            STATE.mkdir(parents=True, exist_ok=True)
            SUN_NAME.write_text(host + "\n")                # (an older version's line: the name it wrote is this one)
        elif m and ours and m.group(1) == ours and ours != host:
            continue
        out.append(l)
    return out


def sunshine_name_after_rename() -> None:
    """Called when the announcer starts again (Avahi restarts on a rename): a Sunshine name Starchaser wrote that is
    now the old name is rewritten, and Sunshine, when it runs and nobody is streaming, starts again to show it."""
    f = SUN / "sunshine.conf"
    if not f.exists() or not SUN_NAME.exists():
        return
    host = socket.gethostname()
    if SUN_NAME.read_text().strip() == host:
        return
    lines = f.read_text().splitlines()
    kept = follow_sunshine_name(lines, host)
    if kept == lines:
        return
    if not any(re.match(r"\s*sunshine_name\s*=", l) for l in kept):
        kept.append(f"sunshine_name = {host}")
    f.write_text("\n".join(kept) + "\n")
    SUN_NAME.write_text(host + "\n")
    env = session_env()
    unit = sunshine_unit(env)
    if unit and not sun_vd_streaming():
        sh("systemctl", "--user", "try-restart", unit, timeout=30, env=env)
    elif unit:
        SUN_RESTART_OWED.touch()


def sunshine_conf(streaming: bool = False) -> bool:
    """Starchaser's Sunshine settings: capture through Hyprland (wlr), no KDE virtual display. Returns True if changed.
    While a profile streams, the screen choice is left exactly as it is: only the stream's screen is on then, so
    the real biggest screen can't be seen to pick."""
    SUN.mkdir(parents=True, exist_ok=True)
    f = SUN / "sunshine.conf"
    lines = f.read_text().splitlines() if f.exists() else []
    keep = [l for l in lines if not re.match(r"\s*(capture|output_name|origin_web_ui_allowed)\s*=", l) and "managed by Starchaser" not in l]
    # the web UI answers only this computer until Starchaser has set its login: before that, whoever opened it
    # first on the network could claim it
    origin = "lan" if sunshine_creds()[0] else "pc"
    new = ["# capture / output / web UI: managed by Starchaser (Fleet)", "capture = wlr", f"origin_web_ui_allowed = {origin}"]
    if streaming:
        new += [l for l in lines if re.match(r"\s*output_name\s*=", l)][:1]
    else:
        main = main_monitor_name()
        if main is not None:
            new.append(f"output_name = {main}")             # the biggest screen, not whichever is listed first
    # the web page answers "CSRF Protection Error" unless it is opened at one of these: this computer's addresses
    # (home network and Tailscale), its name, name.local and localhost. A line someone wrote by hand is kept;
    # the one Starchaser wrote last is brought up to date (the addresses change).
    host = socket.gethostname()
    keep = follow_sunshine_name(keep, host)
    if not any(re.match(r"\s*sunshine_name\s*=", l) for l in keep):
        new.append(f"sunshine_name = {host}")
        STATE.mkdir(parents=True, exist_ok=True)
        SUN_NAME.write_text(host + "\n")
    names = list(dict.fromkeys(lan_addresses() + [tailscale_ip(), host, f"{host}.local", "localhost", "127.0.0.1"]))
    ours = SUN_CSRF.read_text().strip() if SUN_CSRF.exists() else ""
    theirs = [l for l in keep if re.match(r"\s*csrf_allowed_origins\s*=", l)]
    if not theirs or all((ours and l.strip() == ours) or old_csrf_line(l, host) for l in theirs):
        # names (not addresses) the line had are kept, so a web address someone used keeps working
        for l in theirs:
            names += [n for n in csrf_names(l) if not valid_ip(n) and n not in names]
        csrf = "csrf_allowed_origins = " + ",".join(f"https://{n}:47990" for n in names if n)
        keep = [l for l in keep if l not in theirs]
        new.append(csrf)
        STATE.mkdir(parents=True, exist_ok=True)
        SUN_CSRF.write_text(csrf + "\n")
    new += keep
    changed = new != lines
    if changed:
        if f.exists():
            shutil.copy(f, f.with_name(f"sunshine.conf.bak-starchaser-{time.strftime('%Y%m%d-%H%M%S')}"))
        f.write_text("\n".join(new) + "\n")
    a = SUN / "apps.json"
    cur = jread(a, {})
    # KDE-era entries (sun-vd via krfb/kscreen) have the same names and commands, so they're kept as they are
    apps = [x for x in cur.get("apps", []) if not (x.get("name") == "Desktop" and x.get("prep-cmd"))]
    names = {x.get("name") for x in apps}
    missing = [x for x in STARCHASER_APPS["apps"] if x["name"] not in names]
    if missing or not cur.get("env", {}).get("PATH"):
        if a.exists():
            shutil.copy(a, a.with_name(f"apps.json.bak-starchaser-{time.strftime('%Y%m%d-%H%M%S')}"))
        order = [x["name"] for x in STARCHASER_APPS["apps"]]
        apps = sorted(apps + missing, key=lambda x: order.index(x["name"]) if x.get("name") in order else len(order))
        jwrite(a, {**cur, "env": {**cur.get("env", {}), **STARCHASER_APPS["env"]}, "apps": apps})
        changed = True
    return changed


def csrf_names(line: str) -> list:
    """The host names / addresses in a csrf_allowed_origins line, or [] if it isn't one of plain https://X:47990
    origins."""
    origins = [o.strip() for o in line.split("=", 1)[-1].split(",")]
    m = [re.fullmatch(r"https://([A-Za-z0-9.:-]+):47990", o) for o in origins]
    return [x.group(1) for x in m] if m and all(m) else []


def old_csrf_line(line: str, host: str) -> bool:
    """The line Starchaser wrote before it kept a copy (sunshine-csrf): IPv4 addresses, then exactly this computer's
    name, name.local, name.<the network's search domain>, localhost and 127.0.0.1. Brought up to date like ours."""
    n = csrf_names(line)
    if len(n) < 5 or not n[-3].startswith(f"{host}.") or n[-3] == f"{host}.local":
        return False
    tail = [host, f"{host}.local", n[-3], "localhost", "127.0.0.1"]
    return n[-5:] == tail and all(re.fullmatch(r"\d+\.\d+\.\d+\.\d+", x) for x in n[:-5])


def sunshine_creds() -> tuple:
    """The loopback web login managed here; never shared with another fleet computer."""
    if SUN_WEB.exists():
        # only the line's own ending goes: a password may end (or start) with spaces
        u, _, pw = SUN_WEB.read_text().removesuffix("\n").partition(":")
        return u.strip(), pw
    return "", ""


def save_sunshine_creds(u: str, pw: str) -> None:
    """Store the login in one step (a file of its own, readable only by this user, then renamed into place), so a
    reader never sees half of it and a second writer can't interleave with this one."""
    STATE.mkdir(parents=True, exist_ok=True)
    tmp = SUN_WEB.with_name(f".{SUN_WEB.name}.{os.getpid()}.{threading.get_ident()}.tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(f"{u}:{pw}\n")
    os.chmod(tmp, 0o600)
    tmp.replace(SUN_WEB)


def sunshine_login_works(u: str, pw: str) -> bool:
    """Whether Sunshine takes this login, asked with the login itself (nothing is stored to find out)."""
    return curl_secret("GET", "/api/pin", [f"user = {curl_quote(f'{u}:{pw}')}"])[0] in (200, 404, 405, 400)


def sunshine_login_state() -> str:
    """'ok' (Starchaser's stored login works), 'none' (Sunshine has no login yet: its web UI shows the welcome page),
    'down' (Sunshine isn't answering at all), or 'unknown' (Sunshine has a login Starchaser doesn't know, or the
    stored one is wrong)."""
    r = sh("curl", "-sk", "-o", "/dev/null", "-w", "%{http_code} %{redirect_url}", "https://localhost:47990/", timeout=4)
    if r.stdout.split()[:1] in ([], ["000"]):
        return "down"
    if "welcome" in r.stdout:
        return "none"
    u, _ = sunshine_creds()
    if u and sunshine_api("GET", "/api/pin")[0] in (200, 404, 405, 400):
        return "ok"
    return "unknown"


def ensure_sunshine_login() -> str:
    """Bootstrap an unclaimed loopback API with a random login. An existing unknown login is never reset."""
    with state_lock():
        state = sunshine_login_state()
        if state != "none":
            return state
        username, password = "starchaser", secrets.token_urlsafe(32)
        body = json.dumps({"newUsername": username, "newPassword": password, "confirmNewPassword": password})
        code, response = curl_secret("POST", "/api/password", ['header = "Content-Type: application/json"',
                                                               f"data-binary = {curl_quote(body)}"])
        if code != 200 or response.get("status") not in (True, "true"):
            return "none"
        save_sunshine_creds(username, password)
        return "ok"


def rd_login(pid: str, peer_name: str) -> dict:
    """The login the person typed on the paired device (JSON on stdin, never on a command line). No login on Sunshine yet:
    create it with exactly that. Otherwise it must match the existing one; it is never overwritten."""
    try:
        d = json.loads(sys.stdin.readline() or "{}")
    except ValueError:
        d = {}
    u, pw = str(d.get("user", "")).strip(), str(d.get("password", ""))
    if not re.fullmatch(r"[\w.@-]{1,64}", u) or not (1 <= len(pw) <= 256) or "\n" in pw:
        return {"ok": False, "error": "Enter a username and a password."}
    if not remote_allowed(pid):
        return {"ok": False, "error": NOT_ALLOWED.format(host=socket.gethostname())}
    state = sunshine_login_state()
    if state == "down":
        return {"ok": False, "error": DOWN.format(host=socket.gethostname())}
    if state == "none":
        # Sunshine's own first-login API (what its welcome page uses; it needs no login while there is none). The
        # password goes to curl on stdin, never on a command line, where other programs could read it.
        body = json.dumps({"newUsername": u, "newPassword": pw, "confirmNewPassword": pw})
        code, res = curl_secret("POST", "/api/password", ['header = "Content-Type: application/json"',
                                                          f"data-binary = {curl_quote(body)}"])
        if code != 200 or res.get("status") not in (True, "true"):
            return {"ok": False, "error": f"Couldn't set up {socket.gethostname()}'s Sunshine login. Try again in a moment."}
        save_sunshine_creds(u, pw)
        rd_clear_pending()
        return {"ok": True, "created": True}
    # checked with the typed login itself; only one that works replaces the stored one (a wrong try, or two tries at
    # once, never puts back an older login over a newer one)
    if sunshine_login_works(u, pw):
        save_sunshine_creds(u, pw)
        rd_clear_pending()
        return {"ok": True, "created": False}
    return {"ok": False, "error": f"That isn't {socket.gethostname()}'s Sunshine login."}


NOT_ALLOWED = "Remote desktop wasn't allowed on {host}. The first time, someone at {host} has to click Allow in the notification."
DOWN = "Remote desktop didn't start on {host}. Try again, or restart {host}."


def remote_allowed(pid: str) -> bool:
    try:
        doc = fleet().load()
        p = next((p for p in load_peers() if p["id"] == pid and not p.get("role")), None)
        if doc.get("unreadable") or doc.get("local", {}).get("left") or not p or not fleet().is_member(pid, p["key"]):
            return False
        if doc["local"].get("remoteOwnFleet") is True:
            return True
        allowed = jread(REMOTE_OK, {})
        return isinstance(allowed, dict) and pid in allowed
    except (OSError, ValueError, KeyError):
        return False


def ask_remote(env: dict, pid: str, peer_name: str) -> bool:
    shown = html.escape(peer_name)
    answer = ask_person(env, "preferences-desktop-remote-desktop", f"{shown} wants to see and control this screen",
                        f"Allow only if you or someone you trust is starting remote desktop on {shown}. "
                        "The screens turn off while connected and come back afterward. You can stop streaming in Settings › Fleet.",
                        "Allow", "Don't allow", 60)
    if answer != "yes":
        return False
    with state_lock():
        if not any(x["id"] == pid for x in load_peers()):   # unpaired while the question was up
            return False
        ok = jread(REMOTE_OK, {})
        ok = ok if isinstance(ok, dict) else {}
        ok[pid] = int(time.time())
        jwrite(REMOTE_OK, ok)
    return True


def rd_prepare(pid: str, peer_name: str) -> dict:
    env = session_env()
    host = socket.gethostname()
    if not list(Path(env["XDG_RUNTIME_DIR"]).glob("wayland-*")):
        return {"ok": False, "error": f"Nobody is signed in on {host}. Turn on Remote desktop at the sign-in screen in Settings › Fleet there to connect before sign-in."}
    if not shutil.which("sunshine"):
        return {"ok": False, "error": f"Sunshine isn't installed on {host} (the Starchaser desktop setup installs it)."}
    if not remote_allowed(pid) and not ask_remote(env, pid, peer_name):
        return {"ok": False, "error": NOT_ALLOWED.format(host=host)}
    fw = sh("pkexec", "/usr/local/lib/starchaser/starchaser-remote-desktop", "allow", timeout=60)
    fwr = {}
    try:
        fwr = json.loads(fw.stdout or "{}")
    except ValueError:
        pass
    if fwr.get("why") == "turned off in the firewall":
        # the person turned remote desktop off in this computer's firewall: it stays off. Say so on both screens
        # instead of letting the connection fail with no reason.
        notify_desktop(env, "preferences-desktop-remote-desktop", f"{html.escape(peer_name)} tried to see this screen",
               "Remote desktop is turned off in this computer's firewall, so nothing was let in. "
               "You can turn it back on in Settings › Firewall.")
        return {"ok": False, "error": f"Remote desktop is turned off in {host}'s firewall. "
                                      f"To use it, turn it back on there in Settings › Firewall."}
    if (fw.returncode != 0 or fwr.get("ok") is False) and not fwr.get("unknown") and (fwr or firewall_on()):
        # (the helper couldn't run at all, e.g. pkexec refused an account outside wheel: with no firewall turned on
        # there's nothing to open, so remote desktop goes ahead as it always did)
        # the firewall step failed (refused, no password box, a policy it couldn't check or load): say so here, or
        # Sunshine starts behind closed ports and the other device asks for a login and then "Pairing didn't finish"
        errs = fwr.get("errors") if isinstance(fwr.get("errors"), str) else ""
        last = ((fw.stderr or "").strip().splitlines() or [""])[-1]
        if errs:
            why = errs
        elif fw.returncode in (126, 127) and not (fw.stdout or "").strip():
            why = "this account isn't allowed to change it"      # pkexec refused, or no way to ask
        else:
            why = last or "it didn't answer"
        return {"ok": False, "error": f"{host}'s firewall couldn't be opened for remote desktop ({why[:200]}). "
                                      f"Nothing was let in. Check Settings › Firewall on {host}."}
    unit = sunshine_unit(env)
    # a stream already running (another click on Remote desktop meanwhile) is never cut off by a restart: a change
    # waits until Sunshine is started again after the stream
    streaming = sun_vd_streaming()
    changed = sunshine_conf(streaming)
    restart = (changed or SUN_RESTART_OWED.exists()) and not streaming
    if changed and streaming:
        SUN_RESTART_OWED.touch()
    if unit:
        sh("systemctl", "--user", "enable", unit, timeout=20, env=env)
        sh("systemctl", "--user", "restart" if restart else "start", unit, timeout=30, env=env)
    elif not shutil.which("pgrep") or sh("pgrep", "-x", "sunshine").returncode != 0:
        detach(["sunshine"], env)
    if restart:
        SUN_RESTART_OWED.unlink(missing_ok=True)
    for _ in range(40):                                      # the web API answers once it's up
        if sh("curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}", "https://localhost:47990/", timeout=3).stdout.strip() not in ("", "000"):
            break
        time.sleep(0.5)
    else:
        return {"ok": False, "error": DOWN.format(host=host)}
    sunshine_unpair_waiting()                                # devices unpaired while Sunshine was down
    # a firewall change made for this connection is never silent: say what was opened
    opened = (fwr.get("added") or []) if fw.returncode == 0 and fwr.get("changed") else []
    body = ("Remote desktop was allowed through the firewall on home networks for this. "
            "You can change that in Settings › Firewall.") if "sunshine" in opened else \
           ("Finding devices was allowed through the firewall on home networks for this. "
            "You can change that in Settings › Firewall.") if opened else \
           ("Remote desktop is allowed only for certain devices or ports in this computer's firewall, and that was "
            "left as it is. You can change it in Settings › Firewall.") if "sunshine" in (fwr.get("limited") or []) else \
           "Remote desktop from a computer in your fleet."
    body += " This computer's screens turn off while it's connected and come back when it disconnects."
    notify_desktop(env, "preferences-desktop-remote-desktop", f"{html.escape(peer_name)} is connecting to this screen", body)
    login = ensure_sunshine_login()
    if login == "ok":
        rd_clear_pending()
    return {"ok": True, "login": login,
            "firewall": fwr if fw.returncode == 0 else {"ok": False, "errors": (fw.stderr or fw.stdout).strip()}}


def notify_desktop(env: dict, icon: str, title: str, body: str) -> None:
    subprocess.Popen([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", icon, title, body],
                     env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def curl_quote(text: str) -> str:
    """A value for a curl config file: double-quoted, with the escapes curl reads there."""
    for a, b in (("\\", "\\\\"), ('"', '\\"'), ("\t", "\\t"), ("\r", "\\r"), ("\n", "\\n"), ("\v", "\\v")):
        text = text.replace(a, b)
    return f'"{text}"'


def curl_secret(method: str, path: str, config: list) -> tuple:
    """curl to Sunshine's web API with `config` (login, body) read from stdin (--config -), so no password is ever
    on a command line. Returns (HTTP status, JSON answer)."""
    r = sh("curl", "-sk", "--config", "-", "-X", method, "-w", "\n%{http_code}", f"https://localhost:47990{path}",
           timeout=8, input="\n".join(config) + "\n")
    text, _, code = r.stdout.rpartition("\n")
    try:
        return int(code or 0), json.loads(text or "{}")
    except ValueError:
        return (int(code) if code.isdigit() else 0), {}


def sunshine_api(method: str, path: str, body=None) -> tuple:
    u, pw = sunshine_creds()
    config = [f"user = {curl_quote(f'{u}:{pw}')}"]
    if body is not None:
        config += ['header = "Content-Type: application/json"', f"data-binary = {curl_quote(json.dumps(body))}"]
    return curl_secret(method, path, config)


def client_ip() -> str:
    return (os.environ.get("SSH_CLIENT") or "").split(" ")[0].replace("::ffff:", "")


def rd_clear_pending() -> None:
    """A pairing that never finished blocks the next one from the same client (409): cancel those first."""
    code, d = sunshine_api("GET", "/api/pin")
    for pr in (d.get("pairings") or []) if code == 200 else []:
        if pr.get("address", "").replace("::ffff:", "") == client_ip():
            sunshine_api("DELETE", "/api/pin", {"pairing_id": pr["id"]})


def sunshine_client_list():
    """The Moonlight clients paired with this Sunshine as {uuid: name}, or None if it can't say."""
    code, d = sunshine_api("GET", "/api/clients/list")
    if code != 200:
        return None
    return {c["uuid"]: str(c.get("name") or "") for c in (d.get("named_certs") or []) if isinstance(c, dict) and c.get("uuid")}


def sunshine_clients(name=None):
    """The uuids of the Moonlight clients paired with this Sunshine (an empty set if it can't say); with `name`,
    only those paired under that name (None if it can't say)."""
    cl = sunshine_client_list()
    if cl is None:
        return None if name is not None else set()
    return {u for u, n in cl.items() if name is None or n == name}


def record_client(pid: str, before: set, client: str) -> bool:
    """Note the client Sunshine just added for this device: the new one under the name rd-pin gave it, so a device
    pairing at the same moment isn't noted as this one. (A Sunshine that lists no names: only a lone new client.)
    False when the device was unpaired (or its remote desktop taken back) while the pairing was going on: the new
    client is removed again at once, so an unpair always wins over a pairing that finished after it."""
    new, listed = set(), None
    for _ in range(20):                                     # Moonlight finishes its side of the pairing a moment later
        cl = sunshine_client_list()
        listed = cl if cl is not None else listed
        cl = cl or {}
        fresh = {u: n for u, n in cl.items() if u not in before}
        new = {u for u, n in fresh.items() if n == client}
        if not new and len(fresh) == 1 and not any(cl.values()):
            new = set(fresh)
        if new:
            break
        time.sleep(0.5)
    with state_lock():
        # checked under the same lock forget() and drop_grants() take, so an unpair is either seen here or runs
        # after this and finds the client noted
        revoked = not remote_allowed(pid) or not any(x["id"] == pid for x in load_peers())
        if not new:
            return not revoked
        data = jread(SUN_CLIENTS, {})
        data = data if isinstance(data, dict) else {}
        if revoked:
            data.pop(pid, None)
            data["_unpair"] = list(dict.fromkeys(list(data.get("_unpair") or []) + sorted(new)))
        else:
            old = set(data.get(pid) or [])
            if listed is not None:                          # an earlier try that never finished isn't a pairing
                old &= set(listed)
            data[pid] = sorted(old | new)
        jwrite(SUN_CLIENTS, data)
    if revoked:
        sunshine_unpair_waiting()
    return not revoked


def sunshine_unpair_waiting() -> bool:
    """Remove the Moonlight pairings of devices that were unpaired (only theirs, never every client). False when
    some are left because Sunshine isn't answering."""
    with state_lock():
        data = jread(SUN_CLIENTS, {})
    if not isinstance(data, dict):
        return True
    queued = list(data.get("_unpair") or [])
    names = list(data.get("_unpair_names") or [])
    if not queued and not names:
        return True
    # Sunshine's answers take a while, and an unpair may queue more meanwhile: the queue is read, worked through
    # without the lock, then put back as it is now minus what was done here
    left, names_left = list(queued), []
    for n in names:                                        # pairings from before they were noted: by name
        found = sunshine_clients(n)
        if found is None:
            names_left.append(n)
        else:
            left = list(dict.fromkeys(left + sorted(found)))
    still = []
    for u in left:
        code, _ = sunshine_api("POST", "/api/clients/unpair", {"uuid": u})
        if code != 200 and code not in (400, 404):         # (gone already counts as done)
            still.append(u)
    with state_lock():
        now = jread(SUN_CLIENTS, {})
        now = now if isinstance(now, dict) else {}
        now["_unpair"] = list(dict.fromkeys(still + [u for u in (now.get("_unpair") or []) if u not in left]))
        now["_unpair_names"] = list(dict.fromkeys(names_left + [n for n in (now.get("_unpair_names") or []) if n not in names]))
        ids = now.get("_unpair_name_ids") if isinstance(now.get("_unpair_name_ids"), dict) else {}
        now["_unpair_name_ids"] = {n: v for n, v in ids.items() if n in now["_unpair_names"]}
        jwrite(SUN_CLIENTS, now)
    return not still and not names_left


def rd_pin(pid: str, peer_name: str, pin: str, client: str) -> dict:
    """Hand Moonlight's PIN to Sunshine. Newer Sunshine wants the pending pairing's id, which we find by the
    client's address (this SSH connection's), never someone else's pending pairing; older Sunshine takes the PIN
    alone. The client Sunshine adds is noted, so unpairing the device removes it again."""
    if not remote_allowed(pid):
        return {"ok": False, "error": NOT_ALLOWED.format(host=socket.gethostname())}
    ip = client_ip()
    before = sunshine_clients()
    for _ in range(60):
        code, d = sunshine_api("GET", "/api/pin")
        if code == 200 and "pairings" in d:
            mine = [pr for pr in d["pairings"] if pr.get("address", "").replace("::ffff:", "") == ip]
            if mine:
                code, r = sunshine_api("POST", "/api/pin", {"pairing_id": mine[0]["id"], "pin": pin, "name": client})
                if r.get("status") is True:
                    if not record_client(pid, before, client):
                        return {"ok": False, "error": NOT_ALLOWED.format(host=socket.gethostname())}
                    return {"ok": True}
        elif code in (404, 405, 400):                     # an older Sunshine: no pending list
            code, r = sunshine_api("POST", "/api/pin", {"pin": pin, "name": client})
            if r.get("status") in (True, "true"):
                time.sleep(1)
                if not record_client(pid, before, client):
                    return {"ok": False, "error": NOT_ALLOWED.format(host=socket.gethostname())}
                return {"ok": True}
        time.sleep(0.5)
    return {"ok": False, "error": "Sunshine didn't take the PIN"}


FW_POLICY = Path("/etc/starchaser/policy.json")


def firewall_on() -> bool:
    """Whether this computer's firewall is turned on (its policy is readable by everyone). Unreadable but present
    counts as on, so a failed firewall step is still reported then."""
    try:
        p = json.loads(FW_POLICY.read_text())
    except FileNotFoundError:
        return False
    except (OSError, ValueError):
        return True
    return not isinstance(p, dict) or bool(p.get("enabled"))


def mark_remote_used(pid: str) -> None:
    with state_lock():
        used = jread(STATE / "remote-used.json", {})
        used = used if isinstance(used, dict) else {}
        used[pid] = int(time.time())
        jwrite(STATE / "remote-used.json", used)


def moonlight_keys() -> None:
    """Moonlight: send Super / Alt shortcuts to the other computer in a window too, not only fullscreen."""
    conf = HOME / ".config/Moonlight Game Streaming Project/Moonlight.conf"
    if not conf.exists():
        return
    t = conf.read_text()
    if re.search(r"(?m)^capturesyskeys=", t):
        return                  # set already, maybe by the person in Moonlight's own settings: theirs is kept
    if "[General]\n" in t:
        conf.write_text(t.replace("[General]\n", "[General]\ncapturesyskeys=2\n", 1))


def remote(pid: str) -> None:
    """One remote desktop start per device at a time (Settings > Fleet and the Super+R picker both start one):
    two first-time starts would ask the person there to Allow twice, and the second could hand Sunshine the other
    start's PIN."""
    p = peer(pid)
    lockdir = HOME / ".cache/starchaser/devices"
    lockdir.mkdir(parents=True, exist_ok=True)
    fd = os.open(lockdir / f"remote-{pid}.lock", os.O_RDWR | os.O_CREAT, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            print(json.dumps({"result": "failed", "busy": True,
                              "error": f"Already connecting to {p['name']}. Wait for that to finish."}), flush=True)
            return
        _remote(p, pid)
    finally:
        os.close(fd)


def login_screen_request(p, action, enrollment="", pin="", session=""):
    """Independent signature on the already pinned own-member link; helpers cannot reach this verb."""
    if not ID_RE.fullmatch(str(p.get("id", ""))) or p.get("role") in ("helper", "help-target"):
        return {}
    try:
        signed = sh(tool_path("starchaser-login-remote"), "sign", p["id"], action, enrollment, pin, session, timeout=15)
        if signed.returncode: return {}
        response = ssh_to(p, "login-screen", input=signed.stdout + "\n", timeout=25)
        value = json.loads(response.stdout or "{}")
        return value if isinstance(value, dict) else {}
    except (OSError, ValueError, subprocess.SubprocessError):
        return {}


def _remote(p: dict, pid: str) -> None:
    say = lambda **kw: print(json.dumps(kw), flush=True)
    near = {n["id"]: n for n in nearby()}
    if p["id"] in near:
        p = dict(p, address=near[p["id"]]["address"])
    used = jread(STATE / "remote-used.json", {})
    used = used if isinstance(used, dict) else {}
    say(step=f"Connecting to {p['name']}…")
    login_probe = login_screen_request(p, "probe")
    if login_probe.get("loginScreen"):
        prep = login_screen_request(p, "start", login_probe["enrollment"])
        for _ in range(25):
            if not prep.get("ok") or prep.get("state") in ("ready", "failed"): break
            time.sleep(.4)
            prep = login_screen_request(p, "probe", login_probe["enrollment"])
        if prep.get("state") != "ready":
            say(result="failed", error=prep.get("error") or "The login-screen notice didn't become ready. Try connecting again.")
            return
        prep.update(ok=True, login="ok", loginScreen=True, enrollment=login_probe["enrollment"])
        r = subprocess.CompletedProcess([], 0, json.dumps(prep), "")
    else:
        r = ssh_to(p, "rd-prepare", timeout=650)               # (up to a minute of that is the person there deciding)
    try:
        prep = json.loads(r.stdout or "{}")
    except ValueError:
        prep = {}
    if not prep.get("ok"):
        say(result="failed", error=prep.get("error") or why_not(p, r))
        return
    if prep.get("loginScreen") and (prep.get("transport") or {}).get("kind") == "vnc":
        if sh(tool_path("starchaser-login-view"), "--check", timeout=10).returncode:
            say(result="failed", error="Update Starchaser here in Settings › Updates to add the login-screen viewer, then connect again.")
            return
        detach([tool_path("starchaser-login-view"), pid], session_env())
        say(result="connected")
        return
    if not shutil.which("moonlight"):
        subprocess.Popen(["starchaser", "software", "offer", "moonlight", "Remote desktop to the computers in your fleet uses Moonlight."],
                         start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        say(result="failed", error="Moonlight isn't installed here: Starchaser offered to install it.")
        return
    mark_remote_used(pid)          # Allow was given there: the next try doesn't say "the first time" again
    addr = p["address"]
    env = dict(session_env(), LANG="C.UTF-8")             # Moonlight is a Qt app: it needs the session's display

    def paired() -> bool:                                  # paired = it can list the host's apps
        r = sh("moonlight", "list", addr, timeout=25, env=env)
        return r.returncode == 0 and ("Login screen" in r.stdout if prep.get("loginScreen") else any(n in r.stdout for n, _, _ in PROFILES))

    if not paired():
        # Pairing hands Moonlight's PIN to the host's Sunshine, which needs its web login. Starchaser never invents
        # one: ask (Settings shows a small form and writes {"user","password"} or {"cancel":true} to our stdin).
        login, err = prep.get("login", "ok"), ""
        while login != "ok":
            say(need="login", create=(login == "none"), host=p["name"], error=err)
            line = sys.stdin.readline()
            try:
                ans = json.loads(line or "{}")
            except ValueError:
                ans = {}
            if not line or ans.get("cancel"):
                say(result="failed", error="Canceled.")
                return
            lr = ssh_to(p, "rd-login", timeout=60, input=json.dumps({"user": ans.get("user", ""), "password": ans.get("password", "")}) + "\n")
            try:
                res = json.loads(lr.stdout or "{}")
            except ValueError:
                res = {}
            if res.get("ok"):
                login = "ok"
                say(step=("Created" if res.get("created") else "Using") + f" {p['name']}'s Sunshine login…")
            else:
                err = res.get("error") or why_not(p, lr)
        say(step=f"Pairing with {p['name']} (once)…")
        pin = f"{int.from_bytes(os.urandom(2), 'big') % 9000 + 1000}"
        pairing = subprocess.Popen(["moonlight", "pair", addr, "--pin", pin], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        time.sleep(1.5)
        if prep.get("loginScreen"):
            pin_answer = login_screen_request(p, "pair", prep["enrollment"], pin)
            pr = subprocess.CompletedProcess([], 0, json.dumps(pin_answer), "")
        else:
            pr = ssh_to(p, f"rd-pin {pin} {socket.gethostname()}", timeout=40)
        try:
            pin_res = json.loads(pr.stdout or "{}")
        except ValueError:
            pin_res = {}
        pin_res = pin_res if isinstance(pin_res, dict) else {}
        try:
            out, _ = pairing.communicate(timeout=40)
        except subprocess.TimeoutExpired:
            pairing.kill()
            out = ""
        if not paired():
            if not pin_res.get("ok"):
                # the other side refused the code (or never answered): its reason, not Moonlight's last line
                why = str(pin_res.get("error") or ("" if pr.returncode == 0 else why_not(p, pr))).strip()
                why = why + "." if why and why[-1] not in ".!?" else why
                say(result="failed", error=f"{p['name']} didn't accept the pairing code." + (" " + why if why else ""))
            else:
                say(result="failed", error="Pairing didn't finish" + (": " + out.strip().splitlines()[-1][-160:] if out and out.strip() else "."))
            return
    moonlight_keys()
    say(step=f"Opening Moonlight for {p['name']}…")
    detach(["moonlight", "stream", addr, "Login screen" if prep.get("loginScreen") else viewer_profile(env)], env)
    say(result="connected")                                # (Moonlight was started; it shows the screen once it connects)


# ---------------------------------------------------------------------------------------------- the list
def waiting_markers() -> list:
    """The pairings waiting for the other side (handle_pair's markers). One left behind when the link service was
    stopped mid-wait (SIGTERM skips the cleanup; only the next daemon start clears pending/) is older than the
    130 s wait and is skipped, so Settings doesn't say "Waiting for …" forever."""
    out = []
    for f in sorted(PENDING.glob("*.waiting")) if PENDING.exists() else []:
        try:
            if time.time() - f.stat().st_mtime < 150:
                out.append(f)
        except OSError:
            pass
    return out


def listing() -> dict:
    help_status()                                           # expire invalid grants before probing
    raw = jread(PEERS, [])
    all_peers = load_peers()
    peers = [p for p in all_peers if p.get("role") not in ("helper", "help-target")]
    if isinstance(raw, list) and len(all_peers) != len(raw):
        # an entry that doesn't check out (a user name that isn't one, say): drop it and every trust it had
        for x in raw:
            if not valid_peer(x) and isinstance(x, dict) and ID_RE.fullmatch(str(x.get("id", ""))):
                forget(x["id"])
        peers = [p for p in load_peers() if p.get("role") not in ("helper", "help-target")]
    near = nearby()
    browsed = NEARBY_DONE                                   # (a whole browse finished: an empty list means nobody)
    nmap = {n["id"]: n for n in near}

    def probe(p):
        if p["id"] in nmap:
            p = dict(p, address=nmap[p["id"]]["address"])
        r = ssh_to(p, "status", timeout=6)
        st = None
        if r.returncode == 0:
            try:
                st = json.loads(r.stdout)
            except ValueError:
                pass
        out = {k: p.get(k) for k in ("id", "name", "user", "kind", "address", "paired")}
        out["online"] = st is not None
        out["status"] = st
        err = r.stderr.decode(errors="replace") if isinstance(r.stderr, bytes) else (r.stderr or "")
        if r.returncode == 255 and ("Host key verification failed" in err or "IDENTIFICATION HAS CHANGED" in err):
            out["problem"] = "identity-changed"             # it answers, but not as the computer that was paired
        if st is not None and not isinstance(st, dict):
            out["online"], out["status"], st = False, None, None
        if st:                                              # keep what we learned (name changes, address)
            out["name"] = safe_name(st.get("name") or out["name"])
        return out

    with ThreadPoolExecutor(max_workers=8) as ex:
        paired = list(ex.map(probe, peers))
    # the probes take seconds, and meanwhile a pairing (or an unpair) may have changed peers.json: what they learned
    # goes into the file as it is NOW, so a device paired during this run isn't written away again
    start_wake = []
    with state_lock():
        readable = peers_file_ok()
        peers = load_peers()
        before = json.dumps(peers, sort_keys=True)
        wake = jread(WAKE, {})
        wake = wake if isinstance(wake, dict) else {}
        for p in paired:                                    # remember the latest address / name / ways to reach it
            for q in peers:
                if q["id"] == p["id"] and p["online"]:
                    st = p["status"] or {}
                    q["address"], q["name"] = p["address"], p["name"]
                    addrs = st.get("addresses") if isinstance(st.get("addresses"), list) else []
                    q["addresses"] = [a for a in addrs if valid_ip(a)][:8] or q.get("addresses") or []
                    q["tailscale"] = st.get("tailscale") if valid_ip(st.get("tailscale")) else q.get("tailscale") or ""
                    wl = [w for w in st.get("wake") or [] if isinstance(w, dict)] if isinstance(st.get("wake"), list) else []
                    q["macs"] = [w["mac"] for w in wl if valid_mac(w.get("mac"))] or q.get("macs") or []
                    q["kind"] = safe_kind(st.get("kind")) or q.get("kind")
                    # (to the few minutes a person reads it: a fresh stamp on every look would rewrite peers.json
                    # each time, and the welcome and the taskbar read the list again when that file changes)
                    if int(time.time()) - int(q.get("lastSeen") or 0) >= LAST_SEEN_STEP:
                        q["lastSeen"] = int(time.time())
                    # a desktop with a wired card: ask it (in the background, at most once a day until it works) to
                    # keep Wake on LAN on, so Wake works later. It tells the person there when it changes anything.
                    w = wake.get(q["id"]) if isinstance(wake.get(q["id"]), dict) else {}
                    if any(x.get("nm") != "magic" for x in wl) and not w.get("done") and time.time() - w.get("tried", 0) > 86400:
                        wake[q["id"]] = {"tried": int(time.time()), "done": False}
                        start_wake.append(q["id"])
            q = next((q for q in peers if q["id"] == p["id"]), {})
            p["lastSeen"], p["canWake"] = q.get("lastSeen"), bool(q.get("macs"))
        if start_wake:
            jwrite(WAKE, wake)
        known = {p["id"] for p in peers}
        # only when something changed (never over a file that didn't read): every write wakes the screens that
        # watch peers.json, and they run this list again, so an unchanged write kept an idle desktop busy
        if readable:
            if json.dumps(peers, sort_keys=True) != before:
                jwrite(PEERS, peers)
            drop_orphan_keys(known)                         # a key whose pairing was lost half-way
    paired = [p for p in paired if p["id"] in known]        # (unpaired while this ran)
    try:                                                    # what each one said about itself goes into the fleet list
        F = fleet()
        for p in paired:
            p["fleetId"] = "dev-" + p["id"]
            st = p.get("status") if p.get("online") else None
            if isinstance(st, dict):
                F.observe(p["fleetId"], {"hostname": st.get("name") if isinstance(st.get("name"), str) else "",
                                         "addresses": {"last": p.get("address") or "", "lan": st.get("addresses") or [],
                                                       "tailscale": st.get("tailscale") or ""},
                                         "macs": [w.get("mac") for w in st.get("wake") or [] if isinstance(w, dict)],
                                         "os": {"id": "", "label": st.get("os") or ""} if st.get("os") else {}},
                          by=p["id"])
    except Exception:                                       # (the list still shows the devices)
        pass
    pair_checks()
    for pid in start_wake:
        subprocess.Popen([sys.executable, os.path.realpath(__file__), "wake-prep", pid], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    sunshine_unpair_waiting()                               # (only does anything when an unpaired device is left)
    pending = [jread(f, {}) for f in sorted(PENDING.glob("*.json"))] if PENDING.exists() else []
    waiting = [w for w in (jread(f, {}) for f in waiting_markers()) if isinstance(w, dict) and w.get("id")]
    # Probes take seconds. Read grants after handshake markers: trust is written before its
    # marker disappears, so a connection completed during the probes cannot look ended.
    help_state = help_status()
    help_peers = [p for p in load_peers() if p.get("role") == "helper"]
    tag, size = fleet_badge()
    # not "nearby, not in your fleet": computers in the fleet this one hasn't taken in yet (it just joined, and the
    # list is on its way), or ones announcing this fleet's tag
    try:
        doc = fleet().load()
        members = {e["link"]["device"] for e in doc["machines"] if e.get("link")}
        # started here and nobody has joined: Settings can undo it (starchaser fleet stop)
        lone = bool(tag) and not doc["machines"] and bool((doc.get("fleet") or {}).get("lone"))
    except Exception:
        members, lone = set(), False
    near = [n for n in near if n["id"] not in known and n["id"] not in members and not (tag and n.get("fleet") == tag)]
    return {"self": self_status(), "paired": paired, "nearby": near,
            "fleet": {"tag": tag, "size": size, "lone": lone}, "fleets": fleets_nearby(near, tag),
            "tailscale": tailscale_state(peers),
            "fleetOwner": fleet_owner(), "help": help_peers, "helpSession": help_state, "pairingMode": pairing_mode(),
            "pending": pending, "waiting": waiting, "daemon": sh("systemctl", "--user", "is-active", "starchaser-link").stdout.strip() == "active",
            "sshd": remote_login_on(), "browsed": browsed,
            "avahi": sh("systemctl", "is-active", "avahi-daemon").stdout.strip() == "active"}


def fleets_nearby(near: list, mine: str) -> list:
    """The nearby computers that aren't paired with this one, grouped by the fleet they say they're in (not this
    computer's own fleet): [{tag, size, members: [names], via: [nearby computers]}], the biggest fleet first. A
    computer in no fleet yet isn't here (it stays in "nearby"). Display only: joining is still the code check."""
    groups = {}
    for n in near:
        t = n.get("fleet") or ""
        if t and t != mine:
            groups.setdefault(t, []).append(n)
    out = []
    for t, ns in groups.items():
        names = sorted(dict.fromkeys(n["name"] for n in ns), key=str.lower)
        out.append({"tag": t, "size": max([len(names)] + [int(n.get("size") or 0) for n in ns]), "members": names,
                    "via": [{k: n.get(k) for k in ("id", "name", "user", "kind", "address", "port")} for n in ns]})
    # a steady order, by name (never by the size a computer claims: anyone can announce any size, and rows that swap
    # places under the pointer put a click on the wrong fleet's Join)
    return sorted(out, key=lambda g: (g["members"][0].lower() if g["members"] else "", g["tag"]))


def tailscale_state(peers: list) -> dict:
    """Away from home: is Tailscale installed / signed in, and which other devices are on the tailnet."""
    if not shutil.which("tailscale"):
        return {"installed": False}
    try:
        d = json.loads(sh("tailscale", "status", "--json", timeout=5).stdout or "{}")
    except ValueError:
        d = {}
    running = sh("systemctl", "is-active", "tailscaled").stdout.strip() == "active"
    mine = {q.get("tailscale") for q in peers if q.get("tailscale")}
    others = []
    for peer_ in (d.get("Peer") or {}).values():
        ips = peer_.get("TailscaleIPs") or []
        if any(ip in mine for ip in ips):
            continue                                        # a paired device: it has its own card
        others.append({"name": peer_.get("HostName") or peer_.get("DNSName", "").split(".")[0], "os": peer_.get("OS", ""),
                       "online": bool(peer_.get("Online")), "ip": ips[0] if ips else ""})
    others.sort(key=lambda x: (not x["online"], x["name"].lower()))
    return {"installed": True, "running": running, "state": d.get("BackendState", "Stopped" if not running else ""),
            "ip": ((d.get("Self") or {}).get("TailscaleIPs") or [""])[0], "tailnet": (d.get("CurrentTailnet") or {}).get("Name", ""),
            "others": others}


def tailscale_up() -> None:
    """Sign in: `tailscale up` prints a login link and waits until it's used in a browser."""
    if not shutil.which("tailscale"):
        sys.exit("starchaser link: Tailscale isn't installed. Get it in Settings > Software, then sign in.")
    p = subprocess.Popen(["tailscale", "up"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    shown = False
    for line in p.stdout:
        m = re.search(r"https://login\.tailscale\.com/\S+", line)
        if m and not shown:
            print(json.dumps({"url": m.group(0)}), flush=True)
            shown = True
    p.wait()
    print(json.dumps({"result": "connected" if p.returncode == 0 else "failed"}), flush=True)


def valid_mac(mac) -> bool:
    return isinstance(mac, str) and bool(re.fullmatch(r"([0-9a-f]{2}:){5}[0-9a-f]{2}", mac.lower()))


def wake(pid: str) -> None:
    """A Wake-on-LAN magic packet: 6 x 0xFF then the MAC 16 times, broadcast on UDP 9 (and 7)."""
    p = peer(pid)
    macs = p.get("macs") or []
    if not macs:
        print(json.dumps({"ok": False, "error": f"{p['name']} hasn't said how to wake it yet (it needs a wired connection)."}))
        return
    targets = {"255.255.255.255"}
    for a in lan_addresses():                               # this network's own broadcast address too (a /24 guess)
        targets.add(".".join(a.split(".")[:3] + ["255"]))
    sent = 0
    for mac in macs:
        if not valid_mac(mac):
            continue
        raw = bytes.fromhex(mac.replace(":", ""))
        pkt = b"\xff" * 6 + raw * 16
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as so:
            so.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            for t in targets:
                for port in (9, 7):
                    try:
                        so.sendto(pkt, (t, port))
                        sent += 1
                    except OSError:
                        pass
    print(json.dumps({"ok": sent > 0, "sent": sent}))


def send(pid: str, files: list) -> None:
    p = peer(pid)

    def answer(res) -> dict:
        try:
            d = json.loads((res.stdout.decode(errors="replace") if isinstance(res.stdout, bytes) else res.stdout or "") or "{}")
        except (ValueError, AttributeError):
            d = {}
        return d if isinstance(d, dict) else {}

    for f in files:
        path = Path(f)
        made_ok = True
        try:
            if path.is_dir():
                # "--": a folder named like an option ("-photos") is still a folder name to tar
                r = subprocess.Popen(["tar", "-C", str(path.parent), "-cf", "-", "--", path.name], stdout=subprocess.PIPE,
                                     stderr=subprocess.DEVNULL)
                res = ssh_to(p, f"recv-file {path.name}.tar", binary_in=r.stdout)
                r.stdout.close()
                made_ok = r.wait() == 0
            else:
                with open(path, "rb") as fh:
                    res = ssh_to(p, f"recv-sized {os.fstat(fh.fileno()).st_size} {path.name}", binary_in=fh)
                if res.returncode != 0 and answer(res).get("error") == "not allowed":
                    with open(path, "rb") as fh:                # a device with an older Starchaser: the old way
                        res = ssh_to(p, f"recv-file {path.name}", binary_in=fh)
        except OSError as e:
            print(json.dumps({"file": path.name, "ok": False, "error": read_error(e)}), flush=True)
            continue
        err = ""
        if res.returncode != 0:                         # the other side's own reason (recv-file prints it), else plain words
            err = answer(res).get("error") or why_not(p, res)
        elif not made_ok:
            err = (f"only part of the folder arrived, because a file in it couldn't be read here. The files that "
                   f"could be read are in Downloads on {p['name']}")
        print(json.dumps({"file": path.name, "ok": res.returncode == 0 and made_ok, "error": err}), flush=True)


def read_error(e: OSError) -> str:
    """Why a file couldn't be sent, in plain words (no raw system text, no closing period: the card adds its own)."""
    if e.errno in (errno.EACCES, errno.EPERM):
        return "this account isn't allowed to read it"
    if e.errno == errno.ENOENT:
        return "it isn't there any more"
    return "it couldn't be read here" + (f" ({e.strerror.lower()})" if e.strerror else "")


def clipboard(pid: str) -> None:
    if fleet().load()["local"].get("sharedClipboard") is False:
        raise SystemExit("Shared clipboard is off. Turn it on in Settings › Fleet first.")
    p = peer(pid)
    try:
        got = subprocess.run(["wl-paste", "--no-newline"], capture_output=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        got = None
    # an empty clipboard isn't sent: wl-paste fails when nothing is copied, and an empty paste is never what was meant
    if got is None or got.returncode != 0 or not got.stdout:
        print(json.dumps({"ok": False, "error": "Nothing is copied here yet."}))
        return
    r = ssh_to(p, "clipboard", data=got.stdout)
    err = why_not(p, r) if r.returncode != 0 else ""
    try:                                                    # the other device says whether its clipboard took it
        reply = json.loads((r.stdout.decode(errors="replace") if isinstance(r.stdout, bytes) else r.stdout or "").strip() or "{}")
    except ValueError:
        reply = {}
    if r.returncode == 0 and isinstance(reply, dict) and reply.get("ok") is False:
        print(json.dumps({"ok": False, "error": reply.get("error") or f"{p['name']} couldn't take it."}))
        return
    print(json.dumps({"ok": r.returncode == 0, "error": err}))


def wake_prep(pid: str) -> None:
    p = peer(pid)
    r = ssh_to(p, "wol-setup", timeout=40)
    try:
        ok = r.returncode == 0 and json.loads(r.stdout or "{}").get("ok") is True
    except ValueError:
        ok = False
    with state_lock():
        wake = jread(WAKE, {})
        wake = wake if isinstance(wake, dict) else {}
        if any(x["id"] == pid for x in load_peers()):       # (not for a device unpaired meanwhile)
            wake[pid] = {"tried": int(time.time()), "done": ok}
            jwrite(WAKE, wake)


def unpair(pid: str, lost: bool = False) -> None:
    """Remove a device from the fleet: on every computer, not only this one (starchaser fleet remove)."""
    p = peer(pid)
    res = fleet().remove_flow("dev-" + pid, lost=lost)
    here = not (jread(SUN_CLIENTS, {}) or {}).get("_unpair")
    notes = [res["note"]] if res.get("note") else []
    if not here:
        notes.append(f"Remote desktop isn't running on this computer right now, so {p['name']}'s access to it is taken "
                     "away within a minute of it starting again.")
    print(json.dumps({"ok": True, "note": " ".join(notes)}))


if __name__ == "__main__":
    if sys.argv[1:2] == ["help"] or any(a in ("-h", "--help") for a in sys.argv[1:]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    a = sys.argv[1:]
    cmd = a[0] if a else "list"
    if cmd in ("daemon", "self", "tailscale-up") and len(a) > 1:
        sys.exit(takes_nothing_after("starchaser link", cmd, a))
    if cmd == "daemon":
        daemon()
    elif cmd == "list":
        if len(a) > 1:
            sys.exit(takes_nothing_after("starchaser link", "list", a))
        # the look for nearby devices runs a whole network browse (a few seconds with none around): say so on the
        # terminal while it goes, never on the JSON line Settings reads
        print("Looking for nearby devices\u2026", file=sys.stderr)
        print(json.dumps(listing()))
    elif cmd == "self":
        print(json.dumps(self_status()))
    elif cmd == "discovery" and len(a) <= 2 and a[1:] in ([], ["on"], ["off"], ["auto"]):
        if a[1:]:
            set_discovery({"on": True, "off": False, "auto": None}[a[1]])
        print(json.dumps(discovery_status()))
    elif cmd == "pairing-mode" and len(a) in (2, 3) and a[1] in ("fleet", "help", "off") and a[2:] in ([], ["--window"]):
        set_pairing_mode(a[1], window=a[2:] == ["--window"])
        print(json.dumps({"ok": True, "mode": pairing_mode()}))
    elif cmd == "sunshine-login" and len(a) == 1:
        username, password = sunshine_creds()
        print(json.dumps({"ok": bool(username), "user": username, "password": password}))
    elif cmd == "help-shell" and len(a) == 2 and ID_RE.fullmatch(a[1]):
        help_shell(a[1])
    elif cmd == "help-visible" and len(a) == 1:
        print(json.dumps(help_visible()))
    elif cmd == "help-status" and len(a) == 1:
        print(json.dumps(help_status()))
    elif cmd == "end-help" and len(a) == 1:
        sessions = end_help()
        print(json.dumps({"ok": True, "sessionsEnded": sessions["complete"],
                          "note": "Help keys are removed, but some remote sign-ins couldn't be ended. Turn off Remote login in Settings › Security." if not sessions["complete"] else ""}))
    elif cmd == "pair" and len([x for x in a if x not in ("--no-manage", "--help-only")]) >= 2:
        manage = "--no-manage" not in a
        help_only = "--help-only" in a
        a = [x for x in a if x not in ("--no-manage", "--help-only")]
        port = PORT
        if len(a) > 2:
            port = int(a[2]) if a[2].isdigit() else 0
            if not 1 <= port <= 65535:
                print(json.dumps({"result": "failed", "error": "The port must be a number from 1 to 65535."}))
                sys.exit(2)
        if (pair(a[1], port, manage, help_only=help_only) or {}).get("result") in ("unreachable", "failed"):
            sys.exit(1)
    elif cmd == "join" and len([x for x in a if x != "--no-manage"]) >= 2:
        manage = "--no-manage" not in a
        a = [x for x in a if x != "--no-manage"]
        port = PORT
        if len(a) > 2:
            port = int(a[2]) if a[2].isdigit() else 0
            if not 1 <= port <= 65535:
                print(json.dumps({"result": "failed", "error": "The port must be a number from 1 to 65535."}))
                sys.exit(2)
        join(a[1], port, manage)
    elif cmd == "join-wait" and len(a) in (1, 2) and (len(a) == 1 or a[1].isdigit()):
        join_wait(min(int(a[1]), 600) if len(a) == 2 else 60)
    elif cmd == "more-time" and len(a) == 2 and re.fullmatch(r"[0-9a-f]{8}", a[1]):
        if not (PENDING / f"{a[1]}.json").exists():
            raise SystemExit("That question ended. Try again.")
        fleet().write_atomic(PENDING / f"{a[1]}.more", "more", 0o600)
        print('{"ok":true}')
    elif cmd == "answer":
        # the answer word and the id are checked apart: 'yes' is usually right and the id is what's wrong, so say
        # which; a request that is already answered or gone says so instead of leaving an answer file nothing reads
        if len(a) != 3:
            sys.exit(usage_error("starchaser link", "answer needs a request ID and yes or no",
                                 "answer <request-id> yes|no", ("yes", "no")))
        if a[2] not in ("yes", "no"):
            sys.exit(usage_error("starchaser link", "wrong arguments for 'answer'",
                                 "answer <request-id> yes|no", ("yes", "no")))
        if not re.fullmatch(r"[0-9a-f]{8}", a[1]) or not (PENDING / f"{a[1]}.json").exists():
            sys.exit(f"starchaser link: no pairing request with id '{a[1]}' (ids come from 'starchaser link list')")
        fleet().write_atomic(PENDING / f"{a[1]}.answer", a[2], 0o600)
    elif cmd == "send" and len(a) >= 3:
        send(a[1], a[2:])
    elif cmd == "clipboard" and len(a) == 2:
        clipboard(a[1])
    elif cmd == "unpair" and len(a) in (2, 3) and a[2:] in ([], ["--lost"]):
        unpair(a[1], lost=a[2:] == ["--lost"])
    elif cmd == "software-request" and len(a) == 1:
        software_requests_module().relay(__import__("types").SimpleNamespace(**globals()))
    elif cmd == "software-request-cancel" and len(a) == 2 and re.fullmatch(r"[0-9a-f]{32}", a[1]):
        software_requests_module().relay(__import__("types").SimpleNamespace(**globals()), cancel=a[1])
    elif cmd == "software-request-decline" and len(a) == 3 and ID_RE.fullmatch(a[1]) and re.fullmatch(r"[0-9a-f]{32}", a[2]):
        print(ssh_to(peer(a[1]), "software-request-decline", input=json.dumps({"id": a[2]})).stdout)
    elif cmd == "fleet-sync" and (len(a) == 1 or (len(a) == 3 and a[1] == "--except" and ID_RE.fullmatch(a[2]))):
        print(json.dumps(fleet_sync(exclude=a[2] if len(a) == 3 else "")))
    elif cmd == "settings-sync" and (len(a) == 1 or (len(a) == 3 and a[1] == "--except" and ID_RE.fullmatch(a[2]))):
        print(json.dumps(settings_sync(exclude=a[2] if len(a) == 3 else "")))
    elif cmd == "manage-request" and (len(a) == 2 or (len(a) == 3 and a[2] == "--after-pair")):
        res = manage_request_after_pair(a[1]) if len(a) == 3 else manage_request(a[1])
        print(json.dumps(res))
        sys.exit(0 if res.get("ok") else 1)
    elif cmd == "manage-fleet-allow" and len(a) == 1:
        print(json.dumps(share_manage_allow()))
    elif cmd == "rd-off-ask" and len(a) == 2:
        rd_off_ask(a[1])
    elif cmd == "remote" and len(a) == 2:
        remote(a[1])
    elif cmd == "agent-attach" and len(a) >= 2:
        # your own SSH login (the link key can't open a terminal), attached to the agent's tmux session if it has one
        p = peer(a[1])
        tmux = re.sub(r"[^\w.-]", "", a[2]) if len(a) > 2 else ""
        where = candidates(p)
        if not where:
            sys.exit(f"no address for {p['name']}")
        # the host key pairing verified, never a first-use prompt; the account's own key (the fleet's manage key)
        remote_cmd = ["ssh", "-t", "-o", f"UserKnownHostsFile={KNOWN}", "-o", f"HostKeyAlias=starchaser-{p['id']}",
                      "-o", "StrictHostKeyChecking=yes", "-l", p["user"], "--", where[0]] + [shlex.join(["sh", "-c",
                          # the other computer's fleet tool: an older Starchaser has it on PATH, a newer one off PATH
                          'for d in "$HOME/.local/bin" /usr/lib/starchaser/bin /usr/bin; do [ -x "$d/starchaser-fleet" ] && exec "$d/starchaser-fleet" "$@"; done; exit 127',
                          "starchaser", "terminal-session", socket.gethostname(), *([tmux] if tmux else [])])]
        detach(["starchaser", "terminal", "--title", f"{p['name']}" + (f" · {tmux}" if tmux else ""), *remote_cmd])
    elif cmd == "wake" and len(a) == 2:
        wake(a[1])
    elif cmd == "tailscale-up":
        tailscale_up()
    elif cmd == "wake-prep" and len(a) == 2:
        wake_prep(a[1])
    elif cmd == "serve" and len(a) == 2:
        serve(a[1])
    elif cmd == "fleet-invite" and len(a) == 3:
        sys.exit(fleet_invite_send(a[1], a[2]))
    else:
        commands = {
            **{name: (name, (), ()) for name in
               ("daemon", "list", "self", "tailscale-up", "manage-fleet-allow")},
            **{name: (f"{name} <device-id>", ("device ID",), ()) for name in
               ("clipboard", "remote", "wake", "wake-prep", "serve", "rd-off-ask")},
            **{name: (f"{name} <address> [port] [--no-manage]", ("address",), ())
               for name in ("pair", "join")},
            **{name: (f"{name} [--except <device-id>]", (), ())
               for name in ("fleet-sync", "settings-sync")},
            "join-wait": ("join-wait [seconds]", (), ()),
            "answer": ("answer <request-id> yes|no", ("request ID", "answer"), ("yes", "no")),
            "send": ("send <device-id> <file> [file ...]", ("device ID", "file"), ()),
            "unpair": ("unpair <device-id> [--lost]", ("device ID",), ()),
            "manage-request": ("manage-request <device-id> [--after-pair]", ("device ID",), ()),
            "agent-attach": ("agent-attach <device-id> [session]", ("device ID",), ()),
        }
        sys.exit(command_usage_error("starchaser link", [x for x in a if x != "--no-manage"], commands,
                                       internal=("rd-off-ask", "agent-attach")))
