Управление и стриминг симулятора iOS, iPad или Apple Watch через npx serve-sim: превью, тапы, жесты, кнопки, поворот, камера, права.

Звёзды2 946
Форки171
Авторevanbacon
Обновлённоя 17 2026

Установка

SKILL.md

serve-sim

Drive an Apple Simulator (iOS, iPad, Apple Watch) from an agent using the serve-sim CLI. serve-sim spawns a Swift helper that captures the simulator framebuffer via simctl io, exposes it as an MJPEG stream plus a binary WebSocket input channel, and serves a React preview UI on top. This skill teaches an agent the exact CLI surface, the gesture JSON shape, the gotchas, and the recommended workflows.

When to use

  • The user wants an agent to tap, swipe, drag, pinch, or send hardware buttons to a running Apple Simulator.
  • The user wants to stream a simulator to a browser (local, LAN, or tunneled) for review or remote control.
  • The user wants to inject a synthetic camera feed (file, webcam, or animated placeholder) into a specific app on the simulator.
  • The user wants to toggle CoreAnimation debug overlays (off-screen rendering, blended layers, slow animations) for performance work.
  • The user wants to simulate a memory warning or rotate the device programmatically.
  • The user wants to read the simulator's accessibility tree to find UI elements without pixel hunting.
  • The user wants to grant, revoke, or reset an app's privacy permissions — camera, photos, location, contacts, or push notifications.

When NOT to use

  • Android emulators → use adb shell tooling.
  • Building or installing an iOS app → use xcodebuild or xcrun simctl install.
  • React Native in-app runtime debugging (Redux state, network inspection, component tree) → use rn-debugger tooling.
  • Real iOS hardware devices → use xcrun devicectl or Xcode.

Prerequisites

Before any other action, verify the host satisfies these. If something is missing, tell the user exactly what to install — do not proceed.

RequirementCheck commandWhy
macOS hostuname -s returns Darwinserve-sim only runs on macOS
Xcode CLI toolsxcrun --version exits 0simctl is the underlying simulator driver
Node.js ≥18node --version ≥18serve-sim is an npm package run via npx
macOS 14+ (optional)sw_vers -productVersion ≥14Required ONLY for camera subcommand

A bundled helper script is available: scripts/check-prereqs.sh. Run it; if it exits non-zero, surface the message to the user.

A booted simulator is required for most subcommands. Check with xcrun simctl list devices booted. If none are booted, tell the user to open Xcode → Simulator or to run xcrun simctl boot <UDID>.

Mental model

┌──────────────┐  simctl io  ┌─────────────────┐  MJPEG / WS  ┌─────────┐
│ iOS Simulator│ ──────────► │ serve-sim-bin   │ ───────────► │ Browser │
└──────────────┘   (Swift)   │ (per-device)    │              └─────────┘
                             └─────────────────┘
                                     ▲
                              state file in
                            $TMPDIR/serve-sim/
                                     ▲
                            ┌──────────────────┐
                            │ serve-sim CLI    │
                            └──────────────────┘

Key invariants the agent must respect:

  • All coordinates are normalized 0..1, with (0, 0) at top-left and (1, 1) at bottom-right of the display. Never pass pixel coordinates.
  • One helper per device. Multiple booted simulators are supported by passing several device names or by attaching to all.
  • State lives in $TMPDIR/serve-sim/server-{udid}.json. Use serve-sim --list to query it; do not read the JSON directly unless you know what you are doing.
  • The orientation set via rotate is remembered by the helper, and subsequent gestures are rotated client-side. An agent that sends raw coords after a rotation does not need to compensate manually.

Common operations

GoalCommandNotes
Start preview servernpx serve-sim [device]Default preview at http://localhost:3200, stream at :3100. Foreground process.
Start headless / daemonnpx serve-sim --detach [device]Returns JSON with pid, port, url. Use for agent loops.
Show stream in host's previewnpx serve-sim --detach -q → hand off url to host preview toolSee "Showing the stream in your agent's preview" section.
List running streamsnpx serve-sim --listAdd -q for JSON-only output.
Stop all helpersnpx serve-sim --killPass [device] to stop a specific one.
Single tapnpx serve-sim tap <x> <y><x> <y> in 0..1. Use this, not gesture, for plain taps. See "Critical gotcha" below.
Multi-step gesturenpx serve-sim gesture '<json>'See references/gestures.md.
Hardware buttonnpx serve-sim button <name>Names: home, swipe_home, app_switcher, lock, siri, side_button. See references/buttons-rotation.md.
Rotate devicenpx serve-sim rotate <orientation>portrait, portrait_upside_down, landscape_left, landscape_right.
Simulate memory warningnpx serve-sim memory-warningEquivalent to Debug → Simulate Memory Warning.
CoreAnimation debugnpx serve-sim ca-debug <option> <on|off>Options: blended, copies, misaligned, offscreen, slow-animations. See references/ca-debug.md.
Inject camera feednpx serve-sim camera <bundle-id> [--file <path>|--webcam [name]](Re)launches the app with the camera dylib attached. macOS 14+ only. See references/camera.md.
Hot-swap camera sourcenpx serve-sim camera switch <placeholder|webcam|file> [arg]No app relaunch.
Manage app permissionsnpx serve-sim permissions <grant|revoke|reset|list> <permission> <bundle-id>Camera, photos, location, push notifications, contacts, etc. See references/permissions.md.
Read accessibility treecurl http://localhost:3100/axReturns axe-style JSON. See references/endpoints.md for all endpoints.

