Skip to main content

Example: File watching

You use this pattern when your app reacts to filesystem changes inside a sandbox: rebuild on save, tail new logs, trigger tests when files land in a folder. The high-level API is sandbox.fs.watch. Under the hood you start a watch session over HTTP and stream events over a WebSocket: see File watching.

What you accomplish

You register a path (and optionally recursive). You receive events with types and paths. You close the watcher when you finish. You remove the sandbox when you no longer need the VM.

Prerequisites

You completed Examples overview. On Python, watch is async: you use AsyncVoidRun.

Pattern: TypeScript

You pass onEvent and onError. You call close() on the watcher handle.

Pattern: Python (async)

You await sandbox.fs.watch inside an async context. You close() the watcher, then you remove the sandbox.
Prefer asyncio.to_thread around sandbox.exec in async handlers. Use *_async FS helpers (for example list_files_async) when the SDK exposes them.

How this maps to HTTP

You start a session with POST /sandboxes/{id}/files/watch. You open WebSocket to /sandboxes/{id}/files/watch/{sessionId}/stream. You pass X-API-Key when your deployment requires it on upgrade. The SDK hides most of this: you fall back to raw HTTP when you debug.

Practices you should follow

  • You watch narrow paths (/app/src not /) when you can; broad recursive watches generate noise and load.
  • You debounce events in your app if you rebuild on every write.
  • You close watchers in finally blocks so you do not leak sessions.

File system

Upload, list, download

File watching concepts

HTTP + WebSocket flow