LLimrun

Run a macOS virtual machine

A macOS instance is a full macOS virtual machine in the cloud. You can use its desktop in the Limrun console with your mouse, trackpad, and keyboard, and the lim CLI or an SDK client can run shell commands in it, launch apps, click and type on its screen, and record what happens. To build your own Mac app and run it on one, see Build a Mac app.

Before you start

You need an API key in LIM_API_KEY and one of these:

The Python SDK has no macOS client; drive macOS instances from Python through the CLI.

Create a macOS instance

Create an instance. The command waits until the virtual machine is ready:

lim macos create

The output names the instance, the console URL that shows its desktop, and the region it runs in:

Created macOS instance: macos_<region>_<id>
Console URL: https://console.limrun.com/stream/macos_<region>_<id>
Region: <region>
Delete with: lim macos delete macos_<region>_<id>

Pass flags to keep the instance in one jurisdiction, name it, or label it:

lim macos create --jurisdiction eu --display-name review-mac --label env=dev --inactivity-timeout 30m
FlagWhat it does
--jurisdiction us|eu|asKeep the instance inside one jurisdiction. Creation fails when no region there has capacity.
--inactivity-timeout <duration>Delete the instance after this long without input or API calls, such as 30m. Without the flag, your organization's macOS default applies.
--hard-timeout <duration>Delete the instance after this long regardless of activity, such as 3h. Without the flag, your organization's macOS default applies.
--display-name <name>Name shown in listings and the console.
--label key=valueAttach a metadata label. Repeat for several labels.
--reuse-if-existsReturn an existing instance with exactly the same labels instead of creating one. See Labels and reuse.
--permission <permission>Add an asset permission to the instance's role. Repeatable. See Workload roles.
--snapshot-key, --snapshot-restore-keysRestore the disk from a saved snapshot and save it again when the instance terminates. See Keep a macOS disk between instances.
--tunnel <name>, --tunnel-header 'Name: value'Attach a private tunnel before the instance becomes ready. See Reach services on your machine.
--egress-domain <domain>, --egress-header 'Name: value'Inject HTTP headers into the instance's outbound requests to your domains, with no tunnel. Repeat each flag for more domains or headers. See Inject headers into outbound requests.
--record, --events, --app-logs <bundle-id>, --perf, --persist-ttl <duration>Start persisted captures as soon as the instance is ready. See Keep captures after the session.
--jsonPrint the instance as JSON, with its console URL in consoleUrl.

Use the desktop

Open the console URL in a browser where you are signed in to console.limrun.com with the organization that owns the instance. The page streams the desktop and sends your pointer, scroll, and keyboard input to the virtual machine, including modifier keys and macOS shortcuts.

To print the console URL again, get the instance:

lim macos get

Without an ID, lim macos get shows the last macOS instance you created in the current workspace, and lists your macOS instances when there is none. Pass an ID to show another one: lim macos get <instance-id>. Every other lim macos command on this page picks its instance the same way and takes --id <instance-id> for another one. See The CLI's default instance for how the CLI scopes workspaces.

Connect a client

The SDKs work inside the virtual machine through a client made from the ready instance. The CLI connects on its own for every command, so it has no client step:

# No client step: every command connects on its own.
lim macos screenshot ./screen.jpg
import Limrun from '@limrun/api';

const lim = new Limrun(); // reads LIM_API_KEY
const mac = await lim.macosInstances.create({ wait: true, spec: { inactivityTimeout: '30m' } });
const guest = await lim.macosInstances.createClient({ instance: mac });
// ... work inside the guest ...
guest.disconnect();
import (
    "context"

    limrun "github.com/limrun-inc/go-sdk"
    "github.com/limrun-inc/go-sdk/macos"
    "github.com/limrun-inc/go-sdk/packages/param"
)

ctx := context.Background()
client := limrun.NewClient() // reads LIM_API_KEY

mac, err := client.MacosInstances.New(ctx, limrun.MacosInstanceNewParams{
    Wait: param.NewOpt(true),
    Spec: limrun.MacosInstanceNewParamsSpec{InactivityTimeout: param.NewOpt("30m")},
})
if err != nil {
    panic(err)
}
guest, err := client.MacosInstances.CreateClient(*mac)
if err != nil {
    panic(err)
}
defer guest.Close()

The client needs the instance's status.token, which create, get, and list return only to a credential that controls the instance. The TypeScript and Go snippets on the rest of this page reuse guest (and ctx in Go).

Run shell commands

Run a command line inside the virtual machine. It runs as the guest's user, limrun, in its login session and with a login shell, and that user can run sudo without a password. Output streams back as it arrives, and the remote exit code becomes the command's exit code:

