# Recover a Crashed App in Remote Mac Automation

Canonical: https://figment.so/blog/mac-agent-app-crash-recovery

Restart a crashed app only on failed exits, cap the relaunches, and resume from a checkpoint. A launchd KeepAlive policy plus a counting wrapper does it on a Figment Intel Mac VM ($25 a month).

Recover a crashed automation app with a bounded relaunch workflow: restart only on failed exits, cap the number of retries, and resume from a checkpoint instead of starting over. A crash stops the job and wipes the app's in-memory state, and a naive restart-on-crash loop spins through the same fault and exhausts your API quota before anyone notices. The setup below runs on a Figment Intel Mac VM ($25 a month) for most agents.

## Which Figment plan fits this job?

For a single headless agent that drives a web API, orchestrates scripts, or runs a GUI tool with an Intel-compatible build, the [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, $2 a day, $0.15 an hour) is enough. It has 4 shared vCPUs, 4GB of RAM and an 80GB SSD, runs macOS Sequoia, and works with Intel Mac toolchains including Xcode 26.0 to 26.3. You reach it over SSH or encrypted remote desktop, so the recovery script can run in a terminal session and connect outbound to your own services.

Choose an Apple silicon plan when the app needs it:

- **[Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm)** ($39 a month, $6 a day): the app ships arm64-only binaries, uses Apple-silicon-only frameworks, or needs Xcode 26.4 or later. It has 4 shared vCPUs and 4GB of RAM.
- **[Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro)** ($349 a month, or $299 a month on a 12-month term): a heavy GUI app that crashes under memory pressure on 4GB, or work that should not share hardware (M4 Pro, 48GB RAM, 512GB SSD).

Figment runs the Mac and network layer and fixes infrastructure faults. The restart policy, the app and its monitoring are yours to operate.

## What do I need to collect first?

Gather these inputs and decide the agent type before writing any plist.

| Input | Where to find it |
|---|---|
| Full path to the app binary | `which myapp`, or inside the `.app` bundle at `Contents/MacOS/` |
| Working directory | Your project root on the Mac |
| Checkpoint file path | App config, or an environment variable you control |
| Log directory | Any path writable by the agent user |
| Relaunch ceiling | Integer matching your retry budget (e.g. `5`) |

**LaunchAgent or LaunchDaemon?** If the app needs a user desktop session (menus, windows, or user-session Keychain access), install it as a LaunchAgent under `~/Library/LaunchAgents/`. If it is fully headless and must start before any login, use a LaunchDaemon under `/Library/LaunchDaemons/`. Most remote automation workflows belong in a LaunchAgent. The plist must be owned by the invoking user (or root for a daemon) and must not be group- or world-writable. Apple's [Creating Launch Daemons and Agents](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) is the authoritative reference.

## How do I restart only on failure, with a pause between restarts?

Use a launchd plist with `KeepAlive` set to `SuccessfulExit: false` and a `ThrottleInterval`. The design pairs launchd's restart machinery with a thin wrapper that tracks retries and arms the checkpoint resume flag.

```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>com.yourorg.automation-agent</string>

    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/agent-wrapper</string>
    </array>

    <key>WorkingDirectory</key>
    <string>/Users/agent/workdir</string>

    <!-- Restart whenever the wrapper exits non-zero. The wrapper uses
         exit 0 to stop the cycle (clean run OR retry ceiling hit). -->
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>

    <!-- 30 s floor between restarts; launchd's default is 10 s. -->
    <key>ThrottleInterval</key>
    <integer>30</integer>

    <key>RunAtLoad</key>
    <true/>

    <key>StandardOutPath</key>
    <string>/Users/agent/logs/agent.out.log</string>

    <key>StandardErrorPath</key>
    <string>/Users/agent/logs/agent.err.log</string>
</dict>
</plist>
```

