# Queue Agent Tasks Safely on One Rented Mac

Canonical: https://figment.so/blog/mac-agent-task-queue

Store each task in its own directory with a state file (PENDING, RUNNING, DONE, FAILED) and guard the worker with an atomic mkdir lock. A Figment Intel Mac VM ($25 a month) runs the queue.

Run a single-worker queue on one Mac by giving each task its own directory with a `state` file (`PENDING`, `RUNNING`, `DONE` or `FAILED`) and guarding the worker with an atomic `mkdir` lock. That gives you serial execution where no task runs twice and none is silently dropped, with nothing to operate beyond launchd. If the tasks are shell, Python, Node, curl, image or PDF tooling or any Intel-compatible binary, a Figment Intel Mac VM at $25 a month is enough. Tasks that need Apple silicon go on an Apple Silicon Mac VM ($39 a month).

## Which Figment Mac plan runs the queue?

The plan depends on what the tasks execute. The queue itself uses almost no resources.

| Tasks need | Plan | Price |
| --- | --- | --- |
| Shell, Python, Node, curl, image or PDF tools, Intel-compatible binaries | [Intel Mac VM](/mac-hosting#intel-vm), 4 shared vCPUs, 4GB, 80GB, macOS Sequoia | $25 a month, $2 a day |
| arm64-only binaries, Xcode 26.4 or later, visionOS tooling ([Apple porting guide](https://developer.apple.com/documentation/apple-silicon/porting-your-macos-apps-to-apple-silicon)) | [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm), 4 shared vCPUs, 4GB, 65GB | $39 a month, $6 a day |
| Heavy tasks, or a queue you want isolated on a whole Mac | [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro), M4 Pro, 48GB, 512GB | $349 a month ($299 on a 12-month term) |

The Intel Mac VM and the Dedicated M4 Pro include SSH, encrypted remote desktop and browser access; the Apple Silicon Mac VM has the browser desktop and SSH. Storage includes the OS.

## Why does a single-worker queue need explicit state?

A polling agent that fetches "the next task" and runs it has two silent failure modes:

1. **Double execution.** The agent crashes mid-task, nothing recorded the outcome, and the next poll picks up the same task.
2. **Dropped tasks.** The agent starts a task, the Mac restarts, and nobody reconciles it.

Writing task state to disk at every transition prevents both. Each task owns a directory and moves through four states:

```
PENDING → RUNNING → DONE
                  ↘ FAILED
```

The worker picks up only `PENDING`. Anything found in `RUNNING` at startup belonged to a previous run that died, so the worker demotes it to `FAILED` with a reason, and a human or a retry policy decides what happens next.

## How do I implement the state machine?

Use `mkdir` as the lock, because a single `mkdir` is atomic on APFS. You need no external tools, no flock and no daemons beyond launchd.

```bash
#!/usr/bin/env bash
# queue-loop.sh — single-worker queue state machine
set -euo pipefail

QUEUE_DIR="${HOME}/agent-queue"
LOCK_DIR="${QUEUE_DIR}/.worker.lock"
LOG="${QUEUE_DIR}/worker.log"

mkdir -p "$QUEUE_DIR"
log() { echo "[$(date -u +%FT%TZ)] $*" | tee -a "$LOG"; }

# Acquire exclusive lock (mkdir is atomic). Exit quietly if already held.
if ! mkdir "$LOCK_DIR" 2>/dev/null; then
  log "Another worker is running. Exiting."
  exit 0
fi
trap 'rmdir "$LOCK_DIR" 2>/dev/null || true' EXIT

# Startup reconciliation: anything still RUNNING died previously.
for task_dir in "$QUEUE_DIR"/*/; do
  [[ -f "$task_dir/state" ]] || continue
  if [[ "$(cat "$task_dir/state")" == "RUNNING" ]]; then
    log "Reclaiming interrupted task $(basename "$task_dir")"
    echo "FAILED" > "$task_dir/state"
    echo "interrupted_at_startup" > "$task_dir/failure_reason"
  fi
done

# Pick one PENDING task.
NEXT_TASK=""
for task_dir in "$QUEUE_DIR"/*/; do
  [[ -f "$task_dir/state" ]] || continue
  if [[ "$(cat "$task_dir/state")" == "PENDING" ]]; then
    NEXT_TASK="$task_dir"; break
  fi
done
[[ -z "$NEXT_TASK" ]] && { log "Queue empty."; exit 0; }

TASK_ID=$(basename "$NEXT_TASK")
echo "RUNNING" > "$NEXT_TASK/state"
date -u +%FT%TZ > "$NEXT_TASK/started_at"
log "Starting $TASK_ID"

if bash "$NEXT_TASK/run.sh" >> "$NEXT_TASK/output.log" 2>&1; then
  echo "DONE" > "$NEXT_TASK/state"
  date -u +%FT%TZ > "$NEXT_TASK/completed_at"
  log "$TASK_ID DONE"
else
  rc=$?
  echo "FAILED" > "$NEXT_TASK/state"
  echo "exit_code_${rc}" > "$NEXT_TASK/failure_reason"
  log "$TASK_ID FAILED rc=$rc"
  exit "$rc"
fi
```

Enqueue a task by writing a `run.sh` and a `state` file:

```bash
# enqueue-task.sh <task-id>  (pipe the script body on stdin)
TASK_ID="${1:-task-$(date +%s)}"
TASK_DIR="${HOME}/agent-queue/${TASK_ID}"
mkdir -p "$TASK_DIR"
cat > "$TASK_DIR/run.sh"
chmod +x "$TASK_DIR/run.sh"
echo "PENDING" > "$TASK_DIR/state"
date -u +%FT%TZ > "$TASK_DIR/enqueued_at"
```

This is an untested example. Run it against a throwaway task before you point it at real work.

## How do I install it as a launchd agent?

Each invocation does one poll and exits. `StartInterval` schedules the next poll, and `KeepAlive.SuccessfulExit = false` tells launchd to restart the worker only when it exits non-zero, that is, after a failed task. The two keys evaluate independently ([`launchd.plist(5)`](https://keith.github.io/xcode-man-pages/launchd.plist.5.html), [Apple Creating Launchd Jobs](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html)).

```xml
<!-- ~/Library/LaunchAgents/com.yourteam.queue-worker.plist -->
<plist version="1.0">
<dict>
  <key>Label</key><string>com.yourteam.queue-worker</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>/Users/agent/agent-queue/queue-loop.sh</string>
  </array>
  <key>StartInterval</key><integer>30</integer>
  <key>KeepAlive</key>
  <dict><key>SuccessfulExit</key><false/></dict>
  <key>StandardOutPath</key><string>/Users/agent/agent-queue/worker.log</string>
  <key>StandardErrorPath</key><string>/Users/agent/agent-queue/worker-err.log</string>
</dict>
</plist>
```

Load it with `launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.yourteam.queue-worker.plist`. Setting `SuccessfulExit` implies `RunAtLoad`, so the first poll happens immediately.

## How do I prove the lock works?

Run a concurrency test before you trust the queue. It launches two workers against one `PENDING` task and asserts that the task ran exactly once.

```bash
#!/usr/bin/env bash
# concurrency-test.sh
set -euo pipefail
QUEUE_DIR="${HOME}/agent-queue"
TASK_ID="concurrency-test-$(date +%s)"
TASK_DIR="${QUEUE_DIR}/${TASK_ID}"
mkdir -p "$TASK_DIR"
printf '#!/usr/bin/env bash\nsleep 5\necho "pid=$$" >> "%s/execution_log"\n' \
  "$TASK_DIR" > "$TASK_DIR/run.sh"
chmod +x "$TASK_DIR/run.sh"
echo "PENDING" > "$TASK_DIR/state"

bash "${QUEUE_DIR}/queue-loop.sh" & P1=$!
bash "${QUEUE_DIR}/queue-loop.sh" & P2=$!
wait "$P1" || true
wait "$P2" || true

count=$( [[ -f "$TASK_DIR/execution_log" ]] && wc -l < "$TASK_DIR/execution_log" || echo 0 )
state=$(cat "$TASK_DIR/state")
echo "state=$state count=$count"
if [[ "$count" -eq 1 && "$state" == "DONE" ]]; then
  echo "PASS"; rm -rf "$TASK_DIR"
else
  echo "FAIL"; exit 1
fi
```

Re-run it after any OS update, launchd reload or edit to `queue-loop.sh`. A failed test is a real failure, not a data point.

## What should I check after setup?

Tick off this list:

- [ ] `concurrency-test.sh` prints `PASS`.
- [ ] `worker.log` shows the ordered transitions `PENDING`, `RUNNING`, `DONE`.
- [ ] A task whose `run.sh` ends with `exit 1` ends in state `FAILED` with a `failure_reason`.
- [ ] After `launchctl kickstart -k gui/$(id -u)/com.yourteam.queue-worker` during a running task, the task is left in `FAILED` on the next poll, not `RUNNING`.
- [ ] `~/agent-queue/.worker.lock` is absent while no worker is active.

## When do I need more than one worker?

When one queue is not enough, add another Mac and not another worker on the same one. The lock is per host, and several workers on one host would need a distributed lock.

| Factor | Intel Mac VM | Apple Silicon Mac VM or Dedicated M4 Pro |
|---|---|---|
| Workers on this design | 1 per queue directory | 1 per queue directory |
| Disk for queue directories | 80GB SSD, OS included | 65GB SSD (VM) or 512GB (dedicated), OS included |
| Task runtime | Intel-compatible binaries, shell, Python, Node, curl | arm64 binaries, newer Xcode |
| Trigger to move up | `run.sh` needs an arm64-only binary, Xcode 26.4 or later, or visionOS | Tasks outgrow 4GB, or need isolation |

Rent a second Mac for real parallelism, and keep the queue directory on each Mac separate. Each Mac bills from its own order, so a daily plan suits a burst of parallel work. For several Macs under one agreement, Figment quotes enterprise setups on a call. See the [Mac hosting plans](/mac-hosting).

Related: [Mac agent large uploads](/blog/mac-agent-large-uploads) · [Mac Safari scheduled PDF](/blog/mac-safari-scheduled-pdf) · [GitHub Actions self-hosted runner on Mac](/blog/mac-github-actions-self-hosted-runner)