lim macos run -- sw_vers
lim macos run --cwd Projects/app --env APP_ENV=staging -- ./scripts/setup.sh
const command = guest.run('./scripts/setup.sh', {
  cwd: 'Projects/app',          // relative to the home directory
  env: ['APP_ENV=staging'],
  timeoutSeconds: 1800,
});
command.stdout.on('data', (line) => process.stdout.write(line));
command.stderr.on('data', (line) => process.stderr.write(line));
const { exitCode } = await command;
proc, err := guest.Run(ctx, "./scripts/setup.sh", &macos.RunOptions{
    Cwd: "Projects/app",
    Env: []string{"APP_ENV=staging"},
})
if err != nil {
    panic(err)
}
result, err := proc.Wait(ctx)
if err != nil {
    panic(err)
}
fmt.Println("exit code:", result.ExitCode)

The working directory is relative to the home directory unless it is absolute. Commands stop after 3600 seconds unless you pass --timeout (timeoutSeconds in TypeScript, TimeoutSeconds in Go), up to 21600. lim macos exec is an alias of lim macos run, and Ctrl+C ends the remote command.

Avoid Desktop, Documents, and Downloads as working directories. macOS asks for permission to use them, and the command waits on that prompt.

Move files

Sync a local folder into the virtual machine, then build or run in it. The first sync sends every file, and later syncs send only what changed:

lim macos sync ./MyApp
lim macos run --cwd MyApp -- swift build
lim macos sync ./MyApp --watch
await guest.sync('./MyApp'); // lands in ~/MyApp
const build = guest.run('swift build', { cwd: 'MyApp' });
build.stdout.on('data', (line) => process.stdout.write(line));
await build;
_, err = guest.Sync(ctx, "./MyApp", nil) // lands in ~/MyApp
if err != nil {
    panic(err)
}

The folder lands in the guest user's home under its own name, such as ~/MyApp, unless you pass --destination (destination in TypeScript, Destination in Go), absolute or relative to the home. The folder's .gitignore files apply, and files the local folder no longer has are removed from the guest folder. Files created in the guest folder, such as build output, are left alone. --watch keeps syncing each change until you press Ctrl+C. The files belong to the guest user, and a disk snapshot keeps them.

Push, pull, list, and delete single files and folders by guest path, absolute or relative to the home:

lim macos push-file ./fixture.json Desktop/fixture.json
lim macos ls MyApp
lim macos pull MyApp/.build/release ./release
lim macos delete-file Desktop/fixture.json
await guest.pushFile('./fixture.json', 'Desktop/fixture.json');
const entries = await guest.listFiles('MyApp'); // [{ name, path, isDirectory, size }]
await guest.pull('MyApp/.build/release', './release');
await guest.deleteFile('Desktop/fixture.json');
_, err = guest.PushFile(ctx, "./fixture.json", "Desktop/fixture.json")
entries, err := guest.ListFiles(ctx, "MyApp")
fmt.Println(len(entries), "entries")
_, err = guest.Pull(ctx, "MyApp/.build/release", "./release")
err = guest.DeleteFile(ctx, "Desktop/fixture.json")

Pushing creates parent folders and replaces a file already at the path. Pulling a folder unpacks it locally, merging with what is already there, and when the local path is an existing folder, the file or folder lands inside it under its own name. Deleting a synced folder makes the next sync into it send every file. To upload a folder, sync it.

Open an SSH session

For an interactive shell or an editor's remote mode, open an SSH tunnel. The command turns on SSH in the virtual machine, authorizes your public key, and forwards a local port to it:

lim macos ssh 2222
ssh -p 2222 limrun@localhost

Without --public-key, the CLI uses the first of ~/.ssh/id_ed25519.pub, ~/.ssh/id_ecdsa.pub, and ~/.ssh/id_rsa.pub, or creates a key in ~/.lim/ssh. The forward runs in the background and the command prints its PID; stop it with kill <pid>. Pass --no-detach to keep it in the foreground until Ctrl+C. Password logins stay off.

The SDK clients do the same in two calls: enableSsh(publicKey) (EnableSSH in Go) returns the guest user and the port SSH listens on, and startPortForward(localPort, access.port) forwards a local port to it.

Drive the desktop

Take a screenshot, then click, type, press keys, scroll, and drag at points on it. Points are pixels of the screenshot, counted from the top-left corner:

lim macos screenshot ./screen.jpg
lim macos tap 640 360
lim macos type "hello world" --enter
lim macos press-key q --modifier command
lim macos scroll down --amount 600 --coordinate 640,400
lim macos drag --from 200,300 --to 600,300
import fs from 'node:fs';

