# Detect Complete Browser Downloads on a Mac

Canonical: https://figment.so/blog/mac-agent-download-completion

Wait for the .crdownload, .part or .download temp file to disappear, confirm the file size is stable, and optionally check a SHA-256. The detector runs on a Figment Intel Mac VM ($25 a month).

Wait for the browser's temp file to disappear, confirm the final file's size has stopped changing, and optionally verify a SHA-256 before the next pipeline stage touches the file. Browsers do not announce completion. Chrome and Chromium write a `.crdownload` file, Firefox writes `.part`, and Safari writes `.download` while the final file grows, then rename the temp file to the target name when the transfer finishes. Automation that reads `~/Downloads` right after a click races that rename and processes half-written files. The detector below runs on a Figment Intel Mac VM ($25 a month).

## Which Figment plan runs the browser and the detector?

The [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, $2 a day, $0.15 an hour) runs Chromium, Firefox or Edge automation. It has 4 shared vCPUs, 4GB of RAM and an 80GB SSD, and runs macOS Sequoia. Selenium, Playwright and Puppeteer all drive Chromium on Intel macOS, and the browser and the detector run in the same user session. You reach the Mac over SSH, encrypted remote desktop or the browser.

| Plan | Fits this job when |
|---|---|
| [Intel Mac VM](/mac-hosting#intel-vm): $25 a month, $2 a day | Chromium, Firefox or Edge automation, most web downloads, one browser at a time |
| [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm): $39 a month, $6 a day | arm64-only tooling, iOS simulator runs that need Xcode 26.4 or later. 4 shared vCPUs, 4GB RAM and 65GB SSD |
| [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro): $349 a month ($299 on a 12-month term) | Many parallel browsers or very large downloads on a whole Mac (48GB RAM, 512GB SSD) |

Watch the 80GB disk when you repeatedly download large files, and add your own cleanup step between runs. Figment runs the Mac and network layer. The browser, the detector and the CI pipeline are yours to manage.

## What inputs does the detector need?

It needs a directory, a filename pattern and a timeout. Everything else is optional.

| Input | Source |
|---|---|
| Downloads directory | `~/Downloads` by default for Chrome, Firefox, Edge and Safari |
| Expected filename pattern | A glob matching the target file (e.g. `invoice-*.pdf`) |
| Expected size (bytes), optional | The server's `Content-Length` header or a manifest |
| Expected SHA-256, optional | A release manifest or a value you recorded earlier |
| Stability window (seconds) | Unchanged-size interval that counts as "done"; 3 s is a safe default |
| Timeout (seconds) | Hard cap so a failed download does not hang the job |

The detector runs as the agent user and needs no elevated permissions. If a browser profile redirects downloads elsewhere, override the path when you launch the script.

## How does the detector tell that a download is complete?

It polls every half second for the temp extension to disappear, confirms the file size is stable for the stability window, then optionally checks size and SHA-256. These are the temp extensions and completion signals:

| Browser | Temp extension | Completion signal |
|---|---|---|
| Chrome / Chromium / Edge | `.crdownload` | Temp file renamed to final filename |
| Firefox | `.part` | Temp file renamed to final filename |
| Safari | `.download` | Temp file renamed to final filename |

```python
#!/usr/bin/env python3
"""
detect_download.py: wait for a browser download to complete.

Usage:
    python3 detect_download.py \
        --pattern "report-*.pdf" \
        --timeout 120 \
        [--expected-sha256 <hex>] \
        [--expected-bytes <n>] \
        [--dir ~/Downloads]

Exits 0 on success and prints the final file path to stdout.
Exits 1 on timeout, size mismatch, or checksum mismatch.
"""
import argparse, fnmatch, hashlib, sys, time
from pathlib import Path
from typing import Optional

TEMP_SUFFIXES = {".crdownload", ".part", ".download", ".partial", ".opdownload"}
POLL_INTERVAL = 0.5       # seconds between polls
STABILITY_WINDOW = 3.0    # seconds of unchanged size before "complete"


def find_candidate(download_dir: Path, pattern: str) -> Optional[Path]:
    for p in download_dir.iterdir():
        if p.suffix in TEMP_SUFFIXES:
            continue
        if fnmatch.fnmatch(p.name, pattern):
            return p
    return None


def is_size_stable(path: Path, window: float) -> bool:
    size_before = path.stat().st_size
    time.sleep(window)
    try:
        size_after = path.stat().st_size
    except FileNotFoundError:
        return False
    return size_before == size_after and size_before > 0


def sha256_of(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--pattern", required=True)
    ap.add_argument("--timeout", type=float, default=120)
    ap.add_argument("--expected-sha256", default=None)
    ap.add_argument("--expected-bytes", type=int, default=None)
    ap.add_argument("--dir", default="~/Downloads")
    args = ap.parse_args()

    download_dir = Path(args.dir).expanduser()
    deadline = time.monotonic() + args.timeout
    print(f"Watching {download_dir} for '{args.pattern}' "
          f"(timeout {args.timeout}s)...", flush=True)

    while time.monotonic() < deadline:
        candidate = find_candidate(download_dir, args.pattern)
        if candidate is None or not is_size_stable(candidate, STABILITY_WINDOW):
            time.sleep(POLL_INTERVAL)
            continue

        if args.expected_bytes is not None:
            actual = candidate.stat().st_size
            if actual != args.expected_bytes:
                print(f"ERROR: size mismatch: expected {args.expected_bytes}, "
                      f"got {actual}", file=sys.stderr)
                return 1

        if args.expected_sha256 is not None:
            actual_hash = sha256_of(candidate)
            if actual_hash.lower() != args.expected_sha256.lower():
                print("ERROR: checksum mismatch.\n"
                      f"  expected: {args.expected_sha256}\n"
                      f"  actual:   {actual_hash}", file=sys.stderr)
                return 1

        print(str(candidate), flush=True)
        return 0

    print(f"ERROR: timeout after {args.timeout}s waiting for '{args.pattern}'.",
          file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
```

Use it in a pipeline:

```bash
# Trigger the download first (e.g. a Selenium click), then wait:
if ! FILE=$(python3 detect_download.py \
        --pattern "invoice-*.pdf" \
        --timeout 60 \
        --expected-sha256 "a3f1...c9d2"); then
    echo "Download failed or timed out" >&2
    exit 1
fi
echo "Downloaded to: $FILE"
# Now safe to process "$FILE"
```

If you do not have a hash in advance, drop `--expected-sha256` and pass `--expected-bytes` from the server's `Content-Length` header. With neither available, the stability window alone is the completion signal, and three seconds of unchanged size is reliable for local-disk writes.

## How do I test the detector before real use?

Run these three checks on the Mac before you wire the script into a pipeline.

**Check 1: the temp extension is ignored.**

```bash
touch ~/Downloads/report-test.pdf.crdownload
python3 detect_download.py --pattern "report-test.pdf" --timeout 5
# Expected: exits 1 (timeout); the .crdownload file is correctly skipped.
rm ~/Downloads/report-test.pdf.crdownload
```

**Check 2: the stability window fires.**

```bash
printf 'test content\n' > ~/Downloads/report-test.pdf
python3 detect_download.py --pattern "report-test.pdf" --timeout 10
# Expected: exits 0 and prints the full path after ~3 s.
rm ~/Downloads/report-test.pdf
```

**Check 3: a checksum mismatch is caught.**

```bash
printf 'wrong content\n' > ~/Downloads/report-test.pdf
python3 detect_download.py \
    --pattern "report-test.pdf" \
    --timeout 10 \
    --expected-sha256 "0000000000000000000000000000000000000000000000000000000000000000"
# Expected: exits 1 with "checksum mismatch".
rm ~/Downloads/report-test.pdf
```

## Can I use file events instead of polling?

Yes, with [fswatch](https://emcrisostomo.github.io/fswatch/) for high-frequency workflows. It uses macOS [File System Events](https://developer.apple.com/documentation/coreservices/file_system_events) and kqueue to deliver change notifications with lower CPU cost than polling. FSEvents coalesces changes at directory granularity, so the shell callback still needs the temp-extension and stability checks. A change notification only means "something happened in `~/Downloads`", not "a download just finished".

```bash
# Requires: brew install fswatch
# Verify --event flag names with `fswatch --help`; they vary by version.
fswatch -0 ~/Downloads | while IFS= read -r -d '' path; do
    base=$(basename "$path")
    case "$base" in
        *.crdownload|*.part|*.download|*.partial|*.opdownload|*.tmp) continue ;;
    esac
    python3 detect_download.py --pattern "$base" --timeout 30 || continue
done
```

## What does the detector cost to run?

The plan sets the cost, because the detector itself uses negligible CPU at a 0.5 s poll. One agent running all month on the Intel Mac VM costs $25. A 14-day project on daily plans costs 14 × $2 = $28, so a monthly plan is cheaper once you need more than 12 days. Two parallel detectors on two separate Intel VMs cost 2 × $25 = $50 a month. Billing does not pause when no download is running. The Apple Silicon Mac VM raises the monthly figure to $39 and the Dedicated M4 Pro 48 GB to $349.

## How do I start, or move an existing download step?

Pick a plan on the [Mac hosting page](/mac-hosting). Once the Mac is ready:

1. Copy `detect_download.py` to the agent user's working directory.
2. Run checks 1 to 3 against `~/Downloads` before wiring the script into your pipeline.
3. Replace any `time.sleep(...)` or fixed-delay wait in the existing automation with a call to `detect_download.py`, and use its stdout as the file path for the next step.

Related guides:

- [Mac Agent Network Scope](/blog/mac-agent-network-scope)
- [Mac Agent Log Redaction](/blog/mac-agent-log-redaction)
- [GitHub Actions Self-Hosted Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
