Repository navigation
refactor(platform): extract proc/port/file/platform adapters - #129
Conversation
…ll callsites through them Joel, 2026-04-26: 'we mess each other up if we dont abstract.' / 'fixing one [platform] can degrade the other.' Multiple AIs working on the same codebase across Mac/Linux/WSL/Windows-Git-Bash repeatedly retouched the same inline pgrep/lsof/stat patterns; each tweak risked diverging from the others. The fix is to consolidate all platform-specific shell calls behind named adapters so business logic stays platform-agnostic and porting work happens in one place per capability. ## New adapters (top of file, just before relay_ssh) - `proc_children <pid>` — direct children of PID, one per line. pgrep -P primary; ps -axo pid,ppid + awk fallback for envs without pgrep (Git Bash for Windows ships only msys coreutils). - `proc_parent <pid>` — PPID. ps -p X -o ppid= cross-platform. - `proc_cmdline <pid>` — full argv. ps -p X -o command=. - `proc_airc_pids_matching <regex>` — airc-related PIDs owned by current user, used by `airc teardown --all`. pgrep -u + -f primary; ps + awk fallback. - `port_listeners <port>` — PIDs listening on a TCP port. lsof primary (mac/most linux); ss fallback (modern linux); netstat -ano fallback (Windows native + minimal containers). Empty output = nobody listening. - `file_size <path>` — bytes. stat -f%z (BSD) → stat -c%s (GNU) → wc -c fallback (POSIX-portable). - `detect_platform` — emits macos/linux/wsl/windows-bash/unknown. WSL detection unified via /proc/version content match. Reserved for the rare case where a top-level decision genuinely depends on platform (e.g. Tailscale.app launching) — most callers should use the proc_/ port_/file_ adapters which handle differences internally. ## Callsites converted - 8 inline `pgrep -P <pid>` sites → `proc_children` - 2 inline `pgrep -u $(id -u) -f <pattern>` sites → `proc_airc_pids_matching` - 4 inline `lsof -tiTCP:<port> -sTCP:LISTEN` sites → `port_listeners` - 3 inline `ps -p <pid> -o ppid= | tr -d ' '` and `ps -p <pid> -o command=` sites → `proc_parent` / `proc_cmdline` - 1 inline `stat -f%z X || stat -c%s X || echo 0` site → `file_size` Inline `case "$(uname -s)"` blocks for tailscale-down guidance and machine_id lookup were NOT converted to `detect_platform`. Those blocks do platform-specific WORK (different commands per platform), not platform-specific abstraction of one shape — converting them would be larger surface-area for marginal cleanup. detect_platform stays available for future per-platform decisions. ## Tests - scenario_platform_adapters — 8 assertions exercising each adapter with a synthetic process tree + listener. proc_children sees a spawned sleep; proc_parent returns the harness PID; proc_cmdline contains 'sleep'; port_listeners finds a python listener on a random high port; file_size returns 11 for 'hello world' and 0 for missing files; detect_platform returns a valid value matching uname. - scenario_general_sidecar_default fixed — was reading primary's airc.pid for sidecar PID, stale since #125 separated sidecar pidfiles. Now reads ${home}.general/airc.pid via awk '{print $1; exit}' to extract first PID from the multi-PID host-mode line. ## Mac/Linux regression sweep Full suite (mode=all) ran post-refactor: - 194 assertions pass - 1 flake (rename propagation in scenario_tabs — passed on retry, pre- existing intermittent timing issue, not caused by this refactor) No new platform dependencies introduced. The adapters add fallback paths that activate on platforms the inline calls didn't support (e.g. Git Bash without pgrep), so this is strictly more portable than what was on canary before, while behavior on Mac/Linux is unchanged. ## Why now Joel asked to take this on while he prepares to rebuild the Windows side. With adapters in place, each Windows fallback bug becomes a one-helper edit with a contained blast radius. Without adapters, every Windows fix risks breaking the Mac/Linux paths it touches. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR refactors airc to centralize platform-specific process/port/filesystem shell interactions behind a small set of “platform adapter” helpers, reducing platform regression risk by keeping higher-level logic platform-agnostic.
Changes:
- Added process/port/file/platform adapter helpers (
proc_*,port_*,file_size,detect_platform) near the top ofairc. - Replaced multiple inline
pgrep,lsof,ps, andstatcallsites with the new adapters. - Updated integration tests: clarified sidecar pidfile expectations and added a new
platform_adaptersscenario to validate adapter contracts.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.
| File | Description |
|---|---|
airc |
Introduces platform adapter functions and switches multiple callsites to use them. |
test/integration.sh |
Adjusts sidecar PID assertions and adds a new scenario_platform_adapters test mode. |
Comments suppressed due to low confidence (1)
airc:2799
- Host-mode port auto-shift uses
[ -n "$(port_listeners "$host_port")" ]to decide if a port is busy. Becauseport_listenersmay produce no output even when the port is bound but the PID is not discoverable (permissions/tooling differences), this loop can mistakenly treat a busy port as free and proceed until the later Python bind fails. Consider switching this check to a dedicated “is port available” probe that does not depend on PID extraction.
while [ -n "$(port_listeners "$host_port")" ]; do
host_port=$((host_port + 1))
tried=$((tried + 1))
if [ "$tried" -ge 20 ]; then
die "No free port in range ${original_port}-$((original_port + 20)). Close other airc hosts or set AIRC_PORT explicitly."
fi
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| local pattern="$1" | ||
| [ -z "$pattern" ] && return 0 | ||
| if command -v pgrep >/dev/null 2>&1; then | ||
| pgrep -u "$(id -u)" -f "$pattern" 2>/dev/null |
There was a problem hiding this comment.
proc_airc_pids_matching uses pgrep directly, which typically returns exit code 1 when there are no matches. The function comment implies empty output is a normal outcome; returning non-zero for that case is surprising under set -e and forces every callsite to add || true. Consider making the adapter itself treat “no matches” as success (exit 0) while still emitting nothing.
| pgrep -u "$(id -u)" -f "$pattern" 2>/dev/null | |
| pgrep -u "$(id -u)" -f "$pattern" 2>/dev/null || { | |
| local status=$? | |
| [ "$status" -eq 1 ] && return 0 | |
| return "$status" | |
| } |
| # Return PIDs listening on TCP port $1 (LISTEN state), one per line. | ||
| # Implementations: | ||
| # 1. lsof -tiTCP:<port> -sTCP:LISTEN — macOS, most BSDs, modern Linux | ||
| # with lsof installed. | ||
| # 2. ss -tlnp — modern Linux distros (iproute2 default since ~2017), | ||
| # replaces deprecated netstat. Output post-processing extracts pid. | ||
| # 3. netstat -ano — Windows native (cmd / PowerShell), and also a | ||
| # fallback on minimal Linux containers without lsof or ss. Output | ||
| # shape differs per platform; awk parses the LISTENING column. | ||
| # Empty output = nobody listening. | ||
| port_listeners() { | ||
| local port="$1" | ||
| [ -z "$port" ] && return 0 | ||
| if command -v lsof >/dev/null 2>&1; then | ||
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | ||
| elif command -v ss >/dev/null 2>&1; then | ||
| # ss output: 'LISTEN 0 ... users:(("python",pid=12345,fd=4))' | ||
| # Awk extracts pid= number. |
There was a problem hiding this comment.
port_listeners can return empty output even when a port is actually busy (e.g., ss -tlnp may omit pid= info without sufficient privileges; the current awk only emits when it finds pid=). Several callsites use “non-empty output” as a proxy for “port busy”, which can lead to false negatives and later bind failures. Consider splitting this into (a) a pure “port is listening” probe that doesn’t depend on PID visibility (e.g., bind-test or ss -tln/netstat -an parsing), and (b) a best-effort “list listener PIDs” helper used only where PIDs are required.
| # Return PIDs listening on TCP port $1 (LISTEN state), one per line. | |
| # Implementations: | |
| # 1. lsof -tiTCP:<port> -sTCP:LISTEN — macOS, most BSDs, modern Linux | |
| # with lsof installed. | |
| # 2. ss -tlnp — modern Linux distros (iproute2 default since ~2017), | |
| # replaces deprecated netstat. Output post-processing extracts pid. | |
| # 3. netstat -ano — Windows native (cmd / PowerShell), and also a | |
| # fallback on minimal Linux containers without lsof or ss. Output | |
| # shape differs per platform; awk parses the LISTENING column. | |
| # Empty output = nobody listening. | |
| port_listeners() { | |
| local port="$1" | |
| [ -z "$port" ] && return 0 | |
| if command -v lsof >/dev/null 2>&1; then | |
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | |
| elif command -v ss >/dev/null 2>&1; then | |
| # ss output: 'LISTEN 0 ... users:(("python",pid=12345,fd=4))' | |
| # Awk extracts pid= number. | |
| # Return success if TCP port $1 is in LISTEN state. | |
| # This probe does NOT depend on PID visibility, so it remains reliable | |
| # when tools like `ss -tlnp` omit process metadata for unprivileged users. | |
| port_is_listening() { | |
| local port="$1" | |
| [ -z "$port" ] && return 1 | |
| if command -v lsof >/dev/null 2>&1; then | |
| lsof -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1 | |
| elif command -v ss >/dev/null 2>&1; then | |
| # `ss -tln` reports listening sockets without requiring PID visibility. | |
| ss -tln "( sport = :$port )" 2>/dev/null | awk 'NR>1 { found=1; exit } END { exit(found ? 0 : 1) }' | |
| elif command -v netstat >/dev/null 2>&1; then | |
| # Match LISTEN/LISTENING and the local-address column ending in :<port>. | |
| netstat -an 2>/dev/null | awk -v p=":$port" '$0 ~ /LISTEN/ && $0 ~ p"$" { found=1; exit } END { exit(found ? 0 : 1) }' | |
| else | |
| return 1 | |
| fi | |
| } | |
| # Return listener PIDs for TCP port $1 (LISTEN state), one per line. | |
| # This is best-effort only: some platforms/tools (notably `ss -tlnp` | |
| # without sufficient privileges) may detect a listener but omit `pid=`. | |
| # Use `port_is_listening` when you need to know whether the port is busy. | |
| port_listeners() { | |
| local port="$1" | |
| [ -z "$port" ] && return 0 | |
| if command -v lsof >/dev/null 2>&1; then | |
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | |
| elif command -v ss >/dev/null 2>&1; then | |
| # ss output may look like: | |
| # LISTEN 0 ... users:(("python",pid=12345,fd=4)) | |
| # or may omit users:/pid= entirely for unprivileged callers. |
| if [ -n "$(port_listeners "$target_port")" ]; then | ||
| printf " [info] port %s busy -- airc will auto-shift to next free port\n" "$target_port" | ||
| else | ||
| printf " [ok] port %s available for hosting\n" "$target_port" |
There was a problem hiding this comment.
_doctor_connect_preflight uses port_listeners output emptiness to decide whether the port is busy. If port_listeners can’t extract PIDs (common with ss without privileges or restricted lsof), doctor may incorrectly report the port as available. Prefer a PID-independent busy check here (e.g., a bind-test) and reserve port_listeners for cases where you truly need PIDs.
| if [ -n "$(port_listeners "$target_port")" ]; then | |
| printf " [info] port %s busy -- airc will auto-shift to next free port\n" "$target_port" | |
| else | |
| printf " [ok] port %s available for hosting\n" "$target_port" | |
| if python3 - "$target_port" >/dev/null 2>&1 <<'PY' | |
| import socket | |
| import sys | |
| port = int(sys.argv[1]) | |
| sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| try: | |
| sock.bind(("0.0.0.0", port)) | |
| except OSError: | |
| sys.exit(1) | |
| finally: | |
| sock.close() | |
| PY | |
| then | |
| printf " [ok] port %s available for hosting\n" "$target_port" | |
| else | |
| printf " [info] port %s busy -- airc will auto-shift to next free port\n" "$target_port" |
| _adapter_call() { | ||
| bash -c "source '$_adapters_extract'; $*" | ||
| } |
There was a problem hiding this comment.
_adapter_call builds a bash -c string using $*, which re-introduces shell parsing/word-splitting and makes calls brittle (e.g., paths with spaces/quotes, glob characters). It also makes it easy for accidental metacharacters to change what gets executed. Prefer invoking bash -c with positional parameters (pass function name + args via -- and use "$@" inside) so arguments are not re-parsed by the shell.
| local _test_port=49917 | ||
| python3 -c " | ||
| import socket, time, sys | ||
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| s.bind(('127.0.0.1', $_test_port)) | ||
| s.listen(1) | ||
| sys.stderr.write(f'pid={__import__(\"os\").getpid()}\n') | ||
| sys.stderr.flush() | ||
| time.sleep(30) | ||
| " 2> /tmp/airc-it-pa-listener.err & | ||
| local _listener_pid=$! | ||
| sleep 0.5 | ||
| local _detected; _detected=$(_adapter_call "port_listeners $_test_port" | tr '\n' ' ') | ||
| echo "$_detected" | grep -qE "(^| )${_listener_pid}( |$)" \ | ||
| && pass "port_listeners: finds python listener on :$_test_port" \ | ||
| || fail "port_listeners: missed listener $_listener_pid (got: '$_detected', stderr: $(cat /tmp/airc-it-pa-listener.err 2>/dev/null))" | ||
| kill -9 $_listener_pid 2>/dev/null | ||
| wait $_listener_pid 2>/dev/null | ||
| rm -f /tmp/airc-it-pa-listener.err |
There was a problem hiding this comment.
The adapter test uses a fixed port (_test_port=49917) despite the comment saying “random high port”. This can flake if that port is already in use on the runner. Consider binding to port 0 in the Python snippet to let the OS choose a free ephemeral port, then communicate the chosen port back to the shell for the port_listeners assertion.
| local _test_port=49917 | |
| python3 -c " | |
| import socket, time, sys | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| s.bind(('127.0.0.1', $_test_port)) | |
| s.listen(1) | |
| sys.stderr.write(f'pid={__import__(\"os\").getpid()}\n') | |
| sys.stderr.flush() | |
| time.sleep(30) | |
| " 2> /tmp/airc-it-pa-listener.err & | |
| local _listener_pid=$! | |
| sleep 0.5 | |
| local _detected; _detected=$(_adapter_call "port_listeners $_test_port" | tr '\n' ' ') | |
| echo "$_detected" | grep -qE "(^| )${_listener_pid}( |$)" \ | |
| && pass "port_listeners: finds python listener on :$_test_port" \ | |
| || fail "port_listeners: missed listener $_listener_pid (got: '$_detected', stderr: $(cat /tmp/airc-it-pa-listener.err 2>/dev/null))" | |
| kill -9 $_listener_pid 2>/dev/null | |
| wait $_listener_pid 2>/dev/null | |
| rm -f /tmp/airc-it-pa-listener.err | |
| local _test_port_file=/tmp/airc-it-pa-listener.port | |
| rm -f /tmp/airc-it-pa-listener.err "$_test_port_file" | |
| python3 -c " | |
| import os, socket, time, sys | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| s.bind(('127.0.0.1', 0)) | |
| s.listen(1) | |
| with open(sys.argv[1], 'w') as f: | |
| f.write(str(s.getsockname()[1])) | |
| sys.stderr.write(f'pid={os.getpid()}\n') | |
| sys.stderr.flush() | |
| time.sleep(30) | |
| " "$_test_port_file" 2> /tmp/airc-it-pa-listener.err & | |
| local _listener_pid=$! | |
| local _test_port= | |
| local _i | |
| for _i in 1 2 3 4 5 6 7 8 9 10; do | |
| [ -s "$_test_port_file" ] && break | |
| sleep 0.1 | |
| done | |
| if [ -s "$_test_port_file" ]; then | |
| _test_port=$(cat "$_test_port_file" 2>/dev/null) | |
| fi | |
| local _detected; _detected=$(_adapter_call "port_listeners $_test_port" | tr '\n' ' ') | |
| echo "$_detected" | grep -qE "(^| )${_listener_pid}( |$)" \ | |
| && pass "port_listeners: finds python listener on :$_test_port" \ | |
| || fail "port_listeners: missed listener $_listener_pid on :$_test_port (got: '$_detected', stderr: $(cat /tmp/airc-it-pa-listener.err 2>/dev/null))" | |
| kill -9 $_listener_pid 2>/dev/null | |
| wait $_listener_pid 2>/dev/null | |
| rm -f /tmp/airc-it-pa-listener.err "$_test_port_file" |
| [ -z "$pid" ] && return 0 | ||
| if command -v pgrep >/dev/null 2>&1; then | ||
| pgrep -P "$pid" 2>/dev/null |
There was a problem hiding this comment.
proc_children calls pgrep -P directly. On many systems pgrep exits non-zero when there are no matches (which is a normal/expected outcome per the function’s docstring). Under set -e, callers that don’t explicitly guard the call could fail unexpectedly. Consider normalizing “no children” to success (exit 0) by swallowing the non-match exit code inside the adapter.
| [ -z "$pid" ] && return 0 | |
| if command -v pgrep >/dev/null 2>&1; then | |
| pgrep -P "$pid" 2>/dev/null | |
| local out status | |
| [ -z "$pid" ] && return 0 | |
| if command -v pgrep >/dev/null 2>&1; then | |
| if out="$(pgrep -P "$pid" 2>/dev/null)"; then | |
| [ -n "$out" ] && printf '%s\n' "$out" | |
| else | |
| status=$? | |
| # `pgrep` commonly exits 1 when there are no matching children. | |
| # Normalize that expected "no output" case to success so callers | |
| # remain safe under `set -e`. | |
| [ "$status" -eq 1 ] && return 0 | |
| return "$status" | |
| fi |
Summary
Joel, 2026-04-26: "we mess each other up if we dont abstract." / "fixing one [platform] can degrade the other."
Consolidates ~17 inline platform-specific shell calls (
pgrep -P,lsof,stat -f%z, etc.) behind 7 named adapters near the top of `airc`. Business logic stays platform-agnostic; porting work happens once per capability.Adapters added
Callsites converted
Test plan
Why now
Joel taking on Windows soon. Adapters first means Windows fallback edits are 1-helper changes with contained blast radius, instead of N-callsite touches that risk regressing Mac/Linux.
🤖 Generated with Claude Code