fs.writeFileSync('screen.jpg', await guest.screenshot());
await guest.tap({ x: 640, y: 360 });
await guest.typeText('hello world');
await guest.pressKey('enter');
await guest.pressKey('q', ['command']);
await guest.scroll({ dy: 600, at: { x: 640, y: 400 } }); // positive dy scrolls down
await guest.drag({ x: 200, y: 300 }, { x: 600, y: 300 });
jpeg, err := guest.Screenshot(ctx)
if err != nil {
    panic(err)
}
_ = os.WriteFile("screen.jpg", jpeg, 0o644)
_ = guest.Tap(ctx, macos.Point{X: 640, Y: 360}, nil)
_ = guest.TypeText(ctx, "hello world")
_ = guest.PressKey(ctx, "enter")
_ = guest.PressKey(ctx, "q", macos.ModifierCommand)
_ = guest.Scroll(ctx, macos.ScrollOptions{DY: 600, At: &macos.Point{X: 640, Y: 400}})
_ = guest.Drag(ctx, macos.Point{X: 200, Y: 300}, macos.Point{X: 600, Y: 300}, nil)

What each action does:

Launch and stop apps

List the apps the guest user can open, with their bundle IDs, to find the one to launch:

lim macos list-apps
const apps = await guest.listApps(); // [{ bundleId, name, installType, pid? }, ...]

The list covers /Applications, /System/Applications, the user's Applications folder, and any app launched from elsewhere. installType is system for apps macOS ships and user for the rest, and running apps carry their pid.

Launch an app by bundle ID, name, or path, and bring it to the front:

lim macos launch-app com.apple.TextEdit
lim macos launch-app com.example.app --env API_URL=https://staging.example.com --arg -v --mode RelaunchIfRunning
lim macos terminate-app com.example.app
const { pid, launched } = await guest.launchApp('com.example.app', {
  mode: 'RelaunchIfRunning',
  arguments: ['-v'],
  env: { API_URL: 'https://staging.example.com' },
});
await guest.terminateApp('com.example.app');
app, err := guest.LaunchApp(ctx, "com.example.app", &macos.LaunchAppOptions{
    Mode:      macos.RelaunchIfRunning,
    Arguments: []string{"-v"},
    Env:       map[string]string{"API_URL": "https://staging.example.com"},
})
if err != nil {
    panic(err)
}
fmt.Println(app.PID, app.Launched)
_ = guest.TerminateApp(ctx, "com.example.app")

When the app already runs, launching it brings it to the front and ignores the arguments and environment, unless you pass RelaunchIfRunning to stop it and start it again. The result's launched is false when the app was only brought to the front. Terminating an app sends every one of its processes SIGTERM, then SIGKILL after five seconds, and succeeds when the app is not running.

Read app logs

Print the last lines of an app's log, or follow it as the app writes:

lim macos app-log com.example.app --tail 200
lim macos app-log com.example.app --follow
const tail = await guest.appLogTail('com.example.app', 200);

const stop = guest.streamAppLog('com.example.app', {
  onEntry: (line) => console.log(line),
  onError: (err) => console.error(err),
});
// ... drive the app ...
stop();
tail, err := guest.AppLogTail(ctx, "com.example.app", 200)
if err != nil {
    panic(err)
}
fmt.Print(tail)

An app's log holds what it wrote to the macOS unified log and, when you started it with launch-app, its stdout and stderr. An app started any other way writes its stdout and stderr nowhere. For apps that are not Apple's, messages from Apple's frameworks are left out. Without --follow, the command prints the last 100 lines from the past hour.

Check app CPU and memory

The virtual machine samples every app in an Applications folder once a second and keeps the last ten minutes, so you can read the figures at any point without starting a capture:

lim macos perf
lim macos perf --app com.example.app --since 2m
lim macos perf --follow
const stop = guest.streamPerformance({
  onEntry: (sample) => {
    if (sample.bundleId !== 'com.example.app') return;
    console.log(`${sample.cpuPercent ?? '-'}% CPU, ${(sample.footprintBytes / 1024 / 1024).toFixed(1)} MB`);
  },
});
// ... drive the app ...
stop();

lim macos perf prints each app's CPU, memory footprint and its peak, thread count, disk rates, and busiest threads, then exits. Apps that stopped in the last ten minutes are listed as stopped, and CPU counts one busy core as 100%. --since summarizes part of the last ten minutes and --follow prints new samples until you press Ctrl+C; the two can't be combined. The figures and sample fields are the same as on iOS; see Check app CPU and memory for how to read them.

Record a video

