---
name: iphone-tailnet
description: Build, install, launch and screenshot iOS apps on an iPhone from a Mac over Tailscale when the phone is on another network. Use when setting up the tailnet relay for a phone, deploying to a remote iPhone, or troubleshooting `xcrun devicectl` showing a phone as unavailable or "peer no longer reachable".
---

# Xcode → iPhone over Tailscale

Xcode and `devicectl` can reach an iPhone wirelessly only when it is on the same LAN. This self-contained setup lets a Mac build, install, launch, and screenshot apps on an iPhone from anywhere over Tailscale.

It has two small parts:

- **`advertise.c`**: re-advertises the phone's own `_remotepairing._tcp` Bonjour record plus a spoofed `.local` A record on **one LAN interface only**, pointing to the Mac.
- **`tunnel_relay.py`**: listens on that LAN address for the phone's pairing port and dynamic tunnel ports, forwarding bytes to the phone's Tailscale IP.

The relay only moves bytes. Pairing and the developer tunnel remain end-to-end encrypted between Xcode and the phone.

Based on [this guide](https://dev.to/kvnpt/how-to-remotely-iterate-deploy-your-sideloaded-ios-apps-over-tailnet-jak), generalised to follow dynamic TCP tunnel ports (see [Why it's built this way](#why-its-built-this-way-dont-simplify-these)). Everything needed is embedded verbatim in the [Files](#files) section below — no external repositories or machine-specific scripts are required.

## Layout on disk

- **Scripts:** `~/.local/share/iphone-tailnet/` (`relay.sh`, `advertise.c`, `tunnel_relay.py`, plus the compiled `advertise` binary)
- **Per-phone config, log & state:** `~/.config/iphone-tailnet/` (default settings file `~/.config/iphone-tailnet/device.env`; override with `IPHONE_TAILNET_CONF` for additional phones)
  - `device.env` — phone's Tailscale IP, Bonjour instance name, pairing port, and TXT record (**contains the phone's pairing `authTag`: `chmod 600`, and never print, paste, or commit it**)
  - `relay.log` — stdout/stderr log next to `device.env`
  - `last-tunnel-port` — saved tunnel port counter next to `device.env`
- **LaunchAgent:** `~/Library/LaunchAgents/local.iphone-tailnet.plist`

## Setting it up for a phone

1. **Prerequisites on both devices:**
   - Install Tailscale on the Mac and the iPhone, signed into the same tailnet. Note the phone's Tailscale IPv4 address (`tailscale status`).
   - Enable Developer Mode on the iPhone (`Settings → Privacy & Security → Developer Mode`).
   - Pair the phone with Xcode over USB once on the Mac, and check **"Connect via network"** in Xcode's *Devices and Simulators* window.
   - Note the phone's UDID: `xcrun devicectl list devices`.
   - Ensure full Xcode (not just Command Line Tools) is installed on the Mac.