Most subcommands accept -d <udid|name> to target a specific device when several are booted.

Critical gotcha: prefer tap over gesture for taps

Each serve-sim gesture call opens its own WebSocket. If you issue two back-to-back gesture calls — one with {"type":"begin",...} and one with {"type":"end",...} — the simulator receives them with enough latency between them that the touch is interpreted as a long-press, not a tap. This is a deliberate constraint of the protocol, not a bug to work around.

Rule: for any single-shot tap, use serve-sim tap <x> <y>. Only use gesture for drags, swipes, or multi-step interactions where you must thread the same socket across begin → move × N → end.

Targeting a specific device

When multiple simulators are booted, every subcommand accepts -d <udid|name>. The name match is case-insensitive against the device name returned by xcrun simctl list devices booted. Examples:

npx serve-sim tap 0.5 0.5 -d "iPhone 16 Pro"
npx serve-sim button home -d ABC12345-...
npx serve-sim --list                                # show all running streams

If the user has only one booted simulator, omit -d entirely. The skill should prefer auto-detection over hard-coding device names.

Output modes

By default, serve-sim prints human-readable status to stdout. For agent loops, prefer JSON output:

npx serve-sim --list -q          # JSON array of running streams
npx serve-sim --detach -q        # JSON with pid/port/url after spawn
npx serve-sim camera status -q   # JSON with {alive, source, mirror, ...}

Parse -q output programmatically. Never parse the non--q human output — it can change between versions.

Showing the stream in your agent's preview

When the user asks to "see the simulator here", "view it in preview", "open it in this tool", or similar, the goal is to stream the simulator into the same surface the user is chatting with. serve-sim returns a regular HTTP URL — the agent's job is to surface that URL and, if the host exposes a preview tool, hand it off.