Record the screen while you drive it. A recording includes the virtual machine's speaker as an audio track:

lim macos record start
# ... drive the desktop ...
lim macos record stop -o demo.mp4
const recordingId = await guest.startRecording({ quality: 5 });
// ... drive the desktop ...
await guest.stopRecording(recordingId, { localPath: 'demo.mp4' });
id, err := guest.StartRecording(ctx, nil)
if err != nil {
    panic(err)
}
// ... drive the desktop ...
_, err = guest.StopRecording(ctx, id, &macos.SaveRecordingTo{LocalPath: "demo.mp4"})

start returns a recording ID, generated when you don't pass one. stop takes an ID, or stops the most recently started recording that is still active, and downloads the MP4. Up to eight recordings can run at once. These options change a recording:

CLI flagTypeScript optionWhat it does
--quality <5-10>qualityEncoder quality, 5 by default. Higher values increase quality and file size.
--no-audioaudio: falseLeave the speaker out of the recording. Needs lim 0.65.5 or @limrun/api 0.79.6.
--presigned-url <url>presignedUrl in the stop callThe instance also uploads the MP4 to this HTTPS URL.
--persist, --persist-ttl <duration>persistKeep the recording in Limrun storage after the instance ends. See Keep captures after the session.

Record the speaker

To capture only what the virtual machine plays, record its speaker into a 48 kHz mono WAV file. It records whether or not anyone is watching the stream:

lim macos speaker start
# ... play audio ...
lim macos speaker stop -o speaker.wav
const id = await guest.startSpeakerRecording();
// ... play audio ...
await guest.stopSpeakerRecording(id, { localPath: 'speaker.wav' });

Speaker recordings take IDs like screen recordings do, and up to eight can run at once. They need lim 0.65.5 or @limrun/api 0.79.6.

Keep captures after the session

Persisted captures are uploaded to Limrun storage, so they outlive the CLI process and the instance. Start them when you create the instance:

lim macos create --record --events --app-logs com.example.app --perf --persist-ttl 24h

--record records the screen until you stop the recording or the instance terminates. --events logs the clicks, scrolls, and keys sent to the screen, counting typed characters without recording them. --app-logs <bundle-id> captures that app's log whenever it runs. --perf saves the CPU and memory samples of running apps. Captures are kept for 72h unless --persist-ttl says otherwise. To persist a recording you start later, use lim macos record start --persist.

List the captures, during the session or after it:

lim macos recordings --id <instance-id>
lim macos events --id <instance-id>
lim macos app-logs --id <instance-id>
lim macos perf-captures --id <instance-id>

Events, app log, and performance captures are JSONL files. With --json, each entry includes a short-lived download URL. In the SDKs, the guest client starts and stops captures (startAppLogCapture, startEventCapture, startPerformanceCapture, and their stop calls), and lim.macosInstances.listRecordings, listEvents, listAppLogs, and listPerformanceCaptures list them.

Access a server inside the VM

Forward a local port to a server running inside the virtual machine, such as a web app, an API, or a database:

lim macos forward 3000
lim macos forward 8080:3000
lim macos forward 0:5432 --json

Pass <local-port>:<remote-port> to use different ports, and local port 0 to pick a free one. The listener binds to 127.0.0.1 and runs in the background; the command prints its PID, so stop it with kill <pid>, or pass --no-detach to stay in the foreground until Ctrl+C. Start the server separately, for example with lim macos run. It must listen on 127.0.0.1, ::1, or all interfaces. UDP is not supported. In the SDKs, call startPortForward(localPort, remotePort) on the guest client.

Reach services on your machine

A destination tunnel lets code in the virtual machine reach services on the machine that runs it, such as a dev server or a VPN-only API. Declare each destination as a selector:

lim macos tunnel --selector localhost:3000 --selector "*.corp.example" --detach
lim macos tunnel status
lim macos tunnel stop
const tunnel = await guest.startTunnel({ selectors: ['localhost:3000', '*.corp.example'] });
const status = await guest.getTunnelStatus();
await guest.stopTunnel(tunnel.tunnelId);
tunnel, err := guest.StartTunnel(ctx, macos.TunnelOptions{
    Selectors: []string{"localhost:3000", "*.corp.example"},
})
if err != nil {
    panic(err)
}
defer tunnel.Close()

localhost:port and IPv4:port selectors are reachable at those same addresses in the virtual machine. Domain selectors resolve in the virtual machine to the tunnel and are dialed from your machine, whether or not the name resolves on public DNS. HTTP and HTTPS traffic through the tunnel is inspected by default. The first inspected tunnel makes the virtual machine trust the instance's inspection CA, which shows a system dialog on the screen for a few seconds; pass --no-inspect to relay traffic untouched. Connections opened before the tunnel starts keep their original route until they close. Selector forms and limits are the same as on iOS; see Connect an iOS simulator to local services.

