Use Apple container system API for resident network recovery - #48
Conversation
Signed-off-by: Joseph Yaksich <gitcommit90@users.noreply.github.com>
📝 WalkthroughWalkthroughApple guest network recovery now defers during active work and restarts networking through Apple container ChangesApple network recovery
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/server/channel-computers.ts`:
- Around line 600-602: Update the Apple service recovery flow around the stopped
and started commands to validate stopped.code immediately after the system stop
call, throwing with stopped.stderr on failure before invoking system start. Only
call system start after a successful stop, and retain started.stderr for
reporting start failures.
- Around line 595-599: Update the repair guard around activeCommands,
activeTurns, and terminalSessions to receive the current operation identity and
exclude only that operation from each activity check. Block repair whenever any
other command, running turn, or terminal session is active, including mixed
command-and-turn work and the terminal being repaired before it is registered in
terminalSessions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: db6641db-03e5-4206-8299-082d87599dc1
📒 Files selected for processing (3)
src/server/channel-computers.tstest/channel-computers.mjstest/fake-container.mjs
| const activeCommands = Number(q1("SELECT COUNT(*) n FROM channel_computer_obligations WHERE kind='command' AND status='active'")?.n || 0); | ||
| const activeTurns = Number(q1("SELECT COUNT(*) n FROM agent_turns WHERE state='running'")?.n || 0); | ||
| if (terminalSessions.size > 0 || activeCommands > 1 || activeTurns > 1) { | ||
| throw new Error("resident computer network is unavailable; automatic repair is waiting for concurrent work to finish"); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 12 \
-e 'repairAppleGuestNetwork\s*\(' \
-e 'channel_computer_obligations' \
-e 'agent_turns' \
-e 'terminalSessions\.(add|set|delete)' \
src/serverRepository: gitcommit90/1Helm
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- repair function and surrounding state ---'
sed -n '1,120p;560,630p;800,870p;900,1015p;1280,1330p;1490,1555p' src/server/channel-computers.ts
printf '%s\n' '--- command obligation call sites ---'
rg -n -C 5 'upsertObligation\([^;]*command|satisfyObligation\([^;]*command|kind[[:space:]]*=[[:space:]]*["'\'']command|["'\'']command["'\'']' src/server --glob '*.ts'
printf '%s\n' '--- running-turn creation and lifecycle call sites ---'
rg -n -C 5 'INSERT INTO agent_turns|claimAgentTurn|finalizeAgentTurn|state=.running.|state=.queued.' src/server --glob '*.ts'
printf '%s\n' '--- terminal session lifecycle ---'
rg -n -C 5 'terminalSessions\.(set|delete)|repairAppleGuestNetwork|ensureChannelComputerRunning' src/server/channel-computers.tsRepository: gitcommit90/1Helm
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- agent-turn creation and command-tool path ---'
rg -n -C 8 \
-e 'INSERT INTO agent_turns' \
-e 'claimAgentTurn\(' \
-e 'runChannelCommand\(' \
-e 'execute.*tool|tool.*execute|computer_command|command' \
src/server/turns.ts src/server/bots.ts src/server --glob '*.ts' \
| head -n 500
printf '%s\n' '--- exact guard predicates ---'
python3 - <<'PY'
from pathlib import Path
p = Path("src/server/channel-computers.ts").read_text()
start = p.index("async function repairAppleGuestNetwork")
end = p.index("const isolatedBackend", start)
print(p[start:end])
PY
printf '%s\n' '--- deterministic mixed-work verifier ---'
python3 - <<'PY'
def global_allows(terminals, commands, turns):
return not (terminals > 0 or commands > 1 or turns > 1)
def channel_allows(channel_terminals, channel_commands, channel_turns):
return not (channel_terminals or channel_commands > 1 or channel_turns > 1)
cases = [
("current command + unrelated turn, global", global_allows(0, 1, 1)),
("current command + unrelated turn, same channel", channel_allows(False, 1, 1)),
("two commands", global_allows(0, 2, 0)),
("two turns", global_allows(0, 0, 2)),
]
for name, allowed in cases:
print(f"{name}: {'ALLOWS_RESTART' if allowed else 'BLOCKS_RESTART'}")
PYRepository: gitcommit90/1Helm
Length of output: 46275
Block mixed work types during Apple network repair.
The global and per-channel guards apply > 1 independently, so one active command and one active turn can pass together. A new terminal is not added to terminalSessions until after ensureChannelComputerRunning, so an active command can also coexist with that terminal's repair. Pass the current operation identity into both checks and block when any other command, running turn, or terminal session is active.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/server/channel-computers.ts` around lines 595 - 599, Update the repair
guard around activeCommands, activeTurns, and terminalSessions to receive the
current operation identity and exclude only that operation from each activity
check. Block repair whenever any other command, running turn, or terminal
session is active, including mixed command-and-turn work and the terminal being
repaired before it is registered in terminalSessions.
| const stopped = await apple(["system", "stop"], { timeoutMs: 90_000 }); | ||
| const started = await apple(["system", "start"], { timeoutMs: 90_000 }); | ||
| if (stopped.code !== 0) throw new Error(stopped.stderr.toString("utf8").trim() || "Apple container services could not stop for network recovery"); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- candidate file map ---'
ast-grep outline src/server/channel-computers.ts
printf '%s\n' '--- target implementation ---'
sed -n '540,635p' src/server/channel-computers.ts
printf '%s\n' '--- related symbols and call sites ---'
rg -n -C 3 'repairAppleGuestNetwork|active commands|agent turns|system stop|system start' srcRepository: gitcommit90/1Helm
Length of output: 25506
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- lock and activity state ---'
sed -n '88,145p' src/server/channel-computers.ts
printf '%s\n' '--- command and turn admission paths ---'
rg -n -C 5 'channel_computer_obligations|kind=.command|status=.active|agent_turns|state=.running|withChannelLock|canStopChannelComputer' src/server
printf '%s\n' '--- stop/restart callers ---'
sed -n '820,875p' src/server/channel-computers.ts
sed -n '1348,1385p' src/server/channel-computers.ts
sed -n '1488,1550p' src/server/channel-computers.tsRepository: gitcommit90/1Helm
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
import re
path = Path("src/server/channel-computers.ts")
text = path.read_text()
start = text.index("async function repairAppleGuestNetwork")
end = text.index("\nconst isolatedBackend", start)
body = text[start:end]
lines = body.splitlines()
stop = next(i for i, line in enumerate(lines) if 'apple(["system", "stop"]' in line)
start_cmd = next(i for i, line in enumerate(lines) if 'apple(["system", "start"]' in line)
stop_check = next(i for i, line in enumerate(lines) if "stopped.code !== 0" in line)
start_check = next(i for i, line in enumerate(lines) if "started.code !== 0" in line)
print({
"system_stop_relative_line": stop + 1,
"system_start_relative_line": start_cmd + 1,
"stop_check_relative_line": stop_check + 1,
"start_check_relative_line": start_check + 1,
"start_precedes_stop_check": start_cmd < stop_check,
"start_failure_message_uses_stopped_stderr": "started.code !== 0" in lines[start_check]
and "stopped.stderr" in lines[start_check],
})
# Read-only control-flow probe for the relevant sequence.
events = []
stopped_code = 1
events.append("system stop")
if True: # current source invokes start before evaluating stopped.code
events.append("system start")
if stopped_code != 0:
events.append("throw stop error")
print({"stop_failure_event_order": events})
PY
printf '%s\n' '--- Apple container CLI references in repository ---'
rg -n -i -C 2 'container (system|service)|system (start|stop)|vmnet' README.md docs src package.json 2>/dev/null || trueRepository: gitcommit90/1Helm
Length of output: 2180
🌐 Web query:
Apple container CLI 1.1.0 container system stop container system start semantics
💡 Result:
In the Apple container CLI version 1.1.0, the container system commands manage the lifecycle of the core background services required for the platform to function [1]. container system start This command initializes the container platform's services, specifically launching the container-apiserver (a launch agent) [1]. Starting these services is a prerequisite for creating and managing containers [2][3]. When executed, it also creates a vmnet network named default to which containers will attach by default [4]. container system stop This command terminates the container services and deregisters them from launchd [5][6]. Running this command stops the container-apiserver, effectively shutting down the background infrastructure [1]. Users are typically instructed to run this command when they need to fully stop the platform or perform system-level tasks such as upgrades or downgrades [2][7][8]. Summary of Semantics - System Lifecycle: The container system commands control the global state of the background API server and associated helpers, rather than the state of individual user containers [1]. - Persistence: Individual containers are managed via container stop and container start [2]. While stopping the system service shuts down the platform, individual container states may not always be gracefully persisted or updated in the CLI's view if the system is interrupted unexpectedly; users are advised to manually stop containers if necessary before performing maintenance [9]. - Configuration: Both commands support a --prefix option (defaulting to com.apple.container.), which allows users to target specific service instances managed by launchd [5][6].
Citations:
- 1: https://github.com/apple/container/blob/main/docs/technical-overview.md
- 2: https://github.com/apple/container/blob/main/docs/tutorials/start-here.md
- 3: https://github.com/apple/container
- 4: https://github.com/apple/container/blob/1.1.0/docs/how-to.md
- 5: https://github.com/apple/container/blob/main/docs/command-reference.md
- 6: https://github.com/apple/container/blob/69fd9484/docs/command-reference.md
- 7: https://github.com/apple/container?tab=readme-ov-file
- 8: https://github.com/apple/container/blob/main/README.md
- 9: [Bug]: container system restart is causing an abnormal state apple/container#175
🏁 Script executed:
#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
path = Path("src/server/channel-computers.ts")
text = path.read_text()
start = text.index("async function repairAppleGuestNetwork")
end = text.index("\nconst isolatedBackend", start)
lines = text[start:end].splitlines()
stop = next(i for i, line in enumerate(lines) if 'apple(["system", "stop"]' in line)
start_cmd = next(i for i, line in enumerate(lines) if 'apple(["system", "start"]' in line)
stop_check = next(i for i, line in enumerate(lines) if "stopped.code !== 0" in line)
start_check = next(i for i, line in enumerate(lines) if "started.code !== 0" in line)
print({
"system_stop_relative_line": stop + 1,
"system_start_relative_line": start_cmd + 1,
"stop_check_relative_line": stop_check + 1,
"start_check_relative_line": start_check + 1,
"start_precedes_stop_check": start_cmd < stop_check,
"start_failure_message_uses_stopped_stderr": "started.code !== 0" in lines[start_check]
and "stopped.stderr" in lines[start_check],
})
events = []
stopped_code = 1
events.append("system stop")
events.append("system start")
if stopped_code != 0:
events.append("throw stop error")
print({"stop_failure_event_order": events})
PY
printf '%s\n' '--- Apple container CLI references in repository ---'
rg -n -i -C 2 'container (system|service)|system (start|stop)|vmnet' README.md docs src package.json 2>/dev/null || trueRepository: gitcommit90/1Helm
Length of output: 2180
Check stopped.code before calling system start.
system start executes even when system stop fails. Throw on a failed stop immediately, then start services only after a successful stop. Preserve started.stderr for the start failure message.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/server/channel-computers.ts` around lines 600 - 602, Update the Apple
service recovery flow around the stopped and started commands to validate
stopped.code immediately after the system stop call, throwing with
stopped.stderr on failure before invoking system start. Only call system start
after a successful stop, and retain started.stderr for reporting start failures.
The real Mac release gate proved Apple's plugin launch service is not addressable through launchctl. Network recovery now uses the supported
container system stop/startAPI and refuses a shared-runtime bounce while other resident work is active.Verified:
node --test test/channel-computers.mjsnpm run typecheckgit diff --checkSummary by CodeRabbit