2. **Install the relay scripts:**
   Create `~/.local/share/iphone-tailnet/` and write `relay.sh`, `advertise.c`, and `tunnel_relay.py` from the [Files](#files) section below, then `chmod +x ~/.local/share/iphone-tailnet/relay.sh ~/.local/share/iphone-tailnet/tunnel_relay.py`. (`relay.sh` compiles `advertise.c` automatically with `clang` on first run.)

3. **Capture the phone's Bonjour record** from a Mac on the phone's own Wi-Fi network, with the phone awake:
   ```bash
   dns-sd -B _remotepairing._tcp local.                    # note the Instance Name
   dns-sd -L "<instance>" _remotepairing._tcp local.       # note the port and TXT key=value pairs
   ```
   If this Mac isn't on the phone's network, ask the user to run those two commands on a Mac that is, and write the values straight into `device.env` without echoing `PAIR_TXT` to logs.

4. **Check how the phone opens its tunnel:**
   - With the phone on the same LAN as the Mac, run any `devicectl` command against it (e.g. `xcrun devicectl device info details --device <UDID>`), then run:
     ```bash
     /usr/bin/log show --last 5m --predicate 'process == "remotepairingd" AND eventMessage CONTAINS "tunnel endpoint"'
     ```
   - Note the port numbers and whether they climb by one each connection.
   - Many iPhones use **TCP ports on an incrementing counter** (e.g. 64250, 64251, …), which `tunnel_relay.py` handles out of the box.
   - If your phone uses **UDP** or a different port scheme (the original article's phone used UDP on 55xxx), adapt the forwarder to UDP for that range before assuming TCP.

5. **Create the settings file:**
   `mkdir -p ~/.config/iphone-tailnet && chmod 700 ~/.config/iphone-tailnet`, create `~/.config/iphone-tailnet/device.env` from the template below, and `chmod 600 ~/.config/iphone-tailnet/device.env`:
   - `PHONE_IP`: the phone's Tailscale IPv4 address
   - `SPOOF_HOSTNAME`: any unused `<name>.local` hostname
   - `INSTANCE`, `PAIR_PORT`, `PAIR_TXT`: from step 3
   - `TUNNEL_PORT_GUESS`: near the tunnel port from step 4 (the relay tracks it from there)
   - `BIND_IF` / `BIND_IP` *(optional)*: leave unset for a single phone; set to pin a specific LAN interface or IP alias

6. **Install and start the LaunchAgent:**
   - Write `~/Library/LaunchAgents/local.iphone-tailnet.plist` from the template below, replacing `/Users/YOU` with your actual `$HOME`.
   - Load it:
     ```bash
     launchctl bootstrap gui/$UID ~/Library/LaunchAgents/local.iphone-tailnet.plist
     ```

7. **Verify:**
   Move the phone off the Mac's LAN (e.g. another Wi-Fi network with Tailscale active). Check:
   ```bash
   export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
   xcrun devicectl list devices | grep <UDID>
   ```
   It should report `available` or `connected`. Try installing a build.

### Running relays for more than one phone on one Mac

Each relay binds to an IPv4 address on the Mac's LAN interface. Two phones with the same pairing port or overlapping 160-port tunnel windows will collide if they share an IP.

- **Simple option:** keep separate plists/configs (`~/.config/iphone-tailnet/<phone>/device.env` via `IPHONE_TAILNET_CONF`) and only run one at a time (`launchctl bootout` / `bootstrap`).
- **Simultaneous option:** add an IP alias on the LAN interface (`sudo ifconfig en0 alias <unused-lan-ip> 255.255.255.255`) and set `BIND_IP=<unused-lan-ip>` in the second phone's `device.env`, with its own `SPOOF_HOSTNAME`, `IPHONE_TAILNET_CONF`, log path, and LaunchAgent label.

## Day-to-day use

Every `xcrun` call needs full Xcode selected (otherwise you get `unable to find utility "devicectl"`):

```bash
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
D=<PHONE_UDID>

# check reachability ("available" or "connected")
xcrun devicectl list devices | grep "$D"

# build (Release, automatic signing) and install
xcodebuild -project MyApp.xcodeproj -scheme MyApp -configuration Release \
  -destination 'generic/platform=iOS' -derivedDataPath build/dd -allowProvisioningUpdates build
xcrun devicectl device install app --device "$D" build/dd/Build/Products/Release-iphoneos/MyApp.app

# launch; pass app arguments after `--` (without `--`, devicectl rejects -Flags)
xcrun devicectl device process launch --device "$D" --terminate-existing com.example.myapp -- -SomeFlag value

# capture a screenshot and shrink it before inspecting
xcrun devicectl device capture screenshot --device "$D" --destination /tmp/shot.png
sips -Z 900 /tmp/shot.png
```

A ready-to-adapt `deploy.sh` is included in [Files](#files).

Things to expect:
- **The first install after a while away fails, then the retry works.** The phone's tunnel port counter has moved past the relay's 160-port window; the failed attempt prints the new port to `remotepairingd`'s log, the relay slides its window, and the retry succeeds. That is why `deploy.sh` retries once.
- **"Installed but not launched":** the phone is locked. Unlock it or tap the app icon on the home screen.
- **"Peer no longer reachable":** usually transient; retry once.
- **Automated visual verification:** you can't tap the screen remotely. Add launch-argument hooks in your app (read via `UserDefaults` / `ProcessInfo.processInfo.arguments`) to open specific screens or trigger states, then capture a screenshot with `devicectl device capture screenshot` and delete temporary screenshots when done.

## When the phone shows as unavailable

Check these in order:

1. **Is the relay running?**
   ```bash
   launchctl print gui/$UID/local.iphone-tailnet | grep state
   tail -30 ~/.config/iphone-tailnet/relay.log
   ```
   Restart with `launchctl kickstart -k gui/$UID/local.iphone-tailnet`. If the LAN interface has no IPv4 address, the relay exits until the network returns.
2. **Is the phone on Wi-Fi with Tailscale active?**
   Check `tailscale ping <PHONE_IP>`. When an iPhone is on cellular only, its `_remotepairing._tcp` port is closed. iOS can also suspend the Tailscale VPN in the background — open the Tailscale app on the phone to wake it.
3. **Did the phone switch Wi-Fi networks?**
   Its Bonjour `authTag` can rotate. Recapture `INSTANCE`, `PAIR_PORT`, and `PAIR_TXT` (setup step 3), update `device.env`, and kickstart the LaunchAgent.
4. **Did the phone reboot?**
   After a reboot, iOS needs one USB connection to a Mac running Xcode to stage its developer disk image again. Once staged, Tailscale deploys work again.
5. **Inspect `remotepairingd`'s log:**
   ```bash
   /usr/bin/log show --last 10m --predicate 'process == "remotepairingd"'
   ```
   Use the full `/usr/bin/log` path (in zsh, `log` is a shell builtin). Look for `Got tunnel endpoint` lines and connection errors.

## Why it's built this way (don't "simplify" these)

- **Bonjour doesn't cross Tailscale.** Xcode discovers network phones via `_remotepairing._tcp` mDNS, so the Mac re-advertises the phone's record (exact instance name and TXT) with a spoofed `.local` hostname resolving to the Mac's own LAN IP.
- **`advertise.c` is used instead of `dns-sd -P`.** `dns-sd -P` advertises on every interface, which causes `remotepairingd` to connect via container/bridge interfaces where the relay isn't listening and fail. `advertise.c` binds the record and service to a single `en*` interface index.
- **The relay follows the tunnel port dynamically.** Many iPhones allocate tunnel ports on a counter wrapping across `49152–65535`. `tunnel_relay.py` listens on `PAIR_PORT` plus the next 160 ports after the last observed tunnel port, tails `/usr/bin/log stream` for `remotepairingd`'s `Got tunnel endpoint '…:PORT'` lines to slide the window, and persists the last port in `last-tunnel-port`.
- **`relay.sh` exits if either child dies.** macOS ships bash 3.2 (no `wait -n`), so a lightweight `kill -0` loop exits as soon as either `advertise` or `tunnel_relay.py` stops, letting `launchd` cleanly restart both together.

---

## Files

### `~/.local/share/iphone-tailnet/advertise.c`

```c
// advertise.c: register a Bonjour service for another host, on one interface only.
// Like `dns-sd -P`, which registers on every interface; remotepairingd then
// connects through whichever interface it heard the record on, so the record
// has to be heard only on the interface whose address the relays listen on.
//
//   advertise <ifname> <instance> <type> <port> <host> <ipv4> [key=value ...]
#include <arpa/inet.h>
#include <dns_sd.h>
#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void reg_cb(DNSServiceRef s, DNSServiceFlags f, DNSServiceErrorType e, const char *n, const char *t,
                   const char *d, void *c) {
    (void)s; (void)f; (void)c;
    if (e) fprintf(stderr, "register failed: %d\n", e);
    else fprintf(stderr, "registered %s.%s%s\n", n, t, d);
}
static void rec_cb(DNSServiceRef s, DNSRecordRef r, DNSServiceFlags f, DNSServiceErrorType e, void *c) {
    (void)s; (void)r; (void)f; (void)c;
    if (e) fprintf(stderr, "address record failed: %d\n", e);
}

int main(int argc, char **argv) {
    if (argc < 7) { fprintf(stderr, "usage: advertise ifname instance type port host ipv4 [k=v ...]\n"); return 2; }
    uint32_t ifi = if_nametoindex(argv[1]);
    if (!ifi) { fprintf(stderr, "no interface %s\n", argv[1]); return 1; }
    struct in_addr a;
    if (inet_pton(AF_INET, argv[6], &a) != 1) { fprintf(stderr, "bad address\n"); return 1; }

    TXTRecordRef txt; TXTRecordCreate(&txt, 0, NULL);
    for (int i = 7; i < argc; i++) {
        char *eq = strchr(argv[i], '=');
        if (!eq) continue;
        *eq = 0;
        TXTRecordSetValue(&txt, argv[i], (uint8_t)strlen(eq + 1), eq + 1);
    }

    DNSServiceRef conn, svc;
    DNSRecordRef rec;
    if (DNSServiceCreateConnection(&conn)) return 1;
    if (DNSServiceRegisterRecord(conn, &rec, kDNSServiceFlagsUnique, ifi, argv[5], kDNSServiceType_A,
                                 kDNSServiceClass_IN, 4, &a, 240, rec_cb, NULL)) { fprintf(stderr, "A record\n"); return 1; }
    svc = conn;
    if (DNSServiceRegister(&svc, kDNSServiceFlagsShareConnection, ifi, argv[2], argv[3], "local", argv[5],
                           htons((uint16_t)atoi(argv[4])), TXTRecordGetLength(&txt), TXTRecordGetBytesPtr(&txt),
                           reg_cb, NULL)) { fprintf(stderr, "register\n"); return 1; }
    for (;;) if (DNSServiceProcessResult(conn)) return 1;
}
```

### `~/.local/share/iphone-tailnet/tunnel_relay.py`

```python
#!/usr/bin/env python3
"""tunnel_relay.py: carry Xcode's connections to an iPhone across the tailnet.

remotepairingd connects to the address the phone advertises (here, this Mac's
LAN address, see advertise.c), first on the pairing port, then on a tunnel
port the phone opens for each connection. Many iPhones hand those out one after
another (64250, 64251, ...), so this keeps listeners open on the next WINDOW
ports after the last one it saw in remotepairingd's log, and moves the window
on as new ones appear. Each connection is forwarded byte for byte to the same
port on the phone's tailnet address; the tunnel itself stays end-to-end TLS.

If the phone's counter has run past the window (after a long time away, say),
the first attempt fails, the log shows the new port, the window moves, and the
next attempt connects. deploy.sh retries once for that reason.

    tunnel_relay.py   # settings from $IPHONE_TAILNET_CONF or ~/.config/iphone-tailnet/device.env
"""

import asyncio
import os
import re
import shlex
import subprocess
import sys
from pathlib import Path

CONF = Path(os.environ.get("IPHONE_TAILNET_CONF", Path.home() / ".config/iphone-tailnet/device.env"))
STATE = CONF.with_name("last-tunnel-port")
WINDOW = 160
LOW, HIGH = 49152, 65535          # the phone's dynamic port range: the counter wraps from HIGH to LOW


def settings():
    env = {}
    for line in CONF.read_text().splitlines():
        line = line.strip()
        if line and not line.startswith("#") and "=" in line:
            k, v = line.split("=", 1)
            parts = shlex.split(v, comments=True)
            env[k.strip()] = parts[0] if parts else ""
    return env


def default_interface():
    out = subprocess.run(["/sbin/route", "-n", "get", "default"], capture_output=True, text=True).stdout
    m = re.search(r"interface:\s*(\S+)", out)
    if m and m.group(1).startswith("en"):
        return m.group(1)
    return "en0"


def bind_address(env):
    ip = (os.environ.get("BIND_IP") or env.get("BIND_IP") or "").strip()
    if ip:
        return ip
    iface = (os.environ.get("BIND_IF") or env.get("BIND_IF") or "").strip() or default_interface()
    out = subprocess.run(["/sbin/ifconfig", iface], capture_output=True, text=True).stdout
    m = re.search(r"inet (\d+\.\d+\.\d+\.\d+)", out)
    if not m:
        sys.exit(f"{iface} has no IPv4 address")
    return m.group(1)


def after(port, n):
    """The n ports after `port`, wrapping as the phone does."""
    span = HIGH - LOW + 1
    return [LOW + (port - LOW + i) % span for i in range(1, n + 1)]


class Relay:
    def __init__(self, local, phone):
        self.local, self.phone = local, phone
        self.servers = {}          # port -> asyncio.Server

    async def pipe(self, reader, writer):
        try:
            while data := await reader.read(65536):
                writer.write(data)
                await writer.drain()
        except (ConnectionError, OSError):
            pass
        finally:
            try:
                writer.close()
            except Exception:
                pass

    def handler(self, port):
        async def handle(r1, w1):
            try:
                r2, w2 = await asyncio.wait_for(asyncio.open_connection(self.phone, port), 15)
            except (OSError, asyncio.TimeoutError) as e:
                print(f"port {port}: phone unreachable ({e})", flush=True)
                w1.close()
                return
            print(f"port {port}: connected", flush=True)
            await asyncio.gather(self.pipe(r1, w2), self.pipe(r2, w1))
        return handle

    async def open(self, port):
        if port in self.servers:
            return
        try:
            self.servers[port] = await asyncio.start_server(self.handler(port), self.local, port, reuse_address=True)
        except OSError as e:          # in use on this Mac: skip it
            print(f"port {port}: can't listen ({e.strerror})", flush=True)

    async def keep(self, ports):
        """Listen on exactly `ports` (plus any connection still open on an old one)."""
        want = set(ports)
        for port in list(self.servers):
            if port not in want:
                self.servers.pop(port).close()
        for port in ports:
            await self.open(port)


async def follow_log(relay, fixed, start):
    await relay.keep(fixed + [start] + after(start, WINDOW))
    print(f"listening on {relay.local}: {', '.join(map(str, fixed))} and {start}+{WINDOW}", flush=True)
    proc = await asyncio.create_subprocess_exec(
        "/usr/bin/log", "stream", "--style", "compact", "--predicate",
        'process == "remotepairingd" AND eventMessage CONTAINS "Got tunnel endpoint"',
        stdout=asyncio.subprocess.PIPE)
    seen = re.compile(r"Got tunnel endpoint: '[^']*:(\d+)'")
    async for line in proc.stdout:
        m = seen.search(line.decode(errors="replace"))
        if m:
            port = int(m.group(1))
            STATE.write_text(str(port))
            print(f"tunnel asked for {port}", flush=True)
            # keep this one open too: it's the connection being made right now
            await relay.keep(fixed + [port] + after(port, WINDOW))
    sys.exit("log stream ended")


async def main():
    s = settings()
    local = bind_address(s)
    relay = Relay(local, s["PHONE_IP"])
    saved = STATE.read_text().strip() if STATE.exists() else ""
    start = int(saved) if saved else int(s.get("TUNNEL_PORT_GUESS") or 64000)
    await follow_log(relay, [int(s["PAIR_PORT"])], start)


if __name__ == "__main__":
    asyncio.run(main())
```

### `~/.local/share/iphone-tailnet/relay.sh`

```bash
#!/bin/bash
# relay.sh: make an iPhone on another network, reachable over Tailscale, look
# local to Xcode, so `xcrun devicectl` can install and launch apps on it.
set -u
CONF="${IPHONE_TAILNET_CONF:-$HOME/.config/iphone-tailnet/device.env}"
# shellcheck disable=SC1090
source "$CONF" || { echo "no $CONF"; exit 1; }
HERE="$(cd "$(dirname "$0")" && pwd)"

if [ -z "${BIND_IF:-}" ]; then
  BIND_IF="$(/sbin/route -n get default 2>/dev/null | /usr/bin/awk '/interface:/ {print $2; exit}')"
  case "$BIND_IF" in
    en*) ;;
    *) BIND_IF="en0" ;;
  esac
fi
MAC_IP="${BIND_IP:-$(/sbin/ifconfig "$BIND_IF" 2>/dev/null | /usr/bin/awk '/inet / {print $2; exit}')}"
[ -n "$MAC_IP" ] || { echo "$BIND_IF has no IPv4 address"; exit 1; }
echo "advertising $INSTANCE as $SPOOF_HOSTNAME on $BIND_IF ($MAC_IP) -> $PHONE_IP"

[ "$HERE/advertise" -nt "$HERE/advertise.c" ] || /usr/bin/clang -O2 -o "$HERE/advertise" "$HERE/advertise.c" || exit 1

pids=()
trap 'kill "${pids[@]}" 2>/dev/null' EXIT
read -r -a txt_args <<< "$PAIR_TXT"
"$HERE/advertise" "$BIND_IF" "$INSTANCE" _remotepairing._tcp "$PAIR_PORT" "$SPOOF_HOSTNAME" "$MAC_IP" "${txt_args[@]}" &
pids+=($!)
IPHONE_TAILNET_CONF="$CONF" BIND_IF="$BIND_IF" BIND_IP="$MAC_IP" /usr/bin/python3 -u "$HERE/tunnel_relay.py" &
pids+=($!)

# Either one ending means the setup is broken: stop, and let launchd restart both.
# (macOS's bash 3.2 has no `wait -n`.)
while kill -0 "${pids[0]}" 2>/dev/null && kill -0 "${pids[1]}" 2>/dev/null; do sleep 5; done
exit 1
```

### `~/.config/iphone-tailnet/device.env` (template)

```bash
# Save to ~/.config/iphone-tailnet/device.env (chmod 600 — PAIR_TXT contains the phone's authTag).
# Capture INSTANCE, PAIR_PORT, and PAIR_TXT from a Mac on the phone's own LAN:
#   dns-sd -B _remotepairing._tcp local.
#   dns-sd -L "<instance>" _remotepairing._tcp local.
PHONE_IP=100.x.y.z                       # the phone's Tailscale IPv4 address
SPOOF_HOSTNAME=iphone-tailnet.local      # any unused .local hostname
INSTANCE="<instance name>"
PAIR_PORT=49152
PAIR_TXT="identifier=<...> authTag=<...> ver=<...> minVer=<...> flags=<...>"
TUNNEL_PORT_GUESS=64000                  # roughly where the phone's tunnel ports are; the relay learns the rest
# Optional: override LAN interface or bind to an IP alias (e.g. for multiple phones)
# BIND_IF=en0
# BIND_IP=192.168.1.200
```

### `~/Library/LaunchAgents/local.iphone-tailnet.plist` (template)

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>local.iphone-tailnet</string>
  <key>ProgramArguments</key>
  <array><string>/bin/bash</string><string>/Users/YOU/.local/share/iphone-tailnet/relay.sh</string></array>
  <!-- Optional: uncomment for additional phones using a separate config file -->
  <!--
  <key>EnvironmentVariables</key>
  <dict>
    <key>IPHONE_TAILNET_CONF</key><string>/Users/YOU/.config/iphone-tailnet/phone2/device.env</string>
  </dict>
  -->
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>30</integer>
  <key>StandardOutPath</key><string>/Users/YOU/.config/iphone-tailnet/relay.log</string>
  <key>StandardErrorPath</key><string>/Users/YOU/.config/iphone-tailnet/relay.log</string>
</dict>
</plist>
```

### `scripts/deploy.sh` (per-project template)

```bash
#!/bin/bash
# deploy.sh: build an iOS app, install it on an iPhone (on LAN or over Tailscale), and launch it.
#
#   scripts/deploy.sh                 # Release build, install, launch
#   scripts/deploy.sh --no-build      # install the last build
#   DEVICE=<udid> scripts/deploy.sh   # target another phone
set -euo pipefail

export DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}"
DEVICE="${DEVICE:-<PHONE_UDID>}"
PROJECT="MyApp.xcodeproj"
SCHEME="MyApp"
BUNDLE="com.example.myapp"
RELAY_LABEL="local.iphone-tailnet"
RELAY_LOG="$HOME/.config/iphone-tailnet/relay.log"

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
APP="$ROOT/build/dd/Build/Products/Release-iphoneos/${SCHEME}.app"
LOG="$ROOT/build/deploy.log"
mkdir -p "$ROOT/build"

if [ "${1:-}" != "--no-build" ]; then
  echo "building…"
  if ! xcodebuild -project "$ROOT/$PROJECT" -scheme "$SCHEME" -configuration Release \
       -destination 'generic/platform=iOS' -derivedDataPath "$ROOT/build/dd" \
       -allowProvisioningUpdates build > "$LOG" 2>&1; then
    grep -E "error:" "$LOG" | head -20
    echo "build failed (full log: $LOG)"
    exit 1
  fi
fi

if ! xcrun devicectl list devices 2>/dev/null | grep "$DEVICE" | grep -qE " (available|connected)"; then
  echo "the phone isn't available: is it on Wi-Fi and Tailscale, and is the relay running?"
  echo "  launchctl print gui/$UID/$RELAY_LABEL | grep state"
  echo "  tail $RELAY_LOG"
  exit 1
fi

install() { xcrun devicectl device install app --device "$DEVICE" "$APP" 2>&1 | grep -E "installationURL|ERROR|error" | head -3; }
echo "installing…"
out="$(install)"
if ! grep -q installationURL <<<"$out"; then
  # Over the tailnet the phone's tunnel port may have moved past the relay's
  # window; the relay has seen the new one now, so a second try connects.
  echo "$out"; echo "retrying…"; sleep 2
  out="$(install)"
  grep -q installationURL <<<"$out" || { echo "$out"; exit 1; }
fi
echo "installed"

if xcrun devicectl device process launch --device "$DEVICE" --terminate-existing "$BUNDLE" > /dev/null 2>&1; then
  echo "launched"
else
  echo "installed but not launched: unlock the phone and run it from the home screen"
fi
```