`KeepAlive` with `SuccessfulExit: false` tells launchd to restart the job whenever the wrapper exits with a non-zero status. That includes the 128+N exit code bash returns when its foreground child is killed by SIGSEGV, SIGILL or SIGABRT. An explicit `exit 0` from the wrapper ends the cycle. `ThrottleInterval` enforces a 30-second floor between spawns. The documented default in the [launchd.plist(5) reference](https://keith.github.io/xcode-man-pages/launchd.plist.5.html) is 10 seconds, which is still tight for a stubborn fault.

`KeepAlive.Crashed: true` is deliberately not used. When the wrapper runs the app as a child and the child dies by signal, bash itself exits normally with code 128+N, so launchd sees a non-zero exit, not a signal termination of its tracked process. `SuccessfulExit: false` catches both the child-signal and regular-error paths.

## How do I count relaunches and pass the checkpoint?

Run the app from a wrapper script that keeps a counter file and stops cleanly when the ceiling is reached.

```bash
#!/usr/bin/env bash
# /usr/local/bin/agent-wrapper
# Enforces a relaunch ceiling; passes checkpoint path to the app.
set -uo pipefail

MAX_RELAUNCHES=5
COUNT_FILE="/Users/agent/workdir/.relaunch_count"
CHECKPOINT="/Users/agent/workdir/checkpoint.json"
APP="/Applications/AutomationApp.app/Contents/MacOS/AutomationApp"

count=0
[[ -f "$COUNT_FILE" ]] && count=$(< "$COUNT_FILE")

if (( count >= MAX_RELAUNCHES )); then
    echo "$(date -u +%FT%TZ) FATAL: relaunch limit $MAX_RELAUNCHES reached. Stopping." >&2
    exit 0   # clean exit prevents launchd from restarting again
fi

printf '%d\n' $(( count + 1 )) > "$COUNT_FILE"
echo "$(date -u +%FT%TZ) Launch attempt $(( count + 1 ))/$MAX_RELAUNCHES"

"$APP" --resume-from "$CHECKPOINT"
EXIT_CODE=$?

if [[ $EXIT_CODE -eq 0 ]]; then
    rm -f "$COUNT_FILE"   # reset so the next scheduled run starts clean
    exit 0
fi

exit "$EXIT_CODE"
```

The counter file survives restarts because launchd restarts the wrapper, not the filesystem. On a fully successful run the wrapper clears the counter, so the next scheduled execution starts at zero. If your app does not accept `--resume-from`, substitute whatever it uses to skip completed work: a marker file, a database row, or a `--start-at-step N` argument.

## How do I verify the restart, the ceiling and the checkpoint?

Run three checks after `launchctl load ~/Library/LaunchAgents/com.yourorg.automation-agent.plist`, before you trust the workflow.

**Check 1: the restart fires after a non-zero wrapper exit.**
```bash
pid=$(launchctl list | awk '/automation-agent/ {print $1}')
[[ -z "$pid" || "$pid" == "-" ]] && { echo "FAIL: wrapper not running"; exit 1; }
kill -TERM "$pid"
sleep 35
new_pid=$(launchctl list | awk '/automation-agent/ {print $1}')
[[ -n "$new_pid" && "$new_pid" != "-" && "$new_pid" != "$pid" ]] \
    && echo "PASS: new PID $new_pid" || echo "FAIL: no restart"
```
The first column of `launchctl list` is the PID (or `-` when not running) and the second is the last exit status. Match against your installed `launchctl help` output, since fields have shifted between macOS versions.

**Check 2: the ceiling stops the loop.** Set `MAX_RELAUNCHES=2`, replace `$APP` with `/bin/false` (always exits non-zero), reload the plist, and watch the logs. The third invocation should print the FATAL line and exit 0, and launchd should then leave the job idle. Confirm with `launchctl list | grep automation-agent`: the job is still registered but shows no running PID.

**Check 3: the checkpoint actually resumes.** Hand-craft a `checkpoint.json` with two tasks complete and two pending. Start the app with `--resume-from` and confirm the log shows it skipping the completed items and running only the two pending ones. This exercises your app's idempotency, not launchd.

Follow the logs from an SSH session:
```bash
tail -f /Users/agent/logs/agent.err.log
```

## How much can a crash loop cost me?

The retry ceiling bounds your worst-case API bill, and the plan price comes on top. Suppose the agent calls an API that costs $0.004 per request and each launch issues up to 50 requests before the checkpoint advances.

- Normal day, no crashes: 1 launch × 50 requests × $0.004 = **$0.20 a day in API spend.**
- Pathological day, ceiling hit: 5 launches × 50 requests × $0.004 = **$1.00 a day**, then the job stops until you clear `.relaunch_count`.
- Without a ceiling, the same fault at a 30-second throttle floor could spawn 2,880 launches in 24 hours, which is **$576 a day** before any alert fires.

Add the hosting plan on top: $25 a month for the Intel Mac VM, or $39 a month for the Apple Silicon Mac VM. Compare that figure with your runaway-loop exposure, not with the headline monthly rate alone.

## How do I start, or move an existing agent?

Pick a plan on the [Mac hosting page](/mac-hosting), connect over SSH, and then:

1. Write `/usr/local/bin/agent-wrapper` with the script above and run `chmod 755` on it.
2. Place the plist in `~/Library/LaunchAgents/`, owned by the agent user and not group- or world-writable.
3. Run `launchctl load ~/Library/LaunchAgents/com.yourorg.automation-agent.plist`.
4. Run the three checks before treating the workflow as production.

To migrate from an existing Mac, copy the working directory (including `checkpoint.json` and `.relaunch_count` if a run is in progress) and the plist, then update absolute paths to the new host's layout before loading.

**Related guides**

- [Set a retry budget for a Mac agent](/blog/mac-agent-retry-budget)
- [Cap API spend from a Mac agent](/blog/mac-agent-api-spend-caps)
- [Run a GitHub Actions self-hosted runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