Steps:

  1. Start serve-sim and capture the URL:

    npx serve-sim --detach -q
    

    This returns JSON like {"pid":..., "port":3200, "url":"http://localhost:3200", "streamUrl":"http://localhost:3100", ...}. The url field is the human-facing preview UI; streamUrl is the raw MJPEG endpoint.

  2. Always surface the URL plainly in your response so the user can fallback to opening it manually in any browser.

  3. Probe your host's preview tool and hand off the URL if one exists. Examples of tool names you may see in your toolset:

    • preview_start (Claude Code) — call it with { url: "<url>" }.
    • mcp__Claude_Preview__preview_start (some MCP setups).
    • A browser_open, open_url, or similar URL-opening tool — pass the URL.
    • Cursor / Codex CLI / others may not expose a preview tool to the agent. In that case, just print the URL and tell the user how to open it (their browser, their IDE's built-in browser pane, etc.).
  4. Do not assume any specific preview tool exists. Inspect the tools available to you in the current session. If one matches the description above, use it. If none does, fall back to step 2 (print the URL prominently).

The stream stays alive until npx serve-sim --kill. Multiple clients (the host's preview + the user's browser + a tunnel) can read the same URL simultaneously.

See references/workflows.md workflow "Show the simulator stream in the host's preview" for the full recipe.

Workflows

For complete end-to-end recipes (UI automation, camera testing, accessibility-driven taps, deep-link flows, preview handoff), see references/workflows.md. The reference covers the patterns documented in serve-sim's own AGENTS.md.

Cleanup

Always stop helpers when finished, unless the user explicitly wants them to keep running:

npx serve-sim --kill            # stop all
npx serve-sim --kill "iPhone 16 Pro"  # stop one

Orphan helpers occupy ports 3200/3100 and prevent fresh starts.

Anti-patterns

  • Do not pass pixel coordinates. All coords are normalized 0..1. If the user gives pixel values, divide by the screen dimensions reported by GET /config.
  • Do not use gesture for plain taps. Use tap. See "Critical gotcha" above.
  • Do not assume npx serve-sim is already running. Verify with --list or by checking $TMPDIR/serve-sim/server-{udid}.json. If absent, start it explicitly.
  • Do not skip the prerequisites check on the first invocation in a session. Wrong macOS version, missing Xcode CLI tools, or Node <18 produce confusing errors downstream.
  • Do not invent button names. Only these six are valid: home, swipe_home, app_switcher, lock, siri, side_button. See references/buttons-rotation.md for the source-of-truth list.
  • Do not parse the non-quiet human output. Use -q for JSON.
  • Do not leave camera helpers running across unrelated tasks. Stop them with npx serve-sim camera --stop-webcam when done.
  • Do not guess coordinates when an accessibility lookup returns no match. If you fetched the AX tree (e.g. GET /ax) to find a target element and the query returned no result, fail loudly — tapping a guessed spot is almost always worse than reporting "target not found" back to the user. See references/workflows.md workflow 1 for the guard pattern.

Reference index

  • references/gestures.md — exact gesture JSON shapes, edge values, multi-touch, drag/swipe recipes.
  • references/buttons-rotation.md — the six valid buttons and the four orientations, with behavioral notes.
  • references/camera.md — synthetic camera injection: placeholder, file, webcam, mirror modes, hot-swap.
  • references/permissions.md — granting/revoking app privacy permissions, including push notifications.
  • references/ca-debug.md — the five CoreAnimation debug flags and when each one helps.
  • references/endpoints.md — HTTP and WebSocket endpoints for agents that bypass the CLI.
  • references/workflows.md — end-to-end recipes for UI automation, camera testing, deep-link flows.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: serve-sim](https://darkplay.ru/ai/skills/serve-sim-serve-sim)

Похожие скиллы и другие разделы каталога

Похожие скиллы в категории «Мобильные»

Та же категория — сравните, что ещё подойдёт под вашу задачу.

edge-to-edgeandroid · Навык для миграции приложения Jetpack Compose на адаптивный режим edge-to-edge.
10 634 ★
xcodebuildmcpgetsentry · Официальный навык для XcodeBuildMCP. Используется при работе с…
6 585 ★
agent-devicecallstack · Автоматизирует работу с приложениями на платформах Apple (iOS, tvOS, macOS) и…
5 436 ★
expo-dev-clientexpo · Сборка и раздача dev-клиентов Expo локально или через TestFlight
4 186 ★
swiftui-performance-auditDimillian · Аудит и оптимизация производительности SwiftUI: рендеринг, скроллинг, CPU/память.
4 029 ★
swiftui-expert-skillAvdLee · Практики SwiftUI для iOS/macOS: состояние, @Observable, композиция, производительность.
3 931 ★
react-native-testingcallstack · Тесты компонентов React Native на RNTL v13–v14: рендер, запросы, матчеры, userEvent…
3 430 ★
argent-android-emulator-setupsoftware-mansion · Настройка и подключение к эмулятору Android через MCP-инструменты argent.
3 206 ★
flutter-apply-architecture-best-practicesflutter · Архитектура Flutter-приложения по слоям (UI, логика, данные) для новых проектов и…
3 190 ★
shadcn-ui-flutternank1ro · Библиотека Flutter UI в духе shadcn/ui: кнопки, карточки, формы и другое.
2 852 ★
Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

React Build Resolveraffaan-m · Чинит сборки React в Vite, webpack, Next.js и других: JSX, гидратация, типы.
225 587 ★
React Revieweraffaan-m · Ревьюер React/JSX: хуки, производительность, границы компонентов и безопасность.
225 587 ★
open-designnexu-io · MCP-сервер Open Design (stdio). 139 навыков и инструменты для проектов, файлов и…
108 160 ★
MCP Memory Server (official)modelcontextprotocol · Эталонный сервер памяти на графе знаний из официального репозитория MCP-серверов.
88 019 ★
aikidoanthropics · Сканирование безопасности Aikido для Claude Code — обнаружение уязвимостей SAST, секретов…
100 комп.
airtableanthropics · Airtable — слой базы данных и операций для ваших агентов в продукте, маркетинге…
100 комп.
airwallex-agentosanthropics · Глобальная финансовая инфраструктура Airwallex в Claude. Управляйте действиями по счёту…
100 комп.
amd-skillsanthropics · Проверенные навыки агентов AMD в одном плагине: обработка изображений и звука локальным…
100 комп.
apolloanthropics · Поиск клиентов, обогащение лидов, загрузка цепочек аутрича и аналитика продаж с Apollo.io…
100 комп.
apollo-skillsanthropics · Навыки агентов Apollo GraphQL для Claude Code — Apollo Client, Server, Federation…
100 комп.

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8