To reach a network that many instances share, create the instance with a private tunnel instead: lim macos create --tunnel <name>. --tunnel-header 'Name: value' adds an HTTP header, next to Limrun-Instance-Id, to every inspected request the instance sends through it, so a service behind one shared tunnel can tell instances apart. The network capture shows these headers, so don't put secrets in them.

Inject headers into outbound requests

Inject HTTP headers into a macOS instance's outbound requests to your domains, without a tunnel. Name the domains and headers when you create the instance. Every outbound HTTP and HTTPS request to those domains then carries the headers, plus Limrun-Instance-Id with the instance's ID, so your backend can tell instances apart:

lim macos create \
  --egress-domain api.example.com \
  --egress-domain '*.staging.example.com' \
  --egress-header 'X-Run-Id: run-4812'
const mac = await lim.macosInstances.create({
  wait: true,
  spec: {
    egressHeaders: {
      domains: ['api.example.com', '*.staging.example.com'],
      headers: { 'X-Run-Id': 'run-4812' },
    },
  },
});
curl -X POST "https://api.limrun.com/v1/macos_instances?wait=true" \
  -H "Authorization: Bearer $LIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "spec": { "egressHeaders": { "domains": ["api.example.com", "*.staging.example.com"], "headers": { "X-Run-Id": "run-4812" } } } }'

An outbound request from the preceding example reaches your server like this:

GET /v1/orders HTTP/1.1
Host: api.example.com
Limrun-Instance-Id: macos_euna_01jx8k...
X-Run-Id: run-4812

List up to 64 domains per instance. A domain is an exact name, such as api.example.com, or a wildcard, such as *.example.com. A wildcard covers every subdomain but not the name itself. To cover both, list example.com as well. You can't use a bare *.

Set up to 16 headers per instance. They follow the same rules as tunnel headers. Creation fails with a 400 error when a header breaks a rule. Limrun stores the header values with the instance's settings, so use them for identifiers such as a run ID, not for secrets or API keys. With --reuse-if-exists, Limrun creates a new instance rather than reuse one whose injected headers differ.

The instance becomes ready only after the headers apply, so an app's first outbound request already carries them. If the headers can't apply, creation fails and Limrun deletes the instance.

To inject the headers, the virtual machine decrypts HTTPS to these domains with a certificate authority (CA) that the guest trusts. It then connects to your server and accepts the server's certificate only if it chains to one of Mozilla's public root certificates or to a CA you added to the instance. Plan for these limits:

Trust a CA certificate

Add a CA certificate to the virtual machine's system trust settings, such as the CA of an intercepting proxy you record traffic with. The file holds one PEM-encoded certificate:

lim macos ca add ./proxy-ca.pem
await guest.addCaCertificate(fs.readFileSync('./proxy-ca.pem', 'utf8'));
pem, _ := os.ReadFile("./proxy-ca.pem")
_, err = guest.AddCACertificate(ctx, string(pem))

Safari and apps that use the system trust store accept the CA on their next connection. macOS asks an administrator to confirm a new trusted root, so the instance answers that dialog itself, and the dialog shows on the screen for a few seconds. Adding a certificate the virtual machine already trusts changes nothing.

List instances

List the macOS instances in your organization. Without flags, the list shows only instances that are ready:

lim macos list

Show instances in every state with --all, pick states with --state (a comma-separated list such as creating,ready), or filter by labels with --label-selector:

lim macos list --label-selector env=dev

Delete the instance

Delete the instance when you are done. Deleting it discards everything on its disk. An instance created with a snapshot key first saves its changes; see Keep a macOS disk between instances:

lim macos delete

Without an ID, the command deletes the last macOS instance you created in the current workspace. Pass an ID to delete another one: lim macos delete <instance-id>.

Set the timeouts

Two timeouts delete an instance you forget about:

When you create an instance without --inactivity-timeout or --hard-timeout, it gets your organization's macOS defaults. Organizations start with an inactivity timeout of 3 minutes and no hard timeout. Organization admins change the defaults in the console under Settings, Instance defaults, Instance timeouts, in the macOS VM row.

Set a longer inactivity timeout when you expect to step away from the desktop and come back to the same instance:

lim macos create --inactivity-timeout 30m

Next steps

database

Keep a macOS disk between instances

Save the files, apps, and tools you set up, and restore them on the next instance.

monitor-play

Create and embed from code

Create macOS instances from your backend and show the desktop in your own web app.