Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(node): Simulator node: live iOS and Android screens on the canvas, inline in run nodes (#1177)

Senzaiken1220195d99a8
diff --git a/CLAUDE.md b/CLAUDE.md
index b2fd7ff8f..b52ce3c19 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2141,6 +2141,129 @@ number: change the table in that one module, never in one emulator.
the dropdown). Add menus: **New view ▸ New run configuration**. Local projects only (disabled
with `RUN_SSH_HINT` in SSH projects; relay stub answers "managed on the host"); POSIX only
(refused on Windows). Server Edition: real. Kanban card modal: not yet. Mobile: N/A.
+- **simulator** (`SimulatorNode.tsx`, `core/simulator/`, `@shared/simulator`) — a live iOS simulator
+ screen on the canvas: click = tap, drag = swipe, wheel = a swipe, typing goes to the device (HID
+ keyboard usages from `KeyboardEvent.code`; ⌘-chords stay with nodeterm), Home / Lock buttons, a
+ device picker with Boot, and a Cover/Inner screen choice on foldables. DeviceHub (Xcode 27's
+ replacement for Simulator.app) cannot be embedded — it exposes only a `devices://` URL scheme and
+ macOS has no cross-app window embedding — so the node draws the device itself through
+ `nt-simbridge`, a small Swift helper whose SOURCE ships in `simbridge-source.ts` and is compiled on
+ first use with `xcrun swiftc` into `<userData>/simulator-bridge/<hash>/` (hash = source + version +
+ Xcode build, so an Xcode update recompiles; MEASURED ~3 s). It uses Xcode's PRIVATE simulator
+ frameworks (CoreSimulator / SimulatorKit — what DeviceHub uses), resolved at RUNTIME (dlopen /
+ NSClassFromString / dlsym) so a moved symbol fails with a sentence, never a link-time crash; the
+ Indigo HID message layout follows facebook/idb (MIT). Rules a refactor must keep, all MEASURED on
+ Xcode 27: (1) frames are the display's IOSurface, encoded only when its seed changes (0 cost while
+ still; ~19–30 fps while moving; first frame ~0.4 s); (2) a device can have SEVERAL main-class
+ displays — a foldable ("iPhone Duo") has an inner and a cover screen and only one is lit — so the
+ helper shows the lit one and follows a fold (switches when the shown one is still and another just
+ changed), with a manual pin; (3) touches go to the SHOWN screen's own digitizer, `0x40000000 |
+ screenID` (`screenProperties.screenID`): the generic main-screen target 0x32 reached neither screen
+ on the foldable; (4) Home/Lock are HID Consumer usages (Menu 0x40 / Power 0x30) to 0x32 — a Face ID
+ device ignores the legacy home-button source — falling back to the legacy source (0x33) when
+ refused; (5) the display state objects are ROCK proxies: no key-value coding, message primitives
+ through typed `objc_msgSend`. Input from the renderer is re-validated (`normalizeSimulatorInput`)
+ before it reaches the helper. A run node with a simulator device shows a 📱 button that opens (or
+ focuses) the Simulator node for it. **Desktop only** (iOS devices need macOS; Android ones run
+ everywhere): the add rows are disabled with `SIMULATOR_UNAVAILABLE_HINT` in a browser tab and
+ with `SIMULATOR_RELAY_HINT` in a relay tab (`simulatorRefusal`, one rule for the menu, the Dock,
+ the palette and `addSimulator`), and a Simulator node that reaches a relay tab anyway (it is in
+ the host's project file) shows that reason instead of streaming — a relay tab's project is the
+ host's, and the devices this renderer can reach are THIS machine's. `simulator:*` is also in
+ `HOST_ONLY_CHANNEL_PREFIXES`, so a relay peer is refused host-side. Kanban: not a card. Mobile: N/A.
+ **A device takes input from its FIRST HID client only** (MEASURED: a second client's touches are
+ dropped without an error). So the host runs ONE helper per device, shared by every node showing
+ it (`bridges` keyed by UDID, a late joiner replayed the last displays/ready). That is why the
+ Simulator node's OWN Boot is headless (`bootSimulator(id, { openWindow: false })`): a window
+ showing the device is a client too, and it took touch input away from the node. A run node's
+ Boot (`run:boot-device`) still opens Simulator.app as it always has — a user with no Simulator
+ node must still see the device. "Open in DeviceHub" (⋯ menu) says so in its tooltip.
+ **The ⋯ menu** (`simulatorMenu.tsx`, pure) is a complete map of DeviceHub's menus, from the
+ `…MenuItemProvider` names in Xcode 27's DeviceKit: what nodeterm can do runs — HID buttons
+ (Home/Lock/Side/Siri/Volume/Play-Pause) and rotation through the helper; everything else through
+ public `simctl` in `core/simulator/simulator-actions.ts` (appearance, text size, Increase
+ Contrast, location set/scenario/clear, status-bar overrides, shake and Face/Touch ID via the
+ simulator's own `notifyutil` notifications, Open URL, push, privacy, pasteboard sync, install,
+ add media, screenshot/recording, restart, erase) — and what it cannot is listed greyed out with
+ "(Not Supported)" and the reason (App Switcher: the edge-swipe gesture is not recognised from
+ outside DeviceHub; Action Button; Grayscale/Reduce Motion/Reduce Transparency/Liquid Glass: no
+ public command; tvOS/watchOS/visionOS controls; device management). Actions are re-validated
+ (`normalizeSimulatorAction`) and every argument is its own argv entry. All the simctl actions
+ were run live against an iOS 27 simulator; `simctl location list` is a TABLE
+ (`parseLocationScenarios` reads the first column).
+ **Edge swipes carry the panel edge they start on** (`touchEdge`, `TOUCH_EDGE_MARGIN` 2.5%):
+ iOS recognises its system edge gestures — the home swipe up from the bottom — from the Indigo
+ contact's edge field, not from where the finger lands. MEASURED (Xcode 27): without the flag a
+ swipe up from the very bottom only scrolled the app; 1 top / 2 left / 3 bottom / 4 right name
+ PHYSICAL panel edges (an iPad turned left went home with 2, turned right with 4; top inferred), so
+ the node computes the edge after mapping the touch to the panel and it holds for the whole
+ contact. A swipe down from the top worked without it.
+ **Inside a run node.** The screen, toolbar, ⋯ menu and input are one component, `SimulatorView`;
+ `SimulatorNode` is a thin box around it (title, close, resize handles, fit-to-screen), and a run
+ node mounts the same view under its control rows when `data.runSimulator` is present (persisted,
+ `normalizeInlineSimulatorConfig`: the device only — the panel FILLS the node, so resizing the
+ node scales the screen, letterboxed; no size of its own is stored). 📱 on every run node toggles that panel
+ (the run's device preselected when it is an iOS UDID or an Android emulator's adb serial,
+ `SimulatorDevice.serial`; else empty to pick); ⇱ splits it into a Simulator node carrying
+ `dockTo: <runNodeId>`, whose ⇲ (or the run node's 📱) docks it back. The inline stream is keyed
+ `<runNodeId>.sim`. While it is open the compact (terminal hidden) height fit stands down — the
+ node's size is the user's — and the run bar flexes to fill the node; opening grows the node by
+ `INLINE_SIM_HEIGHT`, closing hands that back. Inline there is no node of its own to snap to the
+ screen's shape, so Actual Size / Fit to Screen are greyed out there (pop out for those).
+ **The browser panel** (`@shared/run-preview`) is the same idea for a run whose result is a page:
+ there is NO choice — a node runs one thing, so the button shows the panel the run calls for (📱
+ or 🌐, `previewKindFor`), and an OPEN panel follows the run (switch the device to Chrome and the
+ simulator becomes the browser, and back) — a `chrome`/`msedge` launch configuration,
+ a Flutter web device, picked OR named by the configuration itself (`-d chrome` in its args — a
+ rule that read only the picker showed 📱 for exactly those runs), or a run with no device, i.e.
+ a dev server). `data.runBrowser` (persisted, http(s) only) holds the page: a browser
+ configuration's own `url` (its Run/Open now lands in this panel, or in a panel popped out of it,
+ instead of a separate browser node), else the URL picked out of the run's own output by
+ `localUrlFromOutput` (the newest local http(s) URL on a "served at / Local: / listening on" line;
+ DevTools / VM-service lines skipped; `0.0.0.0` opened as `localhost`), polled with `pty.capture`
+ only while the panel is open, the run is up and no page is known. A picked-out URL is marked
+ `auto` and re-read on the next run (the port may change); one the person navigated to is kept.
+ A Flutter `chrome`/`edge` run is EMBEDDED only when the configuration opts in
+ (`runConfig.embedBrowser: true`, ⋯ → "Show web inside this node", shown for a Flutter web run;
+ `embedsFlutterWeb` is the one rule for host and bar) — an existing configuration keeps Flutter's
+ own Chrome window. Opted in, `planLaunch` swaps the device for
+ `web-server` (`webServerDevice`, `PlanContext.webServer`) wherever it is named — the pick, `-d` /
+ `--device-id` / `-d=` in args or toolArgs, or Dart-Code's `deviceId` field (which used to be
+ dropped, not passed as `-d`) — because Chrome would open a window of Flutter's own while the web
+ server serves the same app to any browser and prints its URL; Run then opens the browser panel
+ by itself. ⇱ pops it into a browser node with `dockTo`; its ⇲
+ (`nodeterm:dock-preview`, shared with the Simulator node) or 🌐 docks it back. A run node holds
+ one panel at a time. The inline page is not part of the browser-node keep-alive pool, so a
+ project switch reloads it.
+ **Android virtual devices** use the same node (`core/simulator/android-*.ts`). A device id is
+ `avd:<name>` (the AVD name is stable; adb serials are not) in the same persisted `udid` field.
+ The picker lists every AVD read from files (`<avdHome>/<name>.ini` → `config.ini`; no
+ avdmanager, which needs a JDK), booted ones from the emulator's discovery files
+ (`…/avd/running/pid_<pid>.ini`, pid checked: a crash leaves the file). Boot runs
+ `emulator -avd <name> -no-window`, headless like iOS, logging to `<userData>/android-emulator/`.
+ Everything streams over the emulator's own gRPC interface, spoken with a hand-written protobuf
+ codec over `node:http2` (`android-grpc.ts`, no dependency), authenticated with the per-run
+ `grpc.token` from the discovery file. MEASURED (emulator 36.6.11): PNG frames fitted into a
+ SQUARE box (one box serves both orientations; width alone is ignored) run ~25 fps while moving
+ and send nothing while still; keys need the full USB usage (`0x70000 | usage`, a bare usage
+ types nothing); Home/Back/Recents/Power are W3C key names (`GoHome`, `GoBack`, `AppSwitch`,
+ `Power`); rotation is `setPhysicalModel` ROTATION z (90 = turned left) and frames then arrive
+ ALREADY TURNED while touches stay in PORTRAIT panel pixels — so the node does not turn an Android
+ picture (`picturePreRotated`) but maps touches with the same `displayToFramebuffer`. A rotation
+ of a portrait-locked app changes no guest pixels, so the stream sends nothing; the session takes
+ a `getScreenshot` after each rotation. Input is queued and sent one call at a time (drag points
+ coalesced) so it reaches the emulator in order. ⌘V sets the device clipboard (`setClipboard`)
+ and presses Ctrl+V. Menu actions use gRPC where it exists (battery, GPS, clipboard, fingerprint,
+ restart, shutdown, screenshots) and `adb -s emulator-<port>` otherwise (night mode, font scale,
+ demo-mode status bar, URLs, APK installs, media) — every `adb shell` argument single-quoted for
+ the DEVICE's shell. Not yet: screen recording, wipe data, foldables, the run node's 📱 for an
+ Android emulator. The node is offered in the desktop app on every OS (iOS devices are simply
+ absent off macOS); the Server Edition and relay tabs still refuse it. Install / Add Media accept a
+ POSIX or a Windows drive path (`C:\…`, `C:/…`; UNC refused), since the emulator runs on Windows too.
+ The emulator's discovery file is trusted only when every directory from the temp/runtime/home
+ base down and the file itself are ours (uid, no symlink, file opened `O_NOFOLLOW`), and a pid we
+ may not signal (EPERM) is another user's, not our emulator — `/tmp/android-<user>` can be created
+ by anyone first, and a planted `grpc.port` would receive every key typed into the device.
- **dino** (`DinoNode.tsx`) — a small self-contained T-Rex-style runner on a canvas (no PTY);
high score persists via `data.highScore`.
- **trigger** (`TriggerNode.tsx`) — a canvas-owned schedule (cron / interval / once) that
diff --git a/src/core/run-service.test.ts b/src/core/run-service.test.ts
index fab9377e6..7e6e2d6d9 100644
--- a/src/core/run-service.test.ts
+++ b/src/core/run-service.test.ts
@@ -6,12 +6,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { fakePlatform } from './platform-fake'
import { initPlatform, resetPlatformForTests } from './platform'
import {
+ bootSimulatorWith,
discoverProjects,
flutterPidFile,
launcherPath,
listEntries,
runStatus,
setWatch,
+ simctlSetupError,
signalRun,
startRun,
stopAllRunWatches,
@@ -315,3 +317,43 @@ describe('run-service', () => {
expect(out.match(/RELOAD/g)).toHaveLength(1)
})
})
+
+describe('bootSimulatorWith', () => {
+ const UDID = '12345678-1234-1234-1234-123456789ABC'
+ function recorder(fail?: string) {
+ const calls: string[] = []
+ const exec = async (file: string, args: string[]) => {
+ calls.push([file, ...args].join(' '))
+ if (fail) throw Object.assign(new Error('x'), { stderr: fail })
+ }
+ return { calls, exec }
+ }
+
+ it('opens Simulator.app after booting, as a run node always has', async () => {
+ const r = recorder()
+ expect(await bootSimulatorWith(UDID, {}, r.exec)).toBe(true)
+ expect(r.calls).toEqual([`/usr/bin/xcrun simctl boot ${UDID}`, '/usr/bin/open -a Simulator'])
+ })
+
+ it('stays headless when the caller is the Simulator node itself', async () => {
+ const r = recorder()
+ expect(await bootSimulatorWith(UDID, { openWindow: false }, r.exec)).toBe(true)
+ expect(r.calls).toEqual([`/usr/bin/xcrun simctl boot ${UDID}`])
+ })
+
+ it('refuses an id that is not a UDID, and a boot that failed', async () => {
+ const r = recorder()
+ expect(await bootSimulatorWith('../x', {}, r.exec)).toBe(false)
+ expect(r.calls).toEqual([])
+ expect(await bootSimulatorWith(UDID, {}, recorder('No such device').exec)).toBe(false)
+ })
+})
+
+describe('simctlSetupError', () => {
+ it('turns a missing or unselected Xcode into the fix, and nothing else', () => {
+ expect(simctlSetupError(Object.assign(new Error('spawn /usr/bin/xcrun ENOENT'), { code: 'ENOENT' }))).toMatch(/xcode-select --switch/)
+ expect(simctlSetupError({ message: 'Command failed', stderr: 'xcrun: error: unable to find utility "simctl", not a developer tool or in PATH' })).toMatch(/Install Xcode/)
+ expect(simctlSetupError({ message: 'Command failed', stderr: 'xcode-select: error: tool \'xcrun\' requires Xcode, but active developer directory is a command line tools instance' })).toMatch(/xcode-select/)
+ expect(simctlSetupError({ message: 'timeout' })).toBeNull()
+ })
+})
diff --git a/src/core/run-service.ts b/src/core/run-service.ts
index d9372559d..c4e0c34a7 100644
--- a/src/core/run-service.ts
+++ b/src/core/run-service.ts
@@ -31,7 +31,8 @@ import {
type RunEntriesResult,
type RunStartResult,
type RunStatus,
- type TaskDef
+ type TaskDef,
+ embedsFlutterWeb
} from '../shared/run-config'
import { shellSingleQuote } from '../shared/shell-quote'
import { findInLoginPath, resolveShellEnvVar, resolveShellPath } from './exec-path'
@@ -126,8 +127,24 @@ async function shellEnv(): Promise<NodeJS.ProcessEnv> {
return p ? { ...process.env, PATH: p } : process.env
}
-async function listSimulators(): Promise<RunDevice[]> {
- if (process.platform !== 'darwin') return []
+/** What `xcrun simctl` printed (or threw) when it could not run at all, as the fix the user needs.
+ * Null for any other failure: only a missing / unselected Xcode has an answer we can give. */
+export function simctlSetupError(e: unknown): string | null {
+ const err = e as { code?: unknown; message?: unknown; stderr?: unknown }
+ const text = `${String(err?.message ?? '')}\n${String(err?.stderr ?? '')}`.toLowerCase()
+ if (err?.code === 'ENOENT' || (text.includes('unable to find utility') && text.includes('simctl')) || text.includes('not a developer tool') || text.includes('requires xcode')) {
+ return 'Xcode\'s simulator tools are not available. Install Xcode, open it once, then select it with: sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer'
+ }
+ return null
+}
+
+export async function listSimulators(): Promise<RunDevice[]> {
+ return (await listSimulatorsChecked()).devices
+}
+
+/** `listSimulators`, plus why the list is empty when simctl itself could not run. */
+export async function listSimulatorsChecked(): Promise<{ devices: RunDevice[]; error?: string }> {
+ if (process.platform !== 'darwin') return { devices: [] }
try {
const { stdout } = await run('/usr/bin/xcrun', ['simctl', 'list', 'devices', 'available', '-j'], {
timeout: 15_000,
@@ -149,11 +166,14 @@ async function listSimulators(): Promise<RunDevice[]> {
})
}
}
- return out.sort((a, b) =>
- a.state === b.state ? a.name.localeCompare(b.name) : a.state === 'booted' ? -1 : 1
- )
- } catch {
- return []
+ return {
+ devices: out.sort((a, b) =>
+ a.state === b.state ? a.name.localeCompare(b.name) : a.state === 'booted' ? -1 : 1
+ )
+ }
+ } catch (e) {
+ const error = simctlSetupError(e)
+ return error ? { devices: [], error } : { devices: [] }
}
}
@@ -211,16 +231,41 @@ export async function listDevices(refresh = false): Promise<RunDevicesResult> {
return devicesInFlight
}
-export async function bootSimulator(udid: unknown): Promise<boolean> {
- if (process.platform !== 'darwin' || typeof udid !== 'string' || !SIMULATOR_UDID.test(udid)) return false
+type BootExec = (file: string, args: string[], opts: { timeout: number }) => Promise<unknown>
+
+export interface BootOptions {
+ /** Open Simulator.app once the device is booted — what a run node's Boot has always done, so a
+ * user without a Simulator node still sees the device. A Simulator node boots WITHOUT it: it is
+ * the device's screen itself, and MEASURED (Xcode 27) a device takes input only from its FIRST
+ * HID client, so a window showing it would take touch input away from the node. Default true. */
+ openWindow?: boolean
+}
+
+export async function bootSimulator(udid: unknown, opts: BootOptions = {}): Promise<boolean> {
+ if (process.platform !== 'darwin') return false
+ return bootSimulatorWith(udid, opts, run)
+}
+
+/** `bootSimulator` minus the platform gate, with the process runner injected (tests). */
+export async function bootSimulatorWith(udid: unknown, opts: BootOptions, exec: BootExec): Promise<boolean> {
+ return (await bootSimulatorReport(udid, opts, exec)) !== null
+}
+
+/** Boot, and say whether THIS call booted the device ('booted') or found it already running
+ * ('already-booted'); null = could not boot. Only a 'booted' device is one the caller may later shut
+ * down on the user's behalf — one that was already running belongs to whoever started it. */
+export async function bootSimulatorReport(udid: unknown, opts: BootOptions, exec: BootExec = run): Promise<'booted' | 'already-booted' | null> {
+ if (typeof udid !== 'string' || !SIMULATOR_UDID.test(udid)) return null
+ let result: 'booted' | 'already-booted' = 'booted'
try {
- await run('/usr/bin/xcrun', ['simctl', 'boot', udid], { timeout: 60_000 })
+ await exec('/usr/bin/xcrun', ['simctl', 'boot', udid], { timeout: 60_000 })
} catch (e) {
- if (!/current state: Booted/i.test(String((e as { stderr?: string }).stderr ?? (e as Error).message))) return false
+ if (!/current state: Booted/i.test(String((e as { stderr?: string }).stderr ?? (e as Error).message))) return null
+ result = 'already-booted'
}
devicesCache = null
- await openSimulatorApp()
- return true
+ if (opts.openWindow !== false) await openSimulatorApp(exec)
+ return result
}
/**
@@ -229,16 +274,16 @@ export async function bootSimulator(udid: unknown): Promise<boolean> {
* "Unable to find application named 'Simulator'") the bundle inside the active Xcode is tried. A
* machine with neither runs its simulators headless, which is fine: the app runs either way.
*/
-async function openSimulatorApp(): Promise<void> {
+async function openSimulatorApp(exec: BootExec): Promise<void> {
try {
- await run('/usr/bin/open', ['-a', 'Simulator'], { timeout: 15_000 })
+ await exec('/usr/bin/open', ['-a', 'Simulator'], { timeout: 15_000 })
return
} catch {
/* try the active Xcode's own copy */
}
try {
- const { stdout } = await run('/usr/bin/xcode-select', ['-p'], { timeout: 5_000 })
- await run('/usr/bin/open', [path.join(stdout.trim(), 'Applications', 'Simulator.app')], { timeout: 15_000 })
+ const { stdout } = (await exec('/usr/bin/xcode-select', ['-p'], { timeout: 5_000 })) as { stdout: string }
+ await exec('/usr/bin/open', [path.join(String(stdout).trim(), 'Applications', 'Simulator.app')], { timeout: 15_000 })
} catch {
/* headless simulators — nothing to show */
}
@@ -460,6 +505,7 @@ export async function startRun(nodeId: unknown, rawConfig: unknown, rawOpts?: un
pythonPath,
deviceId: config.deviceId,
extraArgs: config.extraArgs,
+ webServer: embedsFlutterWeb(config),
flutterPidFile: flutterPidFile(nodeId),
tasks
}, { attach, debugUrl })
diff --git a/src/core/simulator/android-actions.ts b/src/core/simulator/android-actions.ts
new file mode 100644
index 000000000..b7102b3b6
--- /dev/null
+++ b/src/core/simulator/android-actions.ts
@@ -0,0 +1,177 @@
+import { execFile } from 'node:child_process'
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { shellSingleQuote } from '../../shared/shell-quote'
+import type {
+ SimulatorAction,
+ SimulatorActionResult,
+ SimulatorCaptureTarget,
+ SimulatorDeviceState
+} from '../../shared/simulator'
+import { androidUnary } from './android-bridge'
+import {
+ BATTERY_CHARGING,
+ BATTERY_DISCHARGING,
+ BATTERY_FULL,
+ CHARGER_AC,
+ CHARGER_NONE,
+ IMAGE_PNG,
+ VM_RESET,
+ batteryState,
+ clipData,
+ decodeClipText,
+ decodeImage,
+ fingerprint,
+ gpsState,
+ imageFormat,
+ vmRunState
+} from './android-grpc'
+import { adb, findRunning, waitForBootCompleted } from './android-sdk'
+import { captureDir, errorText, safeName, stamp } from './simulator-actions'
+
+/**
+ * The ⋯ menu's actions on an Android virtual device. Whatever the emulator's gRPC interface offers
+ * goes over it (battery, location, clipboard, fingerprint, restart, screenshots); the rest through
+ * `adb` on the emulator's own serial (night mode, text size, status-bar demo mode, URLs, installs,
+ * media). Every `adb shell` argument is single-quoted for the DEVICE's shell: adb joins them into
+ * one command line that sh on the device parses again.
+ */
+
+const run = promisify(execFile)
+
+/** The font scales Android's own Settings → Display size and text slider offers. */
+const FONT_SCALES = [0.85, 1, 1.15, 1.3, 1.5, 1.8, 2]
+
+async function runningSerial(avd: string): Promise<string> {
+ const r = await findRunning(avd)
+ if (!r?.serial) throw new Error('This Android device is not running.')
+ return r.serial
+}
+
+async function serialOf(avd: string): Promise<string> {
+ const serial = await runningSerial(avd)
+ // Every caller goes on to `adb shell`, which needs Android itself up, not just the emulator.
+ await waitForBootCompleted(() => adb(serial, ['shell', 'getprop', 'sys.boot_completed'], 10_000))
+ return serial
+}
+
+const sh = (serial: string, cmd: string, timeout?: number) => adb(serial, ['shell', cmd], timeout)
+
+export async function runAndroidAction(avd: string, a: SimulatorAction): Promise<SimulatorActionResult> {
+ try {
+ return await perform(avd, a)
+ } catch (e) {
+ return { ok: false, error: errorText(e) }
+ }
+}
+
+async function perform(avd: string, a: SimulatorAction): Promise<SimulatorActionResult> {
+ switch (a.a) {
+ case 'appearance':
+ await sh(await serialOf(avd), `cmd uimode night ${a.value === 'dark' ? 'yes' : 'no'}`)
+ return { ok: true }
+ case 'content-size': {
+ const serial = await serialOf(avd)
+ const now = Number((await sh(serial, 'settings get system font_scale')).trim()) || 1
+ const at = FONT_SCALES.reduce((best, v, i) => (Math.abs(v - now) < Math.abs(FONT_SCALES[best] - now) ? i : best), 1)
+ const next = FONT_SCALES[Math.min(FONT_SCALES.length - 1, Math.max(0, at + (a.value === 'increment' ? 1 : -1)))]
+ await sh(serial, `settings put system font_scale ${next}`)
+ return { ok: true, message: `Text size ${Math.round(next * 100)}%` }
+ }
+ case 'location-set':
+ await androidUnary(avd, 'setGps', gpsState(a.lat, a.lon))
+ return { ok: true, message: `Location set to ${a.lat.toFixed(4)}, ${a.lon.toFixed(4)}` }
+ case 'status-bar': {
+ if (a.preset === 'battery') {
+ const status = a.batteryState === 'charged' ? BATTERY_FULL : a.batteryState === 'charging' ? BATTERY_CHARGING : BATTERY_DISCHARGING
+ await androidUnary(avd, 'setBattery', batteryState(a.batteryLevel, status, a.batteryState === 'discharging' ? CHARGER_NONE : CHARGER_AC))
+ return { ok: true }
+ }
+ const serial = await serialOf(avd)
+ if (a.preset === 'clear') {
+ await sh(serial, "am broadcast -a com.android.systemui.demo -e command exit")
+ return { ok: true }
+ }
+ // System UI demo mode: the status bar Android's own screenshots use.
+ const demo = (args: string) => sh(serial, `am broadcast -a com.android.systemui.demo -e command ${args}`)
+ await sh(serial, 'settings put global sysui_demo_allowed 1')
+ await demo('enter')
+ await demo('clock -e hhmm 0941')
+ await demo('battery -e level 100 -e plugged false')
+ await demo('network -e wifi show -e level 4 -e mobile show -e datatype none -e level 4')
+ await demo('notifications -e visible false')
+ return { ok: true }
+ }
+ case 'biometric': {
+ if (a.kind !== 'touch' || (a.op !== 'match' && a.op !== 'nomatch')) return { ok: false, error: 'Not available on Android.' }
+ // Finger 1 is the one Android's fingerprint setup enrolls on an emulator; any other is unknown.
+ const id = a.op === 'match' ? 1 : 9
+ await androidUnary(avd, 'sendFingerprint', fingerprint(true, id))
+ await new Promise((r) => setTimeout(r, 250))
+ await androidUnary(avd, 'sendFingerprint', fingerprint(false, id))
+ return { ok: true }
+ }
+ case 'open-url':
+ await sh(await serialOf(avd), `am start -a android.intent.action.VIEW -d ${shellSingleQuote(a.url)}`)
+ return { ok: true }
+ case 'install': {
+ if (!/\.apks?$/i.test(a.path)) return { ok: false, error: 'Pick an .apk file to install.' }
+ await adb(await serialOf(avd), ['install', '-r', a.path], 300_000)
+ return { ok: true, message: `Installed ${path.basename(a.path)}` }
+ }
+ case 'add-media': {
+ const serial = await serialOf(avd)
+ for (const p of a.paths) {
+ const name = safeName(path.basename(p).replace(/\.[^.]+$/, '')) + path.extname(p).toLowerCase()
+ const remote = `/sdcard/Pictures/${name}`
+ await adb(serial, ['push', p, remote], 300_000)
+ await sh(serial, `am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d ${shellSingleQuote(`file://${remote}`)}`)
+ }
+ return { ok: true, message: a.paths.length === 1 ? 'Added to Pictures' : `Added ${a.paths.length} files to Pictures` }
+ }
+ case 'clipboard-set':
+ await androidUnary(avd, 'setClipboard', clipData(a.text))
+ return { ok: true }
+ case 'pasteboard':
+ if (a.dir === 'to-mac') {
+ const text = decodeClipText(await androidUnary(avd, 'getClipboard', Buffer.alloc(0)))
+ return { ok: true, text, message: text ? 'Copied the device clipboard' : 'The device clipboard is empty' }
+ }
+ return { ok: false, error: 'Paste with ⌘V while the screen has focus.' }
+ case 'restart':
+ await androidUnary(avd, 'setVmState', vmRunState(VM_RESET))
+ return { ok: true, message: 'Restarting…' }
+ default:
+ return { ok: false, error: 'Not available on Android.' }
+ }
+}
+
+export async function readAndroidState(avd: string): Promise<SimulatorDeviceState> {
+ try {
+ // The menu's ✓ marks: read now or not at all — never held behind a boot wait.
+ const out = await sh(await runningSerial(avd), 'cmd uimode night', 5_000)
+ const m = /Night mode:\s*(yes|no)/i.exec(out)
+ return m ? { appearance: m[1].toLowerCase() === 'yes' ? 'dark' : 'light' } : {}
+ } catch {
+ return {}
+ }
+}
+
+/** A full-resolution screenshot, as it is shown (already turned with the device). */
+export async function androidScreenshot(avd: string, target: SimulatorCaptureTarget, name: string): Promise<SimulatorActionResult & { path?: string }> {
+ try {
+ const img = decodeImage(await androidUnary(avd, 'getScreenshot', imageFormat(IMAGE_PNG), 30_000))
+ if (!img) return { ok: false, error: 'The emulator sent no picture.' }
+ const file = path.join(await captureDir(target === 'desktop' ? 'desktop' : 'canvas'), `Android Screenshot - ${safeName(name)} - ${stamp()}.png`)
+ await writeFile(file, img.image)
+ if (target === 'clipboard') {
+ if (process.platform !== 'darwin') return { ok: false, error: 'Copying a screenshot needs macOS; it was saved instead.' }
+ await run('/usr/bin/osascript', ['-e', `set the clipboard to (read (POSIX file ${JSON.stringify(file)}) as «class PNGf»)`], { timeout: 15_000 })
+ return { ok: true, message: 'Screenshot copied to the clipboard' }
+ }
+ return { ok: true, path: file, message: target === 'desktop' ? 'Screenshot saved to the Desktop' : undefined }
+ } catch (e) {
+ return { ok: false, error: errorText(e) }
+ }
+}
diff --git a/src/core/simulator/android-bridge.test.ts b/src/core/simulator/android-bridge.test.ts
new file mode 100644
index 000000000..d59445e88
--- /dev/null
+++ b/src/core/simulator/android-bridge.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+import { inputCall } from './android-bridge'
+import { decodeFields, num } from './android-grpc'
+
+const s = { panel: { w: 1080, h: 2424 } }
+
+describe('Android input', () => {
+ it('turns a ratio into panel pixels', () => {
+ const [method, body] = inputCall(s, { t: 'down', x: 1, y: 0.5 })!
+ expect(method).toBe('sendTouch')
+ const t = decodeFields(decodeFields(body).get(1)![0] as Buffer)
+ expect([num(t, 1), num(t, 2), num(t, 4)]).toEqual([1079, 1212, 1024])
+ })
+
+ it('maps buttons to the emulator key names, and refuses iOS-only ones', () => {
+ const [, body] = inputCall(s, { t: 'button', name: 'back' })!
+ expect((decodeFields(body).get(4)![0] as Buffer).toString()).toBe('GoBack')
+ expect(inputCall(s, { t: 'button', name: 'siri' })).toBeNull()
+ })
+
+ it('rotates by the measured angles: portrait 0, turned left 90', () => {
+ const z = (value: number) => {
+ const [, body] = inputCall(s, { t: 'orientation', value })!
+ return (decodeFields(decodeFields(body).get(3)![0] as Buffer).get(1)![0] as Buffer).readFloatLE(8)
+ }
+ expect(z(1)).toBe(0)
+ expect(z(3)).toBe(90)
+ expect(z(4)).toBe(-90)
+ expect(z(2)).toBe(180)
+ })
+})
diff --git a/src/core/simulator/android-bridge.ts b/src/core/simulator/android-bridge.ts
new file mode 100644
index 000000000..f594174a0
--- /dev/null
+++ b/src/core/simulator/android-bridge.ts
@@ -0,0 +1,266 @@
+import {
+ ANDROID_BUTTON_KEYS,
+ ANDROID_ROTATION_Z,
+ type SimulatorFrame,
+ type SimulatorInput,
+ type SimulatorStatusEvent
+} from '../../shared/simulator'
+import {
+ EmulatorClient,
+ IMAGE_PNG,
+ KEY_DOWN,
+ KEY_PRESS,
+ KEY_UP,
+ decodeImage,
+ imageFormat,
+ namedKeyEvent,
+ rotationModel,
+ touchEvent,
+ usbKeyEvent
+} from './android-grpc'
+import { findRunning, listAvds } from './android-sdk'
+
+/**
+ * An Android virtual device on the canvas: frames streamed from the emulator's gRPC interface,
+ * touches / keys / buttons / rotation sent back over the same connection. The Android twin of the
+ * iOS helper in simulator-service.ts, behind the same node-facing events.
+ *
+ * MEASURED (emulator 36.6.11, Pixel 9, macOS): PNG frames fitted into a 1616-pixel box run at about
+ * 25 fps while the screen moves and cost nothing while it is still (the stream sends a frame only on
+ * change). The requested size is a bounding box the frame is fitted into, so a SQUARE box serves
+ * both orientations and a rotation never needs a new stream.
+ */
+
+/** The shortest side frames are scaled to (the iOS helper's is 900 at JPEG; PNG costs more). */
+const FRAME_SHORT_SIDE = 720
+const RETRY_MS = 1000
+const MAX_RETRIES = 30
+
+export interface AndroidHooks {
+ frame(nodeId: string, f: SimulatorFrame): void
+ status(nodeId: string, e: SimulatorStatusEvent): void
+}
+
+interface Session {
+ avd: string
+ nodes: Set<string>
+ client: EmulatorClient | null
+ cancelStream: (() => void) | null
+ /** Portrait panel size in pixels: touches are sent in this space. */
+ panel: { w: number; h: number }
+ stopping: boolean
+ ready: boolean
+ displays: SimulatorStatusEvent | null
+ retries: number
+ /** Inputs wait here so they reach the emulator in order, one call at a time. */
+ queue: SimulatorInput[]
+ sending: boolean
+ hooks: AndroidHooks
+ /** The square box frames are fitted into (see the header). */
+ box: number
+}
+
+const sessions = new Map<string, Session>()
+const nodeAvd = new Map<string, string>()
+
+export function androidNodeAvd(nodeId: string): string | undefined {
+ return nodeAvd.get(nodeId)
+}
+
+export async function startAndroid(nodeId: string, avd: string, hooks: AndroidHooks): Promise<{ ok: true } | { ok: false; error: string }> {
+ const live = sessions.get(avd)
+ if (live && !live.stopping) {
+ live.nodes.add(nodeId)
+ nodeAvd.set(nodeId, avd)
+ if (live.displays) hooks.status(nodeId, live.displays)
+ if (live.ready) hooks.status(nodeId, { kind: 'ready' })
+ return { ok: true }
+ }
+ const running = await findRunning(avd)
+ if (!running?.endpoint) return { ok: false, error: 'This Android device is not running — Boot it to see its screen.' }
+ const info = (await listAvds()).find((a) => a.name === avd)
+ const w = info?.lcdWidth ?? 1080
+ const h = info?.lcdHeight ?? 2400
+ const panel = { w: Math.min(w, h), h: Math.max(w, h) }
+ const s: Session = {
+ avd,
+ nodes: new Set([nodeId]),
+ client: null,
+ cancelStream: null,
+ panel,
+ stopping: false,
+ ready: false,
+ displays: {
+ kind: 'displays',
+ displays: [{ index: 0, width: panel.w, height: panel.h, name: 'Screen', screenID: 0, ...(info?.density ? { scale: info.density / 160 } : {}) }],
+ active: 0,
+ pinned: false
+ },
+ retries: 0,
+ queue: [],
+ sending: false,
+ hooks,
+ box: Math.round(panel.h * Math.min(1, FRAME_SHORT_SIDE / panel.w))
+ }
+ sessions.set(avd, s)
+ nodeAvd.set(nodeId, avd)
+ hooks.status(nodeId, s.displays!)
+ connect(s, running.endpoint, hooks)
+ return { ok: true }
+}
+
+function each(s: Session, fn: (id: string) => void): void {
+ for (const id of s.nodes) fn(id)
+}
+
+function connect(s: Session, endpoint: { port: number; token: string }, hooks: AndroidHooks): void {
+ const client = new EmulatorClient(endpoint)
+ s.client = client
+ s.cancelStream = client.stream(
+ 'streamScreenshot',
+ imageFormat(IMAGE_PNG, s.box, s.box),
+ (msg) => {
+ s.retries = 0
+ if (!s.ready) {
+ s.ready = true
+ each(s, (id) => hooks.status(id, { kind: 'ready' }))
+ }
+ emitImage(s, msg)
+ },
+ (err) => {
+ if (s.stopping || sessions.get(s.avd) !== s) return
+ client.close()
+ // The emulator restarting (Restart) or still coming up closes the stream: reconnect while it
+ // is running, and say why once it is gone.
+ setTimeout(() => void reconnect(s, hooks, err), RETRY_MS)
+ }
+ )
+}
+
+function emitImage(s: Session, msg: Buffer): void {
+ const img = decodeImage(msg)
+ if (!img || !img.width || !img.height) return
+ const frame: SimulatorFrame = { width: img.width, height: img.height, display: 0, jpeg: new Uint8Array(img.image), mime: 'image/png' }
+ each(s, (id) => s.hooks.frame(id, frame))
+}
+
+/**
+ * One frame taken on demand. MEASURED: the stream sends a frame only when the guest's screen
+ * changes, and turning a device whose app stays portrait (the launcher) changes nothing there — the
+ * emulator turns the picture, not the guest — so after a rotation no frame would come until
+ * something moved. Two shots, because the emulator applies the rotation a moment after the call.
+ */
+function refreshAfterRotation(s: Session): void {
+ for (const delay of [350, 1200]) {
+ setTimeout(() => {
+ if (s.stopping || sessions.get(s.avd) !== s || !s.client || s.client.isClosed) return
+ void s.client
+ .unary('getScreenshot', imageFormat(IMAGE_PNG, s.box, s.box), 10_000)
+ .then((msg) => emitImage(s, msg))
+ .catch(() => undefined)
+ }, delay)
+ }
+}
+
+async function reconnect(s: Session, hooks: AndroidHooks, err?: Error): Promise<void> {
+ if (s.stopping || sessions.get(s.avd) !== s) return
+ const running = await findRunning(s.avd)
+ if (running?.endpoint && s.retries++ < MAX_RETRIES) {
+ connect(s, running.endpoint, hooks)
+ return
+ }
+ sessions.delete(s.avd)
+ const message = running ? `Lost the emulator's screen${err ? `: ${err.message}` : '.'}` : 'The emulator stopped.'
+ each(s, (id) => {
+ hooks.status(id, { kind: 'error', code: 'stream', message })
+ hooks.status(id, { kind: 'exited', code: null, signal: null })
+ if (nodeAvd.get(id) === s.avd) nodeAvd.delete(id)
+ })
+}
+
+export function stopAndroid(nodeId: string): void {
+ const avd = nodeAvd.get(nodeId)
+ nodeAvd.delete(nodeId)
+ const s = avd ? sessions.get(avd) : undefined
+ if (!s) return
+ s.nodes.delete(nodeId)
+ if (s.nodes.size > 0) return
+ s.stopping = true
+ sessions.delete(s.avd)
+ s.cancelStream?.()
+ s.client?.close()
+}
+
+export function stopAllAndroid(): void {
+ for (const id of [...nodeAvd.keys()]) stopAndroid(id)
+}
+
+/** Queue one input. A drag point still waiting is replaced by a newer one — only where the finger
+ * is NOW matters — while downs, ups and keys are never dropped. */
+export function sendAndroidInput(nodeId: string, cmd: SimulatorInput): boolean {
+ const avd = nodeAvd.get(nodeId)
+ const s = avd ? sessions.get(avd) : undefined
+ if (!s || !s.client || s.client.isClosed) return false
+ const last = s.queue[s.queue.length - 1]
+ if (cmd.t === 'move' && last?.t === 'move') s.queue[s.queue.length - 1] = cmd
+ else s.queue.push(cmd)
+ if (s.queue.length > 256) s.queue.splice(0, s.queue.length - 256)
+ void drain(s)
+ return true
+}
+
+async function drain(s: Session): Promise<void> {
+ if (s.sending) return
+ s.sending = true
+ try {
+ while (s.queue.length && s.client && !s.client.isClosed) {
+ const cmd = s.queue.shift()!
+ const call = inputCall(s, cmd)
+ if (!call) continue
+ const ok = await s.client.unary(call[0], call[1], 5_000).then(
+ () => true,
+ () => false
+ )
+ if (ok && cmd.t === 'orientation') refreshAfterRotation(s)
+ }
+ } finally {
+ s.sending = false
+ }
+}
+
+/** The gRPC call one input becomes, or null when it has none on Android. */
+export function inputCall(s: Pick<Session, 'panel'>, cmd: SimulatorInput): [string, Buffer] | null {
+ switch (cmd.t) {
+ case 'down':
+ case 'move':
+ return ['sendTouch', touchEvent(cmd.x * (s.panel.w - 1), cmd.y * (s.panel.h - 1), 1024)]
+ case 'up':
+ return ['sendTouch', touchEvent(cmd.x * (s.panel.w - 1), cmd.y * (s.panel.h - 1), 0)]
+ case 'key':
+ return ['sendKey', usbKeyEvent(cmd.usage, cmd.down ? KEY_DOWN : KEY_UP)]
+ case 'button': {
+ const key = ANDROID_BUTTON_KEYS[cmd.name]
+ return key ? ['sendKey', namedKeyEvent(key, KEY_PRESS)] : null
+ }
+ case 'orientation': {
+ const z = ANDROID_ROTATION_Z[cmd.value]
+ return z === undefined ? null : ['setPhysicalModel', rotationModel(z)]
+ }
+ default:
+ return null
+ }
+}
+
+/** One call on a running emulator, for the ⋯ menu (opens its own connection when no node shows it). */
+export async function androidUnary(avd: string, method: string, body: Buffer, timeoutMs = 15_000): Promise<Buffer> {
+ const live = sessions.get(avd)
+ if (live?.client && !live.client.isClosed) return live.client.unary(method, body, timeoutMs)
+ const running = await findRunning(avd)
+ if (!running?.endpoint) throw new Error('This Android device is not running.')
+ const client = new EmulatorClient(running.endpoint)
+ try {
+ return await client.unary(method, body, timeoutMs)
+ } finally {
+ client.close()
+ }
+}
diff --git a/src/core/simulator/android-grpc.test.ts b/src/core/simulator/android-grpc.test.ts
new file mode 100644
index 000000000..ba38be453
--- /dev/null
+++ b/src/core/simulator/android-grpc.test.ts
@@ -0,0 +1,155 @@
+import http2 from 'node:http2'
+import type { AddressInfo } from 'node:net'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ EmulatorClient,
+ decodeFields,
+ decodeImage,
+ fBytes,
+ fInt,
+ gpsState,
+ imageFormat,
+ messageReader,
+ num,
+ rotationModel,
+ touchEvent,
+ usbKeyEvent,
+ varint
+} from './android-grpc'
+
+describe('protobuf codec', () => {
+ it('encodes varints the way protobuf does', () => {
+ expect([...varint(1)]).toEqual([1])
+ expect([...varint(300)]).toEqual([0xac, 0x02])
+ // A negative int32 is ten bytes of two's complement.
+ expect(varint(-1).length).toBe(10)
+ })
+
+ it('round-trips nested messages', () => {
+ const img = Buffer.concat([fBytes(1, imageFormat(0, 540, 1212)), fBytes(4, Buffer.from('PNGDATA'))])
+ expect(decodeImage(img)).toEqual({ width: 540, height: 1212, image: Buffer.from('PNGDATA') })
+ })
+
+ it('sends a touch in panel pixels with pressure, and a lift as pressure 0', () => {
+ const down = decodeFields(decodeFields(touchEvent(540.4, 1200, 1024)).get(1)![0] as Buffer)
+ expect([num(down, 1), num(down, 2), num(down, 4)]).toEqual([540, 1200, 1024])
+ const up = decodeFields(decodeFields(touchEvent(0, 0, 0)).get(1)![0] as Buffer)
+ expect(num(up, 4)).toBe(0)
+ })
+
+ it('sends a key as the full USB usage (page 7), as the emulator needs', () => {
+ const f = decodeFields(usbKeyEvent(0x04, 1))
+ expect(num(f, 3)).toBe(0x70004)
+ expect(num(f, 2)).toBe(1)
+ })
+
+ it('encodes a rotation as three packed floats', () => {
+ const f = decodeFields(rotationModel(90))
+ expect(num(f, 1)).toBe(1)
+ const data = decodeFields(f.get(3)![0] as Buffer).get(1)![0] as Buffer
+ expect([data.readFloatLE(0), data.readFloatLE(4), data.readFloatLE(8)]).toEqual([0, 0, 90])
+ })
+
+ it('encodes GPS coordinates as doubles', () => {
+ const b = gpsState(37.5, -122.25)
+ // field 2, wire type 1 → key 0x11; field 3 → 0x19
+ expect(b[0]).toBe(0x11)
+ expect(b.readDoubleLE(1)).toBe(37.5)
+ expect(b[9]).toBe(0x19)
+ expect(b.readDoubleLE(10)).toBe(-122.25)
+ })
+
+ it('refuses a truncated message instead of reading past it', () => {
+ expect(() => decodeFields(Buffer.from([0x22, 0x05, 0x01]))).toThrow()
+ })
+
+ it('splits a body into gRPC messages across chunk boundaries', () => {
+ const got: string[] = []
+ const read = messageReader((m) => got.push(m.toString()))
+ const frame = (s: string) => {
+ const h = Buffer.alloc(5)
+ h.writeUInt32BE(s.length, 1)
+ return Buffer.concat([h, Buffer.from(s)])
+ }
+ const body = Buffer.concat([frame('one'), frame('two')])
+ expect(read(body.subarray(0, 6))).toBe(true)
+ expect(read(body.subarray(6))).toBe(true)
+ expect(got).toEqual(['one', 'two'])
+ expect(messageReader(() => undefined)(Buffer.from([1, 0, 0, 0, 0]))).toBe(false)
+ })
+
+ it('omits zero fields, as protobuf defaults', () => {
+ expect(fInt(3, 0).length).toBe(0)
+ })
+})
+
+describe('EmulatorClient', () => {
+ let server: http2.Http2Server | null = null
+ afterEach(() => {
+ server?.close()
+ server = null
+ })
+
+ function start(handler: (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, body: Buffer) => void): Promise<number> {
+ server = http2.createServer()
+ server.on('stream', (stream, headers) => {
+ const parts: Buffer[] = []
+ stream.on('data', (d: Buffer) => parts.push(d))
+ stream.on('end', () => handler(stream as http2.ServerHttp2Stream, headers, Buffer.concat(parts)))
+ })
+ return new Promise((r) => server!.listen(0, '127.0.0.1', () => r((server!.address() as AddressInfo).port)))
+ }
+
+ const frame = (msg: Buffer) => {
+ const h = Buffer.alloc(5)
+ h.writeUInt32BE(msg.length, 1)
+ return Buffer.concat([h, msg])
+ }
+
+ it('sends the bearer token and method, and resolves the reply', async () => {
+ let seen: http2.IncomingHttpHeaders = {}
+ const port = await start((stream, headers, body) => {
+ seen = headers
+ expect(body.subarray(5).toString()).toBe('ping')
+ stream.respond({ ':status': 200, 'content-type': 'application/grpc' }, { waitForTrailers: true })
+ stream.on('wantTrailers', () => stream.sendTrailers({ 'grpc-status': '0' }))
+ stream.end(frame(Buffer.from('pong')))
+ })
+ const c = new EmulatorClient({ port, token: 'secret-token' })
+ const reply = await c.unary('getStatus', Buffer.from('ping'))
+ c.close()
+ expect(reply.toString()).toBe('pong')
+ expect(seen.authorization).toBe('Bearer secret-token')
+ expect(seen[':path']).toBe('/android.emulation.control.EmulatorController/getStatus')
+ })
+
+ it('rejects with the gRPC status the emulator answers', async () => {
+ const port = await start((stream) => {
+ stream.respond({ ':status': 200, 'content-type': 'application/grpc', 'grpc-status': '16', 'grpc-message': 'bad%20token' }, { endStream: true })
+ })
+ const c = new EmulatorClient({ port, token: 'wrong-token' })
+ await expect(c.unary('getStatus', Buffer.alloc(0))).rejects.toMatchObject({ code: 16, message: 'bad token' })
+ c.close()
+ })
+
+ it('streams messages until the server ends, then calls onEnd once', async () => {
+ const port = await start((stream) => {
+ stream.respond({ ':status': 200, 'content-type': 'application/grpc' }, { waitForTrailers: true })
+ stream.on('wantTrailers', () => stream.sendTrailers({ 'grpc-status': '0' }))
+ stream.write(frame(Buffer.from('a')))
+ stream.end(frame(Buffer.from('b')))
+ })
+ const c = new EmulatorClient({ port, token: 'secret-token' })
+ const got: string[] = []
+ let ends = 0
+ await new Promise<void>((resolve) =>
+ c.stream('streamScreenshot', Buffer.alloc(0), (m) => got.push(m.toString()), () => {
+ ends++
+ resolve()
+ })
+ )
+ c.close()
+ expect(got).toEqual(['a', 'b'])
+ expect(ends).toBe(1)
+ })
+})
diff --git a/src/core/simulator/android-grpc.ts b/src/core/simulator/android-grpc.ts
new file mode 100644
index 000000000..defad1cf7
--- /dev/null
+++ b/src/core/simulator/android-grpc.ts
@@ -0,0 +1,365 @@
+import http2 from 'node:http2'
+
+/**
+ * The Android emulator's gRPC control interface (`android.emulation.control.EmulatorController`),
+ * spoken over plain HTTP/2 with a hand-written protobuf codec — the few messages the Simulator
+ * node needs do not justify a gRPC library. Field numbers come from the
+ * `emulator_controller.proto` the SDK ships in `<sdk>/emulator/lib/`.
+ *
+ * MEASURED (emulator 36.6.11, macOS): every emulator listens on 127.0.0.1 with a per-run bearer
+ * token it writes to its discovery file (`grpc.token`); the token grants the controller methods
+ * used here. A screenshot stream sends a frame only when the screen changed.
+ */
+
+// ── Protobuf: just enough of the wire format ───────────────────────────────────────────────────
+
+export function varint(n: number | bigint): Buffer {
+ let v = BigInt.asUintN(64, BigInt(n))
+ const out: number[] = []
+ do {
+ let byte = Number(v & 0x7fn)
+ v >>= 7n
+ if (v) byte |= 0x80
+ out.push(byte)
+ } while (v)
+ return Buffer.from(out)
+}
+
+/** A varint field (int32/uint32/enum/bool). Zero is the default and is omitted, as protobuf does. */
+export function fInt(field: number, n: number): Buffer {
+ return n === 0 ? Buffer.alloc(0) : Buffer.concat([varint(field << 3), varint(n)])
+}
+
+/** A length-delimited field (bytes, string, nested message). */
+export function fBytes(field: number, buf: Buffer): Buffer {
+ return Buffer.concat([varint((field << 3) | 2), varint(buf.length), buf])
+}
+
+export function fString(field: number, s: string): Buffer {
+ return fBytes(field, Buffer.from(s, 'utf8'))
+}
+
+/** A double field (wire type 1). */
+export function fDouble(field: number, v: number): Buffer {
+ const b = Buffer.alloc(8)
+ b.writeDoubleLE(v)
+ return Buffer.concat([varint((field << 3) | 1), b])
+}
+
+/** A packed repeated float field. */
+export function fFloats(field: number, values: readonly number[]): Buffer {
+ const b = Buffer.alloc(values.length * 4)
+ values.forEach((v, i) => b.writeFloatLE(v, i * 4))
+ return fBytes(field, b)
+}
+
+export type ProtoValue = bigint | Buffer
+
+/** Decode one message's top-level fields: field number → its values (varints as bigint, length-
+ * delimited as Buffer). Fixed 32/64-bit fields are skipped. Throws on a truncated message. */
+export function decodeFields(buf: Buffer): Map<number, ProtoValue[]> {
+ const out = new Map<number, ProtoValue[]>()
+ let i = 0
+ const readVarint = (): bigint => {
+ let v = 0n
+ let shift = 0n
+ for (;;) {
+ if (i >= buf.length) throw new Error('truncated protobuf')
+ const c = buf[i++]
+ v |= BigInt(c & 0x7f) << shift
+ if (!(c & 0x80)) return v
+ shift += 7n
+ if (shift > 70n) throw new Error('bad varint')
+ }
+ }
+ while (i < buf.length) {
+ const key = readVarint()
+ const field = Number(key >> 3n)
+ const type = Number(key & 7n)
+ let value: ProtoValue | null = null
+ if (type === 0) value = readVarint()
+ else if (type === 2) {
+ const len = Number(readVarint())
+ if (i + len > buf.length) throw new Error('truncated protobuf')
+ value = buf.subarray(i, i + len)
+ i += len
+ } else if (type === 1) i += 8
+ else if (type === 5) i += 4
+ else throw new Error(`unsupported wire type ${type}`)
+ if (i > buf.length) throw new Error('truncated protobuf')
+ if (value !== null) {
+ const list = out.get(field)
+ if (list) list.push(value)
+ else out.set(field, [value])
+ }
+ }
+ return out
+}
+
+export function num(fields: Map<number, ProtoValue[]>, field: number): number {
+ const v = fields.get(field)?.[0]
+ return typeof v === 'bigint' ? Number(v) : 0
+}
+
+export function bytes(fields: Map<number, ProtoValue[]>, field: number): Buffer | undefined {
+ const v = fields.get(field)?.[0]
+ return Buffer.isBuffer(v) ? v : undefined
+}
+
+// ── Messages ─────────────────────────────────────────────────────────────────────────────────────
+
+export const IMAGE_PNG = 0
+
+/** ImageFormat { format=1, width=3, height=4 }. Width and height must be sent together — MEASURED:
+ * a width alone is ignored and the full-resolution frame comes back. */
+export function imageFormat(format: number, width = 0, height = 0): Buffer {
+ return Buffer.concat([fInt(1, format), fInt(3, width), fInt(4, height)])
+}
+
+export interface EmulatorImage {
+ width: number
+ height: number
+ image: Buffer
+}
+
+/** Image { format=1 (ImageFormat { width=3, height=4 }), image=4 }. */
+export function decodeImage(msg: Buffer): EmulatorImage | null {
+ const f = decodeFields(msg)
+ const fmt = bytes(f, 1)
+ const image = bytes(f, 4)
+ if (!fmt || !image) return null
+ const ff = decodeFields(fmt)
+ return { width: num(ff, 3), height: num(ff, 4), image }
+}
+
+/** TouchEvent { touches=1: Touch { x=1, y=2, identifier=3, pressure=4 } }, in PORTRAIT panel pixels.
+ * MEASURED: touches are not rotated with the device — the same panel point whatever the rotation. */
+export function touchEvent(x: number, y: number, pressure: number): Buffer {
+ return fBytes(1, Buffer.concat([fInt(1, Math.round(x)), fInt(2, Math.round(y)), fInt(4, pressure)]))
+}
+
+export const KEY_DOWN = 0
+export const KEY_UP = 1
+export const KEY_PRESS = 2
+
+/** KeyboardEvent { codeType=1 (Usb=0), eventType=2, keyCode=3 }. MEASURED: the USB code is the
+ * full usage, page 7 in the high half (0x70004 = "a") — a bare usage types nothing. */
+export function usbKeyEvent(usage: number, eventType: number): Buffer {
+ return Buffer.concat([fInt(1, 0), fInt(2, eventType), fInt(3, 0x70000 | usage)])
+}
+
+/** KeyboardEvent { eventType=2, key=4 } — a W3C key name ("GoHome", "GoBack", "AppSwitch", "Power",
+ * "AudioVolumeUp"…), which the emulator maps to the Android key. */
+export function namedKeyEvent(key: string, eventType = KEY_PRESS): Buffer {
+ return Buffer.concat([fInt(2, eventType), fString(4, key)])
+}
+
+/** PhysicalModelValue { target=1 (ROTATION=1), value=3: ParameterValue { data=1 } }. The emulator
+ * turns the device (and its frames) by `z` degrees: 90 = turned left (counter-clockwise). */
+export function rotationModel(z: number): Buffer {
+ return Buffer.concat([fInt(1, 1), fBytes(3, fFloats(1, [0, 0, z]))])
+}
+
+/** GpsState { passiveUpdate=1, latitude=2, longitude=3, satellites=7 }. */
+export function gpsState(lat: number, lon: number): Buffer {
+ return Buffer.concat([fDouble(2, lat), fDouble(3, lon), fInt(7, 12)])
+}
+
+/** ClipData { text=1 }. */
+export function clipData(text: string): Buffer {
+ return text ? fString(1, text) : Buffer.alloc(0)
+}
+
+export function decodeClipText(msg: Buffer): string {
+ const v = bytes(decodeFields(msg), 1)
+ return v ? v.toString('utf8') : ''
+}
+
+export const BATTERY_CHARGING = 1
+export const BATTERY_DISCHARGING = 2
+export const BATTERY_FULL = 4
+export const CHARGER_NONE = 0
+export const CHARGER_AC = 1
+
+/** BatteryState { hasBattery=1, isPresent=2, charger=3, chargeLevel=4, status=6 }. */
+export function batteryState(level: number, status: number, charger: number): Buffer {
+ return Buffer.concat([fInt(1, 1), fInt(2, 1), fInt(3, charger), fInt(4, level), fInt(6, status)])
+}
+
+/** Fingerprint { isTouching=1, touchId=2 }. */
+export function fingerprint(touching: boolean, touchId: number): Buffer {
+ return Buffer.concat([fInt(1, touching ? 1 : 0), fInt(2, touchId)])
+}
+
+export const VM_SHUTDOWN = 5
+export const VM_RESET = 9
+
+export function vmRunState(state: number): Buffer {
+ return fInt(1, state)
+}
+
+// ── Transport ────────────────────────────────────────────────────────────────────────────────────
+
+const SERVICE = '/android.emulation.control.EmulatorController/'
+const MAX_MESSAGE = 32 * 1024 * 1024
+
+export class GrpcError extends Error {
+ constructor(
+ readonly code: number,
+ message: string
+ ) {
+ super(message)
+ }
+}
+
+function frame(msg: Buffer): Buffer {
+ const head = Buffer.alloc(5)
+ head.writeUInt32BE(msg.length, 1)
+ return Buffer.concat([head, msg])
+}
+
+/** Splits a gRPC response body into messages. Returns false on a malformed or oversized one. */
+export function messageReader(onMessage: (msg: Buffer) => void): (chunk: Buffer) => boolean {
+ let buf: Buffer = Buffer.alloc(0)
+ return (chunk) => {
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk
+ while (buf.length >= 5) {
+ if (buf[0] !== 0) return false // compressed messages were never asked for
+ const len = buf.readUInt32BE(1)
+ if (len > MAX_MESSAGE) return false
+ if (buf.length < 5 + len) break
+ onMessage(buf.subarray(5, 5 + len))
+ buf = buf.subarray(5 + len)
+ }
+ return true
+ }
+}
+
+export interface EmulatorEndpoint {
+ port: number
+ token: string
+}
+
+/** One HTTP/2 connection to an emulator, shared by every call. */
+export class EmulatorClient {
+ private session: http2.ClientHttp2Session
+ private closed = false
+
+ constructor(
+ private readonly endpoint: EmulatorEndpoint,
+ onClose?: () => void
+ ) {
+ this.session = http2.connect(`http://127.0.0.1:${endpoint.port}`)
+ this.session.on('error', () => undefined) // surfaced per call; 'close' follows
+ this.session.on('close', () => {
+ this.closed = true
+ onClose?.()
+ })
+ }
+
+ get isClosed(): boolean {
+ return this.closed || this.session.destroyed
+ }
+
+ private request(method: string): http2.ClientHttp2Stream {
+ return this.session.request({
+ ':method': 'POST',
+ ':path': SERVICE + method,
+ 'content-type': 'application/grpc',
+ te: 'trailers',
+ authorization: `Bearer ${this.endpoint.token}`
+ })
+ }
+
+ /** A unary call. Resolves with the response message (empty for google.protobuf.Empty). */
+ unary(method: string, body: Buffer, timeoutMs = 15_000): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ if (this.isClosed) return reject(new GrpcError(14, 'The emulator connection is closed.'))
+ const s = this.request(method)
+ let reply: Buffer = Buffer.alloc(0)
+ let failed = false
+ const read = messageReader((m) => (reply = Buffer.from(m)))
+ const timer = setTimeout(() => {
+ failed = true
+ s.close(http2.constants.NGHTTP2_CANCEL)
+ reject(new GrpcError(4, `${method} timed out.`))
+ }, timeoutMs)
+ s.on('data', (chunk: Buffer) => {
+ if (!read(chunk) && !failed) {
+ failed = true
+ s.close(http2.constants.NGHTTP2_CANCEL)
+ reject(new GrpcError(13, `${method}: unreadable reply.`))
+ }
+ })
+ const finish = (headers: http2.IncomingHttpHeaders) => {
+ if (failed) return
+ const status = Number(headers['grpc-status'] ?? 0)
+ if (status !== 0) {
+ failed = true
+ const msg = headers['grpc-message']
+ reject(new GrpcError(status, typeof msg === 'string' ? decodeURIComponent(msg) : `${method} failed (${status}).`))
+ }
+ }
+ s.on('response', (h) => {
+ if (h['grpc-status'] !== undefined) finish(h) // trailers-only reply
+ })
+ s.on('trailers', finish)
+ s.on('error', (e) => {
+ if (failed) return
+ failed = true
+ clearTimeout(timer)
+ reject(new GrpcError(14, e.message))
+ })
+ s.on('close', () => {
+ clearTimeout(timer)
+ if (!failed) resolve(reply)
+ })
+ s.end(frame(body))
+ })
+ }
+
+ /** A server-streaming call. `onEnd` runs once, with the error if it ended badly. */
+ stream(method: string, body: Buffer, onMessage: (msg: Buffer) => void, onEnd: (err?: Error) => void): () => void {
+ if (this.isClosed) {
+ queueMicrotask(() => onEnd(new GrpcError(14, 'The emulator connection is closed.')))
+ return () => undefined
+ }
+ const s = this.request(method)
+ let ended = false
+ let cancelled = false
+ const end = (err?: Error) => {
+ if (ended) return
+ ended = true
+ onEnd(cancelled ? undefined : err)
+ }
+ const read = messageReader(onMessage)
+ s.on('data', (chunk: Buffer) => {
+ if (!read(chunk)) {
+ end(new GrpcError(13, `${method}: unreadable message.`))
+ s.close(http2.constants.NGHTTP2_CANCEL)
+ }
+ })
+ const status = (h: http2.IncomingHttpHeaders) => {
+ const code = Number(h['grpc-status'] ?? 0)
+ if (code !== 0) {
+ const msg = h['grpc-message']
+ end(new GrpcError(code, typeof msg === 'string' ? decodeURIComponent(msg) : `${method} failed (${code}).`))
+ }
+ }
+ s.on('response', (h) => {
+ if (h['grpc-status'] !== undefined) status(h)
+ })
+ s.on('trailers', status)
+ s.on('error', (e) => end(new GrpcError(14, e.message)))
+ s.on('close', () => end())
+ s.end(frame(body))
+ return () => {
+ cancelled = true
+ if (!s.closed) s.close(http2.constants.NGHTTP2_CANCEL)
+ }
+ }
+
+ close(): void {
+ if (!this.session.destroyed) this.session.close()
+ }
+}
diff --git a/src/core/simulator/android-sdk.test.ts b/src/core/simulator/android-sdk.test.ts
new file mode 100644
index 000000000..bb70f50d1
--- /dev/null
+++ b/src/core/simulator/android-sdk.test.ts
@@ -0,0 +1,178 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { testTmpDir } from '../test-tmp'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ BOOT_NOT_COMPLETED_MESSAGE,
+ adbAt,
+ emulatorSpawnOptions,
+ firstSdkTool,
+ lastError,
+ parseDiscovery,
+ parseIni,
+ runningEmulators,
+ waitForBootCompleted
+} from './android-sdk'
+
+// A discovery file as emulator 36.6.11 writes it (token replaced).
+const DISCOVERY = `emulator.build=15507667
+avd.id=Pixel_9
+port.serial=5554
+port.adb=5555
+avd.name=Pixel 9
+emulator.version=36.6.11.0
+avd.dir=/Users/me/.android/avd/Pixel_9.avd
+grpc.token=AbCdEf0123456789xyz
+grpc.port=8554
+`
+
+describe('Android discovery', () => {
+ it('reads the AVD, adb serial and gRPC endpoint', () => {
+ expect(parseDiscovery(DISCOVERY, 4242)).toEqual({
+ avd: 'Pixel_9',
+ pid: 4242,
+ serial: 'emulator-5554',
+ endpoint: { port: 8554, token: 'AbCdEf0123456789xyz' }
+ })
+ })
+
+ it('has no endpoint without a token, and refuses an AVD name it could not use', () => {
+ expect(parseDiscovery(DISCOVERY.replace(/grpc\.token=.*\n/, ''), 1)?.endpoint).toBeUndefined()
+ expect(parseDiscovery(DISCOVERY.replace('avd.id=Pixel_9', 'avd.id=../etc'), 1)).toBeNull()
+ })
+
+ it('parses ini files, skipping comments', () => {
+ expect(parseIni('# c\nhw.lcd.width = 1080\n\nimage.sysdir.1=system-images/android-34/google_apis/arm64-v8a/\n')).toMatchObject({
+ 'hw.lcd.width': '1080',
+ 'image.sysdir.1': 'system-images/android-34/google_apis/arm64-v8a/'
+ })
+ })
+
+ it('picks the emulator log line that says why it stopped', () => {
+ const log = 'INFO | Android emulator version 36\nERROR | Running multiple emulators with the same AVD\nINFO | bye\n'
+ expect(lastError(log)).toBe('Running multiple emulators with the same AVD')
+ expect(lastError('INFO | only info\n')).toBe('INFO | only info')
+ })
+})
+
+// The Linux discovery dir sits under the shared temp dir, where another local user can create
+// `/tmp/android-<user>` first and plant a file whose grpc.port receives the user's keystrokes.
+describe.skipIf(process.platform === 'win32')('runningEmulators trust', () => {
+ const uid = process.getuid!()
+ let base = ''
+ afterEach(() => {
+ vi.restoreAllMocks()
+ if (base) rmSync(base, { recursive: true, force: true })
+ base = ''
+ })
+ function plant(): { dir: string; trustedBase: string } {
+ base = mkdtempSync(path.join(os.tmpdir(), 'nt-avd-'))
+ const dir = path.join(base, 'android-me', 'avd', 'running')
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(path.join(dir, `pid_${process.pid}.ini`), DISCOVERY)
+ return { dir, trustedBase: base }
+ }
+
+ it('reads a discovery file in a directory chain we own', async () => {
+ const found = await runningEmulators([plant()], uid)
+ expect(found.map((e) => e.endpoint?.port)).toEqual([8554])
+ })
+
+ it('ignores a directory chain owned by another user', async () => {
+ expect(await runningEmulators([plant()], uid + 1)).toEqual([])
+ })
+
+ it('ignores a symlinked component in the chain', async () => {
+ const real = plant()
+ const linked = path.join(base, 'android-link')
+ symlinkSync(path.join(base, 'android-me'), linked)
+ expect(await runningEmulators([{ dir: path.join(linked, 'avd', 'running'), trustedBase: base }], uid)).toEqual([])
+ expect(await runningEmulators([real], uid)).toHaveLength(1)
+ })
+
+ it('ignores a symlinked discovery file', async () => {
+ const d = plant()
+ const target = path.join(base, 'elsewhere.ini')
+ writeFileSync(target, DISCOVERY)
+ rmSync(path.join(d.dir, `pid_${process.pid}.ini`))
+ symlinkSync(target, path.join(d.dir, `pid_${process.pid}.ini`))
+ expect(await runningEmulators([d], uid)).toEqual([])
+ })
+
+ it("treats a pid we may not signal (EPERM) as not ours", async () => {
+ const d = plant()
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('EPERM'), { code: 'EPERM' })
+ })
+ expect(await runningEmulators([d], uid)).toEqual([])
+ })
+})
+
+describe('Android SDK tools', () => {
+ it('takes the tool from the first root that has it, not the first root that exists', async () => {
+ const has = new Set([path.join('/studio/sdk', 'emulator', 'emulator')])
+ const check = async (p: string) => has.has(p)
+ expect(await firstSdkTool(['/stale/sdk', '/studio/sdk'], ['emulator', 'emulator'], check)).toBe(path.join('/studio/sdk', 'emulator', 'emulator'))
+ expect(await firstSdkTool(['/stale/sdk'], ['platform-tools', 'adb'], check)).toBeNull()
+ })
+
+ it('never starts the emulator detached on Windows (it would open console windows)', () => {
+ expect(emulatorSpawnOptions('win32')).toEqual({ detached: false, windowsHide: true })
+ expect(emulatorSpawnOptions('darwin').detached).toBe(true)
+ expect(emulatorSpawnOptions('linux').detached).toBe(true)
+ })
+})
+
+describe('waiting for Android to finish booting', () => {
+ /** A fake adb: answers `-s <serial> shell getprop sys.boot_completed` from a counter file, empty
+ * until the Nth call, then "1"; records its argv. */
+ function fakeAdb(readyOnCall: number | null): { bin: string; argv: string } {
+ const dir = testTmpDir('nt-fake-adb-')
+ const bin = path.join(dir, 'adb')
+ const argv = path.join(dir, 'argv')
+ writeFileSync(
+ bin,
+ `#!/bin/sh
+printf '%s\\n' "$*" >> '${argv}'
+n=$(cat '${dir}/n' 2>/dev/null || echo 0); n=$((n + 1)); echo "$n" > '${dir}/n'
+${readyOnCall === null ? "echo ''" : `if [ "$n" -ge ${readyOnCall} ]; then echo 1; else echo ''; fi`}
+`,
+ { mode: 0o755 }
+ )
+ return { bin, argv }
+ }
+ const instant = { sleep: async () => undefined, pollMs: 1000 }
+
+ it.skipIf(process.platform === 'win32')('returns once the fake adb reports sys.boot_completed=1', async () => {
+ const { bin, argv } = fakeAdb(3)
+ await waitForBootCompleted(() => adbAt(bin, 'emulator-5554', ['shell', 'getprop', 'sys.boot_completed']), { ...instant, timeoutMs: 90_000 })
+ const calls = readFileSync(argv, 'utf8').trim().split('\n')
+ expect(calls).toEqual(Array(3).fill('-s emulator-5554 shell getprop sys.boot_completed'))
+ })
+
+ it.skipIf(process.platform === 'win32')('gives up with a plain sentence when Android never finishes', async () => {
+ const { bin } = fakeAdb(null)
+ let t = 0
+ await expect(
+ waitForBootCompleted(() => adbAt(bin, 'emulator-5554', ['shell', 'getprop', 'sys.boot_completed']), {
+ timeoutMs: 5_000,
+ pollMs: 1_000,
+ now: () => t,
+ sleep: async (ms) => {
+ t += ms
+ }
+ })
+ ).rejects.toThrow(BOOT_NOT_COMPLETED_MESSAGE)
+ })
+
+ it('treats a failing adb (device still offline) as not booted yet', async () => {
+ let calls = 0
+ await waitForBootCompleted(async () => {
+ calls++
+ if (calls < 3) throw new Error('error: device offline')
+ return '1\n'
+ }, instant)
+ expect(calls).toBe(3)
+ })
+})
diff --git a/src/core/simulator/android-sdk.ts b/src/core/simulator/android-sdk.ts
new file mode 100644
index 000000000..3167d6c82
--- /dev/null
+++ b/src/core/simulator/android-sdk.ts
@@ -0,0 +1,474 @@
+import { execFile, spawn } from 'node:child_process'
+import { constants as fsConstants } from 'node:fs'
+import { lstat, mkdir, open, readdir, stat } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { ANDROID_AVD_NAME, androidDeviceId, type SimulatorDevice } from '../../shared/simulator'
+import { findInLoginPath, resolveShellEnvVar } from '../exec-path'
+import { platform } from '../platform'
+import type { EmulatorEndpoint } from './android-grpc'
+
+/**
+ * Where the Android SDK is, which virtual devices (AVDs) it has, and which of them are running.
+ * Everything is read from files the SDK and the emulator write — nothing here asks `avdmanager`,
+ * which needs a JDK — and every answer degrades to "none" rather than a guess.
+ *
+ * MEASURED (emulator 36.6.11, macOS): a running emulator writes `pid_<pid>.ini` into its discovery
+ * directory, naming its AVD (`avd.id`), console port (`port.serial`, so adb's serial is
+ * `emulator-<port>`) and gRPC endpoint (`grpc.port`, `grpc.token`). The file can outlive a crashed
+ * emulator, so its pid is checked.
+ */
+
+const run = promisify(execFile)
+
+async function envVar(name: string): Promise<string | undefined> {
+ const v = (await resolveShellEnvVar(name).catch(() => null)) ?? process.env[name]
+ return v && path.isAbsolute(v) ? v : undefined
+}
+
+async function isDir(p: string): Promise<boolean> {
+ try {
+ return (await stat(p)).isDirectory()
+ } catch {
+ return false
+ }
+}
+
+async function isFile(p: string): Promise<boolean> {
+ try {
+ return (await stat(p)).isFile()
+ } catch {
+ return false
+ }
+}
+
+/** Every place the SDK may be, in order: ANDROID_HOME, ANDROID_SDK_ROOT, then where Android Studio
+ * installs it. */
+async function sdkRootCandidates(): Promise<string[]> {
+ const candidates = [await envVar('ANDROID_HOME'), await envVar('ANDROID_SDK_ROOT')]
+ const home = os.homedir()
+ if (process.platform === 'darwin') candidates.push(path.join(home, 'Library', 'Android', 'sdk'))
+ else if (process.platform === 'win32') {
+ const local = process.env.LOCALAPPDATA
+ if (local) candidates.push(path.join(local, 'Android', 'Sdk'))
+ } else candidates.push(path.join(home, 'Android', 'Sdk'))
+ return candidates.filter((c): c is string => !!c)
+}
+
+/** The SDK root: the first candidate that is a directory. */
+export async function androidSdkRoot(): Promise<string | null> {
+ for (const c of await sdkRootCandidates()) if (await isDir(c)) return c
+ return null
+}
+
+const exe = (name: string) => (process.platform === 'win32' ? `${name}.exe` : name)
+
+/** The first candidate root that HOLDS the tool: a stale ANDROID_HOME pointing at a half-installed SDK
+ * must not hide the complete one Android Studio installed. Pure over `isFile`, for tests. */
+export async function firstSdkTool(roots: string[], rel: string[], fileCheck: (p: string) => Promise<boolean> = isFile): Promise<string | null> {
+ for (const root of roots) {
+ const p = path.join(root, ...rel)
+ if (await fileCheck(p)) return p
+ }
+ return null
+}
+
+export async function emulatorBinary(): Promise<string | null> {
+ return (await firstSdkTool(await sdkRootCandidates(), ['emulator', exe('emulator')])) ?? findInLoginPath('emulator')
+}
+
+export async function adbBinary(): Promise<string | null> {
+ return (await firstSdkTool(await sdkRootCandidates(), ['platform-tools', exe('adb')])) ?? findInLoginPath('adb')
+}
+
+/** Where AVDs live, in avdmanager's own order of precedence. */
+export async function avdHome(): Promise<string> {
+ const explicit = await envVar('ANDROID_AVD_HOME')
+ if (explicit) return explicit
+ const user = await envVar('ANDROID_USER_HOME')
+ if (user) return path.join(user, 'avd')
+ const legacy = await envVar('ANDROID_SDK_HOME')
+ if (legacy) return path.join(legacy, '.android', 'avd')
+ return path.join(os.homedir(), '.android', 'avd')
+}
+
+/** `key=value` lines; later keys win, comments and blank lines skipped. */
+export function parseIni(text: string): Record<string, string> {
+ const out: Record<string, string> = Object.create(null)
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim()
+ if (!line || line.startsWith('#') || line.startsWith(';')) continue
+ const eq = line.indexOf('=')
+ if (eq <= 0) continue
+ out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim()
+ }
+ return out
+}
+
+/** A small regular file's text, or null. Checked and read through ONE open handle, so the file
+ * that passed the check is the file that is read (no swap in between). */
+async function readSmallFile(p: string, max: number): Promise<string | null> {
+ let h: Awaited<ReturnType<typeof open>> | null = null
+ try {
+ h = await open(p, 'r')
+ const s = await h.stat()
+ if (!s.isFile() || s.size > max) return null
+ return await h.readFile('utf8')
+ } catch {
+ return null
+ } finally {
+ await h?.close().catch(() => undefined)
+ }
+}
+
+async function readIni(p: string): Promise<Record<string, string> | null> {
+ const text = await readSmallFile(p, 256 * 1024)
+ return text === null ? null : parseIni(text)
+}
+
+export interface AvdInfo {
+ name: string
+ displayName: string
+ dir: string
+ /** "API 34", from the system image. */
+ os?: string
+ lcdWidth?: number
+ lcdHeight?: number
+ /** Dots per inch (hw.lcd.density): 160 is one pixel per point. */
+ density?: number
+}
+
+/** The installed AVDs: `<avdHome>/<name>.ini` points at the `.avd` folder holding `config.ini`. */
+export async function listAvds(): Promise<AvdInfo[]> {
+ const home = await avdHome()
+ let entries: string[]
+ try {
+ entries = await readdir(home)
+ } catch {
+ return []
+ }
+ const out: AvdInfo[] = []
+ for (const file of entries) {
+ if (!file.endsWith('.ini')) continue
+ const name = file.slice(0, -4)
+ if (!ANDROID_AVD_NAME.test(name)) continue
+ const pointer = await readIni(path.join(home, file))
+ if (!pointer) continue
+ const dir = pointer.path && path.isAbsolute(pointer.path) ? pointer.path : path.join(home, `${name}.avd`)
+ const config = await readIni(path.join(dir, 'config.ini'))
+ if (!config) continue
+ const api = /android-(\d+)/.exec(config['image.sysdir.1'] ?? pointer.target ?? '')?.[1]
+ const w = Number(config['hw.lcd.width'])
+ const h = Number(config['hw.lcd.height'])
+ const dpi = Number(config['hw.lcd.density'])
+ out.push({
+ name,
+ displayName: prettyName(cleanName(config['avd.ini.displayname']), name),
+ dir,
+ os: api ? `API ${api}` : undefined,
+ lcdWidth: Number.isInteger(w) && w > 0 ? w : undefined,
+ lcdHeight: Number.isInteger(h) && h > 0 ? h : undefined,
+ density: Number.isFinite(dpi) && dpi >= 80 && dpi <= 1000 ? dpi : undefined
+ })
+ }
+ return out.sort((a, b) => a.displayName.localeCompare(b.displayName))
+}
+
+/** The name Android Studio shows. An AVD made outside it often has its file name as display name
+ * ("Pixel_3a_API_34_extension_level_7_arm64-v8a"), so underscores become spaces there. */
+function prettyName(display: string | undefined, file: string): string {
+ return !display || display === file ? file.replace(/_/g, ' ') : display
+}
+
+// eslint-disable-next-line no-control-regex
+const CONTROL = /[\u0000-\u001f\u007f]/
+function cleanName(v: string | undefined): string | undefined {
+ if (!v) return undefined
+ const s = v.trim()
+ return s && s.length <= 120 && !CONTROL.test(s) ? s : undefined
+}
+
+// ── Running emulators ────────────────────────────────────────────────────────────────────────────
+
+export interface RunningEmulator {
+ avd: string
+ pid: number
+ /** adb's serial: `emulator-<console port>`. */
+ serial?: string
+ endpoint?: EmulatorEndpoint
+}
+
+/** A directory an emulator writes its discovery file into, and the directory below which nothing
+ * is trusted by location alone: under a shared temp dir another local user can create the path
+ * first, so every component from `trustedBase` (exclusive) down must be ours. */
+export interface DiscoveryDir {
+ dir: string
+ trustedBase: string
+}
+
+/** The directories an emulator writes its discovery file into (emulator's own temp-dir rules). */
+export function discoveryDirs(): DiscoveryDir[] {
+ const home = os.homedir()
+ if (process.platform === 'darwin') {
+ return [{ dir: path.join(home, 'Library', 'Caches', 'TemporaryItems', 'avd', 'running'), trustedBase: home }]
+ }
+ if (process.platform === 'win32') {
+ const local = process.env.LOCALAPPDATA
+ return local ? [{ dir: path.join(local, 'Temp', 'avd', 'running'), trustedBase: local }] : []
+ }
+ const dirs: DiscoveryDir[] = []
+ const xdg = process.env.XDG_RUNTIME_DIR
+ if (xdg) dirs.push({ dir: path.join(xdg, 'avd', 'running'), trustedBase: xdg })
+ const user = process.env.USER ?? os.userInfo().username
+ const tmp = os.tmpdir()
+ dirs.push({ dir: path.join(tmp, `android-${user}`, 'avd', 'running'), trustedBase: tmp })
+ return dirs
+}
+
+/** Our uid, or null where the OS has none (Windows: per-user dirs, no shared temp to squat). */
+function currentUid(): number | null {
+ return typeof process.getuid === 'function' ? process.getuid() : null
+}
+
+/** Every component of `dir` below `trustedBase` is a real directory (not a symlink) owned by `uid`.
+ * A pre-created `/tmp/android-<user>` belonging to someone else would otherwise let them plant a
+ * discovery file whose `grpc.port` receives everything the user types into the device. */
+async function dirOwnedBy(dir: string, trustedBase: string, uid: number): Promise<boolean> {
+ const rel = path.relative(trustedBase, dir)
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return false
+ let cur = trustedBase
+ for (const part of rel.split(path.sep)) {
+ cur = path.join(cur, part)
+ const st = await lstat(cur).catch(() => null)
+ if (!st || !st.isDirectory() || st.uid !== uid) return false
+ }
+ return true
+}
+
+/** Is `pid` a live process WE can signal? EPERM means it exists but belongs to another user —
+ * not our emulator, so its discovery file is not ours to trust. */
+function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** Read one discovery file into what the node needs. Pure, for tests. */
+export function parseDiscovery(text: string, pid: number): RunningEmulator | null {
+ const kv = parseIni(text)
+ const avd = kv['avd.id']
+ if (!avd || !ANDROID_AVD_NAME.test(avd)) return null
+ const port = Number(kv['grpc.port'])
+ const token = kv['grpc.token']
+ const serialPort = Number(kv['port.serial'])
+ return {
+ avd,
+ pid,
+ serial: Number.isInteger(serialPort) && serialPort > 0 && serialPort < 65536 ? `emulator-${serialPort}` : undefined,
+ endpoint:
+ Number.isInteger(port) && port > 0 && port < 65536 && token && /^[A-Za-z0-9+/=._-]{8,512}$/.test(token)
+ ? { port, token }
+ : undefined
+ }
+}
+
+export async function runningEmulators(
+ dirs: DiscoveryDir[] = discoveryDirs(),
+ uid: number | null = currentUid()
+): Promise<RunningEmulator[]> {
+ const out: RunningEmulator[] = []
+ for (const { dir, trustedBase } of dirs) {
+ if (uid !== null && !(await dirOwnedBy(dir, trustedBase, uid))) continue
+ let names: string[]
+ try {
+ names = await readdir(dir)
+ } catch {
+ continue
+ }
+ for (const name of names) {
+ const m = /^pid_(\d+)\.ini$/.exec(name)
+ if (!m) continue
+ const pid = Number(m[1])
+ if (!pidAlive(pid)) continue
+ const text = await readOwnedFile(path.join(dir, name), uid)
+ const e = text === null ? null : parseDiscovery(text, pid)
+ if (e) out.push(e)
+ }
+ }
+ return out
+}
+
+const MAX_DISCOVERY_BYTES = 64 * 1024
+
+/** Read a discovery file only if it is a regular file owned by `uid` (checked on the open handle,
+ * so it cannot be swapped between the check and the read; a symlink is refused at open). Null =
+ * not ours, unreadable (being written or removed), or too large. */
+async function readOwnedFile(file: string, uid: number | null): Promise<string | null> {
+ // Read-only: without O_CREAT nothing is created and the mode is ignored. It is spelled out because
+ // the path is under a shared temp dir, so a reader cannot tell this call apart from a create.
+ const fh = await open(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0), 0o600).catch(() => null)
+ if (!fh) return null
+ try {
+ const st = await fh.stat()
+ if (!st.isFile() || st.size > MAX_DISCOVERY_BYTES) return null
+ if (uid !== null && st.uid !== uid) return null
+ return await fh.readFile('utf8')
+ } catch {
+ return null
+ } finally {
+ await fh.close().catch(() => undefined)
+ }
+}
+
+export async function findRunning(avd: string): Promise<RunningEmulator | null> {
+ return (await runningEmulators()).find((e) => e.avd === avd && e.endpoint) ?? null
+}
+
+// ── Listing and booting ─────────────────────────────────────────────────────────────────────────
+
+/** Every installed AVD as a Simulator-node device. `error` says why the list is empty, when it is. */
+export async function listAndroidDevices(): Promise<{ devices: SimulatorDevice[]; error?: string }> {
+ const [avds, running] = await Promise.all([listAvds(), runningEmulators()])
+ if (!avds.length) {
+ const sdk = await androidSdkRoot()
+ return {
+ devices: [],
+ error: sdk ? undefined : 'The Android SDK was not found (set ANDROID_HOME, or install Android Studio).'
+ }
+ }
+ const serialOf = new Map(running.map((r) => [r.avd, r.serial]))
+ return {
+ devices: avds.map((a) => {
+ const serial = serialOf.get(a.name)
+ return {
+ id: androidDeviceId(a.name),
+ name: a.displayName,
+ platform: 'android' as const,
+ os: a.os,
+ state: serialOf.has(a.name) ? ('booted' as const) : ('shutdown' as const),
+ ...(serial ? { serial } : {})
+ }
+ })
+ }
+}
+
+const BOOT_WAIT_MS = 120_000
+
+/**
+ * Start an AVD headless, as iOS simulators are: the Simulator node is its screen. Resolves once its
+ * gRPC endpoint is published (Android may still be booting — the node shows the boot screen), or
+ * with the emulator's own last words if it exits first.
+ */
+export type AndroidBootResult =
+ | { ok: true; /** Set only when THIS call started the emulator: the process its discovery file names. */ started?: { pid: number; serial?: string } }
+ | { ok: false; error: string }
+
+export async function bootAndroid(avd: string): Promise<AndroidBootResult> {
+ if (!ANDROID_AVD_NAME.test(avd)) return { ok: false, error: 'Invalid device.' }
+ if (await findRunning(avd)) return { ok: true }
+ // Checked before spawning: an unknown name would start an emulator that dies at once, and the
+ // user would read its log line instead of the plain reason.
+ if (!(await listAvds()).some((a) => a.name === avd)) return { ok: false, error: `"${avd}" is not an Android virtual device on this machine.` }
+ const bin = await emulatorBinary()
+ if (!bin) return { ok: false, error: 'The Android emulator was not found (Android SDK → emulator).' }
+ const logDir = path.join(platform().userDataDir, 'android-emulator')
+ await mkdir(logDir, { recursive: true })
+ const logPath = path.join(logDir, `${avd}.log`)
+ // The log is read back through the SAME handle the emulator writes to, never by path again, so
+ // what is reported is that emulator's own output. Positional reads leave the shared offset alone.
+ const log = await open(logPath, 'w+')
+ try {
+ let exited: { code: number | null } | null = null
+ const child = spawn(bin, ['-avd', avd, '-no-window'], { ...emulatorSpawnOptions(process.platform), stdio: ['ignore', log.fd, log.fd], cwd: path.dirname(bin) })
+ child.on('exit', (code) => (exited = { code }))
+ child.on('error', () => (exited = { code: null }))
+ child.unref()
+ const deadline = Date.now() + BOOT_WAIT_MS
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 500))
+ const up = await findRunning(avd)
+ if (up) return { ok: true, started: { pid: up.pid, ...(up.serial ? { serial: up.serial } : {}) } }
+ if (exited) {
+ const tail = lastError(await readLogTail(log).catch(() => ''))
+ return { ok: false, error: tail ? `The emulator stopped: ${tail}` : 'The emulator stopped while starting.' }
+ }
+ }
+ return { ok: false, error: 'The emulator did not come up within two minutes.' }
+ } finally {
+ await log.close().catch(() => undefined)
+ }
+}
+
+/**
+ * How the emulator is started. Off Windows it is detached (its own process group), so it outlives
+ * the app like a tmux session does. On Windows `detached` gives the console-subsystem emulator NO
+ * console, so it and its children open visible console windows of their own; a hidden console
+ * (`windowsHide`) is what keeps a headless device headless there. `unref` lets the app exit either way.
+ */
+export function emulatorSpawnOptions(plat: NodeJS.Platform): { detached: boolean; windowsHide: boolean } {
+ return plat === 'win32' ? { detached: false, windowsHide: true } : { detached: true, windowsHide: true }
+}
+
+/** The last 64 KB of an open log, read at explicit positions. */
+async function readLogTail(h: Awaited<ReturnType<typeof open>>): Promise<string> {
+ const { size } = await h.stat()
+ const len = Math.min(size, 64 * 1024)
+ const buf = Buffer.alloc(len)
+ const { bytesRead } = await h.read(buf, 0, len, size - len)
+ return buf.subarray(0, bytesRead).toString('utf8')
+}
+
+/** The most useful line of an emulator log: its last ERROR / FATAL line, else its last line. */
+export function lastError(log: string): string {
+ const lines = log.split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
+ const bad = [...lines].reverse().find((l) => /^(ERROR|FATAL)\b/.test(l) || /\bERROR\s*\|/.test(l))
+ const pick = bad ?? lines[lines.length - 1] ?? ''
+ return pick.replace(/^(ERROR|FATAL)\s*\|?\s*/, '').slice(0, 300)
+}
+
+/** `adb -s <serial> <args>`, for the actions the emulator's own interface does not offer. */
+export async function adb(serial: string, args: string[], timeout = 60_000): Promise<string> {
+ const bin = await adbBinary()
+ if (!bin) throw new Error('adb was not found (Android SDK → platform-tools).')
+ return adbAt(bin, serial, args, timeout)
+}
+
+/** `adb` at a known path (tests pass a fake one). */
+export async function adbAt(bin: string, serial: string, args: string[], timeout = 60_000): Promise<string> {
+ const { stdout } = await run(bin, ['-s', serial, ...args], { timeout, maxBuffer: 16 * 1024 * 1024 })
+ return stdout
+}
+
+export const BOOT_COMPLETED_WAIT_MS = 90_000
+export const BOOT_COMPLETED_POLL_MS = 1_000
+export const BOOT_NOT_COMPLETED_MESSAGE =
+ 'Android is still starting on this device (it has not finished booting after 90 seconds). Try again once its home screen shows.'
+
+/**
+ * Wait until Android on `serial` reports `sys.boot_completed=1`. The emulator publishes its gRPC
+ * endpoint (and the node shows the boot animation) long before Android itself is up, and an `adb
+ * shell` command sent in between fails or acts on a half-started system. A failed `getprop` counts
+ * as "not yet" (adb says the device is offline while it boots). Throws BOOT_NOT_COMPLETED_MESSAGE
+ * once `timeoutMs` has passed.
+ */
+export async function waitForBootCompleted(
+ getprop: () => Promise<string>,
+ opts: { timeoutMs?: number; pollMs?: number; sleep?: (ms: number) => Promise<void>; now?: () => number } = {}
+): Promise<void> {
+ const timeoutMs = opts.timeoutMs ?? BOOT_COMPLETED_WAIT_MS
+ const pollMs = opts.pollMs ?? BOOT_COMPLETED_POLL_MS
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const now = opts.now ?? Date.now
+ const deadline = now() + timeoutMs
+ for (;;) {
+ const value = await getprop().then((v) => v.trim(), () => '')
+ if (value === '1') return
+ if (now() + pollMs > deadline) throw new Error(BOOT_NOT_COMPLETED_MESSAGE)
+ await sleep(pollMs)
+ }
+}
+
diff --git a/src/core/simulator/device-ownership.test.ts b/src/core/simulator/device-ownership.test.ts
new file mode 100644
index 000000000..e12d4cd49
--- /dev/null
+++ b/src/core/simulator/device-ownership.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createDeviceOwnership, type DeviceOwnershipDeps } from './device-ownership'
+
+function deps(over: Partial<DeviceOwnershipDeps> = {}): DeviceOwnershipDeps & {
+ shutdownIos: ReturnType<typeof vi.fn>
+ shutdownAndroid: ReturnType<typeof vi.fn>
+} {
+ return {
+ iosBooted: async () => true,
+ androidPid: async () => 4242,
+ shutdownIos: vi.fn(async () => undefined),
+ shutdownAndroid: vi.fn(async () => undefined),
+ ...over
+ } as never
+}
+
+describe('device ownership', () => {
+ it('shuts down only the devices this app booted', async () => {
+ const d = deps({ androidPid: async (avd) => (avd === 'Ours' ? 4242 : 999) })
+ const own = createDeviceOwnership(d)
+ own.claimIos('aaaa-ours')
+ own.claimAndroid('Ours', 4242)
+ const asked = await own.shutdownOwned(1000)
+ expect(asked).toEqual({ ios: ['AAAA-OURS'], android: ['Ours'] })
+ expect(d.shutdownIos).toHaveBeenCalledTimes(1)
+ expect(d.shutdownIos).toHaveBeenCalledWith('AAAA-OURS')
+ expect(d.shutdownAndroid).toHaveBeenCalledWith('Ours')
+ // Nothing else was ever named, so nothing else was touched.
+ expect(d.shutdownAndroid).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves a device it never claimed alone (user-booted, or already running at boot)', async () => {
+ const d = deps()
+ const own = createDeviceOwnership(d)
+ expect(await own.shutdownOwned(1000)).toEqual({ ios: [], android: [] })
+ expect(d.shutdownIos).not.toHaveBeenCalled()
+ expect(d.shutdownAndroid).not.toHaveBeenCalled()
+ })
+
+ it('does not shut down an emulator running under our AVD name but a different pid', async () => {
+ const d = deps({ androidPid: async () => 5555 })
+ const own = createDeviceOwnership(d)
+ own.claimAndroid('Pixel', 4242)
+ expect((await own.shutdownOwned(1000)).android).toEqual([])
+ expect(d.shutdownAndroid).not.toHaveBeenCalled()
+ })
+
+ it('never shuts down on a guess: an unknown iOS state is left alone', async () => {
+ const d = deps({ iosBooted: async () => null })
+ const own = createDeviceOwnership(d)
+ own.claimIos('X')
+ expect((await own.shutdownOwned(1000)).ios).toEqual([])
+ expect(d.shutdownIos).not.toHaveBeenCalled()
+ })
+
+ it('forgets a device released by the node or seen shut down', async () => {
+ const d = deps()
+ const own = createDeviceOwnership(d)
+ own.claimIos('a')
+ own.claimAndroid('P', 4242)
+ own.releaseIos('A')
+ own.releaseAndroid('P')
+ expect(own.ownedIos()).toEqual([])
+ expect(own.ownedAndroid()).toEqual([])
+ await own.shutdownOwned(1000)
+ expect(d.shutdownIos).not.toHaveBeenCalled()
+ expect(d.shutdownAndroid).not.toHaveBeenCalled()
+ })
+
+ it('returns within the timeout when a shutdown hangs', async () => {
+ const d = deps({ shutdownIos: vi.fn(() => new Promise(() => undefined)) as never })
+ const own = createDeviceOwnership(d)
+ own.claimIos('slow')
+ const started = Date.now()
+ const asked = await own.shutdownOwned(50)
+ expect(Date.now() - started).toBeLessThan(1000)
+ expect(asked.ios).toEqual(['SLOW'])
+ })
+})
diff --git a/src/core/simulator/device-ownership.ts b/src/core/simulator/device-ownership.ts
new file mode 100644
index 000000000..d14b508eb
--- /dev/null
+++ b/src/core/simulator/device-ownership.ts
@@ -0,0 +1,75 @@
+/**
+ * Which simulators THIS app started, so quitting shuts those down and nothing else.
+ *
+ * A Simulator node boots its device headless — the node is the only screen it has — so a device the
+ * node booted keeps running invisibly after the app quits (an Android emulator started with
+ * `-no-window` is a process with no UI at all). Quitting therefore shuts down what the node booted.
+ * It never touches a device the user booted themselves, or one that was already running when the
+ * node asked for it: ownership is recorded at boot time, from the boot's own answer, and only for a
+ * boot that actually started the device.
+ *
+ * Ownership is dropped as soon as it is no longer provable: the node shut the device down, a listing
+ * shows it shut down (someone else did, and a later boot is theirs), or — Android — the emulator
+ * running under that name is a different process from the one we started.
+ */
+
+export interface DeviceOwnershipDeps {
+ /** Whether the iOS simulator is booted now; null = cannot tell (never shut down on a guess). */
+ iosBooted(udid: string): Promise<boolean | null>
+ /** The pid of the emulator running this AVD now, or null when none is running. */
+ androidPid(avd: string): Promise<number | null>
+ shutdownIos(udid: string): Promise<unknown>
+ shutdownAndroid(avd: string): Promise<unknown>
+}
+
+export interface DeviceOwnership {
+ claimIos(udid: string): void
+ claimAndroid(avd: string, pid: number): void
+ /** The node shut this device down, or it was seen shut down: it is no longer ours. */
+ releaseIos(udid: string): void
+ releaseAndroid(avd: string): void
+ ownedIos(): string[]
+ ownedAndroid(): Array<{ avd: string; pid: number }>
+ /**
+ * Shut down every device still ours, re-checking each first. Resolves within `timeoutMs` whatever
+ * the devices do (quit must never wait on a simulator); answers which ones were asked to shut down.
+ */
+ shutdownOwned(timeoutMs: number): Promise<{ ios: string[]; android: string[] }>
+}
+
+export function createDeviceOwnership(deps: DeviceOwnershipDeps): DeviceOwnership {
+ const ios = new Set<string>()
+ const android = new Map<string, number>()
+ const key = (udid: string) => udid.toUpperCase()
+
+ return {
+ claimIos: (udid) => void ios.add(key(udid)),
+ claimAndroid: (avd, pid) => void android.set(avd, pid),
+ releaseIos: (udid) => void ios.delete(key(udid)),
+ releaseAndroid: (avd) => void android.delete(avd),
+ ownedIos: () => [...ios],
+ ownedAndroid: () => [...android].map(([avd, pid]) => ({ avd, pid })),
+ async shutdownOwned(timeoutMs) {
+ const asked = { ios: [] as string[], android: [] as string[] }
+ const work = Promise.allSettled([
+ ...[...ios].map(async (udid) => {
+ if ((await deps.iosBooted(udid)) !== true) return
+ asked.ios.push(udid)
+ await deps.shutdownIos(udid)
+ ios.delete(udid)
+ }),
+ ...[...android].map(async ([avd, pid]) => {
+ // Same name, different process: the user started this one after ours went away.
+ if ((await deps.androidPid(avd)) !== pid) return
+ asked.android.push(avd)
+ await deps.shutdownAndroid(avd)
+ android.delete(avd)
+ })
+ ])
+ let timer: ReturnType<typeof setTimeout> | undefined
+ await Promise.race([work, new Promise<void>((r) => (timer = setTimeout(r, timeoutMs)))])
+ if (timer) clearTimeout(timer)
+ return { ios: [...asked.ios], android: [...asked.android] }
+ }
+ }
+}
diff --git a/src/core/simulator/simbridge-source.ts b/src/core/simulator/simbridge-source.ts
new file mode 100644
index 000000000..bef6eff32
--- /dev/null
+++ b/src/core/simulator/simbridge-source.ts
@@ -0,0 +1,421 @@
+/**
+ * The Swift source of `nt-simbridge`, the helper behind the Simulator node (see simulator-service).
+ *
+ * Shipped as SOURCE and compiled on the user's Mac with `xcrun swiftc` on first use: any machine
+ * that has iOS simulators has Xcode, so nothing native ships with nodeterm, nothing is signed for
+ * it, and the binary always matches the Xcode it talks to (the cache key includes Xcode's build).
+ *
+ * It uses Xcode's PRIVATE simulator frameworks — the ones DeviceHub itself uses — resolved at
+ * runtime (dlopen / NSClassFromString / dlsym), so nothing links against them and an Xcode that
+ * moved something fails with a sentence instead of a crash. The Indigo HID message layout is from
+ * facebook/idb (FBSimulatorControl, MIT), whose reverse engineering tracks current Xcodes.
+ *
+ * Wire format
+ * stdout frames: "NTF2" | u32 width | u32 height | u32 displayIndex | u32 jpegLength | jpeg (LE)
+ * stdin one JSON command per line:
+ * {"t":"down"|"move"|"up","x":0..1,"y":0..1} a touch at a ratio of the screen
+ * {"t":"key","usage":N,"down":bool} HID keyboard usage (page 7)
+ * {"t":"button","name":"home"|"lock"|"side"|"siri"|"volup"|"voldown"|"playpause"}
+ * (down/move/up take an optional "edge": 1 top, 2 left, 3 bottom, 4 right)
+ * {"t":"gesture","name":"app-switcher"} swipe up from the bottom edge and hold
+ * {"t":"display","index":N|-1} pin a display; -1 = automatic
+ * {"t":"orientation","value":1..4} GSEvent orientation (Purple values:
+ * 1 portrait, 2 upside down, 3/4 landscape)
+ * stderr one JSON status line per event: {"ok":…} / {"error":…}
+ *
+ * Kept free of backticks and dollar-brace sequences so it can live in a TypeScript string.
+ */
+export const SIMBRIDGE_VERSION = 4
+
+export const SIMBRIDGE_SOURCE = String.raw`
+import CoreGraphics
+import Darwin
+import Foundation
+import ImageIO
+import IOSurface
+import UniformTypeIdentifiers
+
+let statusLock = NSLock()
+func status(_ obj: [String: Any]) {
+ guard let d = try? JSONSerialization.data(withJSONObject: obj), let s = String(data: d, encoding: .utf8) else { return }
+ statusLock.lock(); defer { statusLock.unlock() }
+ FileHandle.standardError.write((s + "\n").data(using: .utf8)!)
+}
+func fail(_ code: String, _ msg: String) -> Never {
+ status(["error": code, "message": msg])
+ exit(2)
+}
+
+// ── Arguments ──────────────────────────────────────────────────────────────────────────────────
+let args = CommandLine.arguments
+guard args.count >= 2 else { fail("usage", "nt-simbridge <udid> [--fps N] [--max-width PX] [--quality Q]") }
+let udid = args[1].uppercased()
+func argValue(_ name: String, _ def: Double) -> Double {
+ if let i = args.firstIndex(of: name), i + 1 < args.count, let v = Double(args[i + 1]) { return v }
+ return def
+}
+let fps = max(1, min(60, argValue("--fps", 30)))
+let maxWidth = max(200, min(2000, argValue("--max-width", 900)))
+let quality = max(0.2, min(0.95, argValue("--quality", 0.6)))
+
+// ── Frameworks ─────────────────────────────────────────────────────────────────────────────────
+func developerDir() -> String {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")
+ p.arguments = ["-p"]
+ let pipe = Pipe()
+ p.standardOutput = pipe
+ try? p.run()
+ p.waitUntilExit()
+ return String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? "/Applications/Xcode.app/Contents/Developer"
+}
+let devDir = developerDir()
+let xcodeContents = (devDir as NSString).deletingLastPathComponent
+let simulatorKitPath = xcodeContents + "/SharedFrameworks/SimulatorKit.framework/SimulatorKit"
+for path in ["/Library/Developer/PrivateFrameworks/CoreSimulator.framework/CoreSimulator", simulatorKitPath] {
+ if dlopen(path, RTLD_NOW | RTLD_GLOBAL) == nil {
+ fail("framework", "could not load " + path + ": " + String(cString: dlerror()))
+ }
+}
+let msgSend = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "objc_msgSend")!
+
+func call(_ obj: AnyObject, _ sel: String) -> AnyObject? {
+ let s = NSSelectorFromString(sel)
+ guard obj.responds(to: s) else { return nil }
+ return obj.perform(s)?.takeUnretainedValue()
+}
+
+// ── Device ─────────────────────────────────────────────────────────────────────────────────────
+guard let contextClass = NSClassFromString("SimServiceContext") else { fail("framework", "SimServiceContext not found") }
+typealias ContextFn = @convention(c) (AnyObject, Selector, NSString, UnsafeMutablePointer<NSError?>?) -> AnyObject?
+var ctxErr: NSError?
+guard let context = unsafeBitCast(msgSend, to: ContextFn.self)(contextClass, NSSelectorFromString("sharedServiceContextForDeveloperDir:error:"), devDir as NSString, &ctxErr) else {
+ fail("framework", "SimServiceContext: " + (ctxErr?.localizedDescription ?? "nil"))
+}
+typealias DeviceSetFn = @convention(c) (AnyObject, Selector, UnsafeMutablePointer<NSError?>?) -> AnyObject?
+var setErr: NSError?
+guard let deviceSet = unsafeBitCast(msgSend, to: DeviceSetFn.self)(context, NSSelectorFromString("defaultDeviceSetWithError:"), &setErr),
+ let devices = (deviceSet as AnyObject).value(forKey: "devices") as? [AnyObject] else {
+ fail("framework", "device set: " + (setErr?.localizedDescription ?? "nil"))
+}
+guard let device = devices.first(where: { (($0.value(forKey: "UDID") as? NSUUID)?.uuidString ?? "") == udid }) else {
+ fail("no-device", "no simulator " + udid)
+}
+let stateString = (device.value(forKey: "stateString") as? String) ?? "?"
+guard stateString == "Booted" else { fail("not-booted", "the simulator is " + stateString) }
+
+// ── Displays ───────────────────────────────────────────────────────────────────────────────────
+// A device can have several main-class displays: a foldable has an inner and a cover screen, and
+// only one of them is lit at a time. All of them are tracked; the lit one is shown (see pickActive).
+struct Display { let index: Int; let surface: IOSurface; let screenID: UInt32; let name: String }
+
+/// Touches go to the shown screen's own digitizer: 0x40000000 | screenID. MEASURED on a foldable
+/// (Xcode 27, "iPhone Duo"): the generic main-screen target (0x32) reached neither screen while the
+/// cover screen was the lit one; the cover screen's target did. 0x32 remains the fallback for a
+/// display that vends no screen id.
+func touchTarget(_ d: Display) -> UInt32 { d.screenID > 0 ? (0x4000_0000 | d.screenID) : 0x32 }
+
+func mainDisplays() -> [Display] {
+ guard let io = device.value(forKey: "io") as AnyObject?, let ports = call(io, "ioPorts") as? [AnyObject] else { return [] }
+ var out: [Display] = []
+ for port in ports {
+ guard let descriptor = call(port, "descriptor") else { continue }
+ guard let s = call(descriptor, "framebufferSurface") ?? call(descriptor, "ioSurface"), CFGetTypeID(s) == IOSurfaceGetTypeID() else { continue }
+ var displayClass = -1
+ // "state" is a ROCK proxy: no key-value coding, so message displayClass (an unsigned short).
+ if let state = call(descriptor, "state"), state.responds(to: NSSelectorFromString("displayClass")) {
+ typealias U16Fn = @convention(c) (AnyObject, Selector) -> UInt16
+ displayClass = Int(unsafeBitCast(msgSend, to: U16Fn.self)(state, NSSelectorFromString("displayClass")))
+ }
+ guard displayClass == 0 else { continue }
+ var screenID: UInt32 = 0
+ var name = ""
+ if let props = call(descriptor, "screenProperties") {
+ if props.responds(to: NSSelectorFromString("screenID")) {
+ typealias U32Fn = @convention(c) (AnyObject, Selector) -> UInt32
+ screenID = unsafeBitCast(msgSend, to: U32Fn.self)(props, NSSelectorFromString("screenID"))
+ }
+ name = (call(props, "name") as? String) ?? ""
+ }
+ out.append(Display(index: out.count, surface: unsafeBitCast(s, to: IOSurface.self), screenID: screenID, name: name))
+ }
+ return out
+}
+
+/// Whether a surface shows anything: a sparse grid of pixels, any brighter than near-black.
+func isLit(_ s: IOSurface) -> Bool {
+ IOSurfaceLock(s, .readOnly, nil)
+ defer { IOSurfaceUnlock(s, .readOnly, nil) }
+ let w = IOSurfaceGetWidth(s), h = IOSurfaceGetHeight(s), bpr = IOSurfaceGetBytesPerRow(s)
+ let base = IOSurfaceGetBaseAddress(s).assumingMemoryBound(to: UInt8.self)
+ for gy in 1..<8 {
+ for gx in 1..<8 {
+ let p = base.advanced(by: (h * gy / 8) * bpr + (w * gx / 8) * 4)
+ if Int(p[0]) + Int(p[1]) + Int(p[2]) > 60 { return true }
+ }
+ }
+ return false
+}
+
+var displays = mainDisplays()
+guard !displays.isEmpty else { fail("no-display", "the simulator has no framebuffer display") }
+var activeIndex = displays.firstIndex(where: { isLit($0.surface) }) ?? 0
+var pinned = false
+var lastSeeds = displays.map { IOSurfaceGetSeed($0.surface) }
+var lastChange = displays.map { _ in Date.distantPast }
+func announce() {
+ status(["ok": "displays", "active": activeIndex, "pinned": pinned,
+ "displays": displays.map { ["index": $0.index, "width": IOSurfaceGetWidth($0.surface), "height": IOSurfaceGetHeight($0.surface),
+ "screenID": $0.screenID, "name": $0.name] }])
+}
+announce()
+
+// ── Frames ─────────────────────────────────────────────────────────────────────────────────────
+let out = FileHandle.standardOutput
+let colorSpace = CGColorSpaceCreateDeviceRGB()
+var sentSeed: UInt32 = 0
+var sentIndex = -1
+
+func encode(_ s: IOSurface) -> (Data, Int, Int)? {
+ IOSurfaceLock(s, .readOnly, nil)
+ defer { IOSurfaceUnlock(s, .readOnly, nil) }
+ let w = IOSurfaceGetWidth(s), h = IOSurfaceGetHeight(s)
+ guard let ctx = CGContext(data: IOSurfaceGetBaseAddress(s), width: w, height: h, bitsPerComponent: 8,
+ bytesPerRow: IOSurfaceGetBytesPerRow(s), space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue),
+ let full = ctx.makeImage() else { return nil }
+ let scale = min(1.0, maxWidth / Double(w))
+ var image = full
+ if scale < 1.0 {
+ let ow = Int(Double(w) * scale), oh = Int(Double(h) * scale)
+ if let small = CGContext(data: nil, width: ow, height: oh, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) {
+ small.interpolationQuality = .medium
+ small.draw(full, in: CGRect(x: 0, y: 0, width: ow, height: oh))
+ if let i = small.makeImage() { image = i }
+ }
+ }
+ let data = NSMutableData()
+ guard let dest = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }
+ CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
+ guard CGImageDestinationFinalize(dest) else { return nil }
+ return (data as Data, image.width, image.height)
+}
+
+func le32(_ v: Int) -> Data { var x = UInt32(truncatingIfNeeded: v).littleEndian; return Data(bytes: &x, count: 4) }
+
+let frameQueue = DispatchQueue(label: "nt.simbridge.frames")
+var ticks = 0
+let timer = DispatchSource.makeTimerSource(queue: frameQueue)
+timer.schedule(deadline: .now(), repeating: 1.0 / fps)
+timer.setEventHandler {
+ ticks += 1
+ // Surfaces can be replaced (rotation, a display coming up): re-resolve every ~2 s.
+ if ticks % Int(fps * 2) == 0 {
+ let fresh = mainDisplays()
+ // Compare by IOSurface id: the private API hands back a fresh proxy object on every call.
+ if !fresh.isEmpty, fresh.count != displays.count || zip(fresh, displays).contains(where: { IOSurfaceGetID($0.surface) != IOSurfaceGetID($1.surface) }) {
+ displays = fresh
+ lastSeeds = displays.map { IOSurfaceGetSeed($0.surface) }
+ lastChange = displays.map { _ in Date() }
+ if activeIndex >= displays.count { activeIndex = 0 }
+ announce()
+ }
+ }
+ let now = Date()
+ for (i, d) in displays.enumerated() {
+ let seed = IOSurfaceGetSeed(d.surface)
+ if seed != lastSeeds[i] { lastSeeds[i] = seed; lastChange[i] = now }
+ }
+ // Follow the lit screen (a fold/unfold moves the picture to the other display): when the shown
+ // display has been still for 2 s while another one just changed and is lit, switch to it.
+ if !pinned, displays.count > 1, now.timeIntervalSince(lastChange[activeIndex]) > 2 {
+ if let other = displays.indices.first(where: { $0 != activeIndex && now.timeIntervalSince(lastChange[$0]) < 0.5 && isLit(displays[$0].surface) }) {
+ activeIndex = other
+ announce()
+ }
+ }
+ let active = displays[activeIndex]
+ let seed = lastSeeds[activeIndex]
+ if seed == sentSeed && sentIndex == activeIndex { return }
+ sentSeed = seed
+ sentIndex = activeIndex
+ guard let (jpeg, w, h) = encode(active.surface) else { return }
+ var frame = Data("NTF2".utf8)
+ frame.append(le32(w)); frame.append(le32(h)); frame.append(le32(activeIndex)); frame.append(le32(jpeg.count)); frame.append(jpeg)
+ out.write(frame)
+}
+timer.resume()
+
+// ── HID ────────────────────────────────────────────────────────────────────────────────────────
+guard let sk = dlopen(simulatorKitPath, RTLD_NOW) else { fail("framework", "SimulatorKit") }
+typealias MouseFn = @convention(c) (UnsafeMutablePointer<CGPoint>?, UnsafeMutablePointer<CGPoint>?, UInt32, UInt, CGSize, UInt32) -> UnsafeMutableRawPointer
+typealias KeyFn = @convention(c) (Int32, Int32) -> UnsafeMutableRawPointer
+typealias ArbitraryFn = @convention(c) (Int32, UInt32, UInt32, Int32) -> UnsafeMutableRawPointer
+guard let mouseSym = dlsym(sk, "IndigoHIDMessageForMouseNSEvent"),
+ let keySym = dlsym(sk, "IndigoHIDMessageForKeyboardArbitrary"),
+ let arbSym = dlsym(sk, "IndigoHIDMessageForHIDArbitrary") else { fail("framework", "Indigo message builders missing") }
+let messageForMouse = unsafeBitCast(mouseSym, to: MouseFn.self)
+let messageForKey = unsafeBitCast(keySym, to: KeyFn.self)
+let messageForArbitrary = unsafeBitCast(arbSym, to: ArbitraryFn.self)
+
+guard let hidClass = NSClassFromString("SimulatorKit.SimDeviceLegacyHIDClient") else { fail("framework", "SimDeviceLegacyHIDClient not found") }
+typealias AllocFn = @convention(c) (AnyClass, Selector) -> AnyObject
+typealias HIDInitFn = @convention(c) (AnyObject, Selector, AnyObject, UnsafeMutablePointer<NSError?>?) -> AnyObject?
+let allocated = unsafeBitCast(msgSend, to: AllocFn.self)(hidClass, NSSelectorFromString("alloc"))
+var hidErr: NSError?
+guard let hid = unsafeBitCast(msgSend, to: HIDInitFn.self)(allocated, NSSelectorFromString("initWithDevice:error:"), device, &hidErr) else {
+ fail("hid", "HID client: " + (hidErr?.localizedDescription ?? "nil"))
+}
+typealias SendFn = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, Bool, DispatchQueue, @escaping @convention(block) (NSError?) -> Void) -> Void
+let sendFn = unsafeBitCast(msgSend, to: SendFn.self)
+let hidQueue = DispatchQueue(label: "nt.simbridge.hid")
+status(["ok": "ready"])
+
+@Sendable func send(_ message: UnsafeMutableRawPointer) {
+ hidQueue.async {
+ sendFn(hid, NSSelectorFromString("sendWithMessage:freeWhenDone:completionQueue:completion:"), message, true, hidQueue) { err in
+ if let err { status(["error": "hid-send", "message": err.localizedDescription]) }
+ }
+ }
+}
+
+/// A single-finger touch at a ratio of the screen. SimulatorKit only builds multi-touch messages,
+/// so the contact is sourced from one and re-enveloped as single-touch (idb's touchMessage).
+@Sendable func touch(x: Double, y: Double, down: Bool, target: UInt32, edge: UInt32 = 0) {
+ var point = CGPoint(x: x, y: y)
+ let source = messageForMouse(&point, nil, target, down ? 1 : 2, CGSize(width: 1, height: 1), edge)
+ source.advanced(by: 0x3c).storeBytes(of: x, as: Double.self)
+ source.advanced(by: 0x44).storeBytes(of: y, as: Double.self)
+ let size = 0x140, stride = 0x90
+ guard let dest = calloc(1, size) else { free(source); return }
+ dest.advanced(by: 0x18).storeBytes(of: UInt32(stride), as: UInt32.self)
+ dest.advanced(by: 0x1c).storeBytes(of: UInt8(2), as: UInt8.self)
+ dest.advanced(by: 0x20).storeBytes(of: UInt32(0xB), as: UInt32.self)
+ dest.advanced(by: 0x24).storeBytes(of: mach_absolute_time(), as: UInt64.self)
+ memcpy(dest.advanced(by: 0x30), source.advanced(by: 0x30), 0x70)
+ free(source)
+ memcpy(dest.advanced(by: 0x20 + stride), dest.advanced(by: 0x20), stride)
+ dest.advanced(by: 0x20 + stride + 0x10).storeBytes(of: UInt32(1), as: UInt32.self)
+ dest.advanced(by: 0x20 + stride + 0x14).storeBytes(of: UInt32(2), as: UInt32.self)
+ send(dest)
+}
+
+/// Hardware buttons as HID Consumer-page usages to the digitizer service (0x32): the path that
+/// reaches a Face ID device, which ignores the legacy home-button source.
+let consumerUsage: [String: UInt32] = ["home": 0x40, "lock": 0x30, "side": 0x30, "siri": 0xCF, "volup": 0xE9, "voldown": 0xEA, "playpause": 0xCD]
+/// The legacy ButtonEventSource for the two buttons that have one (target 0x33). Used when the
+/// Consumer-usage path is refused: MEASURED on a foldable, where the digitizer-addressed home press
+/// came back "Mach port invalid" while touches to the screen's own target worked.
+let legacySource: [String: Int32] = ["home": 0, "lock": 1, "side": 0xBB8]
+typealias ButtonFn = @convention(c) (Int32, Int32, Int32) -> UnsafeMutableRawPointer
+let messageForButton: ButtonFn? = dlsym(sk, "IndigoHIDMessageForButton").map { unsafeBitCast($0, to: ButtonFn.self) }
+
+@Sendable func sendChecked(_ message: UnsafeMutableRawPointer, _ done: @escaping @Sendable (Bool) -> Void) {
+ hidQueue.async {
+ sendFn(hid, NSSelectorFromString("sendWithMessage:freeWhenDone:completionQueue:completion:"), message, true, hidQueue) { err in done(err == nil) }
+ }
+}
+
+@Sendable func button(_ name: String) {
+ guard let usage = consumerUsage[name] else { return }
+ sendChecked(messageForArbitrary(0x32, 0x0C, usage, 1)) { ok in
+ if ok {
+ hidQueue.asyncAfter(deadline: .now() + 0.08) { send(messageForArbitrary(0x32, 0x0C, usage, 2)) }
+ } else if let source = legacySource[name], let legacy = messageForButton {
+ send(legacy(source, 1, 0x33))
+ hidQueue.asyncAfter(deadline: .now() + 0.08) { send(legacy(source, 2, 0x33)) }
+ } else {
+ status(["error": "button", "message": "the simulator refused the " + name + " button"])
+ }
+ }
+}
+
+// ── Gestures ───────────────────────────────────────────────────────────────────────────────────
+/// The App Switcher on a Face ID device: a finger from the bottom edge, up past a third of the
+/// screen, a pause, then lift. The contact carries the bottom-edge flag (IndigoHIDEdgeBottom = 3):
+/// iOS recognises system edge gestures from that flag, not from where the finger started.
+@Sendable func appSwitcher(target: UInt32) {
+ let steps = 14
+ touch(x: 0.5, y: 0.995, down: true, target: target, edge: 3)
+ for i in 1...steps {
+ let y = 0.995 - 0.4 * Double(i) / Double(steps)
+ hidQueue.asyncAfter(deadline: .now() + 0.016 * Double(i)) { touch(x: 0.5, y: y, down: true, target: target, edge: 3) }
+ }
+ hidQueue.asyncAfter(deadline: .now() + 0.016 * Double(steps) + 0.6) { touch(x: 0.5, y: 0.595, down: false, target: target, edge: 3) }
+}
+
+// ── Orientation ────────────────────────────────────────────────────────────────────────────────
+// A GSEvent "device orientation changed" (type 50) as a raw mach message to SpringBoard's
+// PurpleWorkspacePort, looked up in the device's bootstrap namespace — the layout from idb's
+// SimulatorPurpleHID. The framebuffer itself stays portrait; iOS draws rotated content into it.
+typealias LookupFn = @convention(c) (AnyObject, Selector, NSString, UnsafeMutablePointer<NSError?>?) -> UInt32
+let purpleQueue = DispatchQueue(label: "nt.simbridge.purple")
+@Sendable func orientation(_ value: UInt32) {
+ purpleQueue.async {
+ var lookupErr: NSError?
+ let port = unsafeBitCast(msgSend, to: LookupFn.self)(device, NSSelectorFromString("lookup:error:"), "PurpleWorkspacePort" as NSString, &lookupErr)
+ guard port != 0 else {
+ status(["error": "orientation", "message": "PurpleWorkspacePort unavailable: " + (lookupErr?.localizedDescription ?? "nil")])
+ return
+ }
+ var buf = [UInt8](repeating: 0, count: 112)
+ func put(_ v: UInt32, _ at: Int) { withUnsafeBytes(of: v.littleEndian) { for i in 0..<4 { buf[at + i] = $0[i] } } }
+ put(0x13, 0x00) // msgh_bits: MACH_MSG_TYPE_COPY_SEND
+ put(108, 0x04) // msgh_size
+ put(port, 0x08) // msgh_remote_port
+ put(0x7B, 0x14) // msgh_id
+ put(50 | 0x2_0000, 0x18) // GSEvent type: device orientation changed | host flag
+ put(4, 0x48) // payload length
+ put(value, 0x4C) // the orientation
+ let kr = buf.withUnsafeMutableBytes { raw -> kern_return_t in
+ let header = raw.baseAddress!.assumingMemoryBound(to: mach_msg_header_t.self)
+ return mach_msg(header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, header.pointee.msgh_size, 0, mach_port_t(MACH_PORT_NULL), 2000, mach_port_t(MACH_PORT_NULL))
+ }
+ if kr != KERN_SUCCESS { status(["error": "orientation", "message": "rotate failed: " + String(cString: mach_error_string(kr))]) }
+ }
+}
+
+// ── Commands ───────────────────────────────────────────────────────────────────────────────────
+DispatchQueue.global().async {
+ while let line = readLine() {
+ guard let d = line.data(using: .utf8), let cmd = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
+ let t = cmd["t"] as? String else { continue }
+ switch t {
+ case "down", "move", "up":
+ guard let x = cmd["x"] as? Double, let y = cmd["y"] as? Double, x.isFinite, y.isFinite else { continue }
+ let target = frameQueue.sync { touchTarget(displays[activeIndex]) }
+ // The panel edge the contact started on (1 top, 2 left, 3 bottom, 4 right): iOS recognises
+ // its edge gestures — the home swipe up from the bottom — from this flag alone.
+ let edge = UInt32(min(4, max(0, (cmd["edge"] as? Int) ?? 0)))
+ touch(x: min(1, max(0, x)), y: min(1, max(0, y)), down: t != "up", target: target, edge: edge)
+ case "key":
+ guard let usage = cmd["usage"] as? Int, (0..<256).contains(usage), let down = cmd["down"] as? Bool else { continue }
+ send(messageForKey(Int32(usage), down ? 1 : 2))
+ case "button":
+ button((cmd["name"] as? String) ?? "")
+ case "gesture":
+ if (cmd["name"] as? String) == "app-switcher" {
+ let target = frameQueue.sync { touchTarget(displays[activeIndex]) }
+ appSwitcher(target: target)
+ }
+ case "orientation":
+ guard let v = cmd["value"] as? Int, (1...4).contains(v) else { continue }
+ orientation(UInt32(v))
+ case "display":
+ guard let i = cmd["index"] as? Int else { continue }
+ frameQueue.async {
+ if i >= 0 && i < displays.count { activeIndex = i; pinned = true } else { pinned = false }
+ sentIndex = -1
+ announce()
+ }
+ default:
+ break
+ }
+ }
+ exit(0) // stdin closed: the node went away
+}
+
+dispatchMain()
+`
diff --git a/src/core/simulator/simulator-actions.test.ts b/src/core/simulator/simulator-actions.test.ts
new file mode 100644
index 000000000..182362ded
--- /dev/null
+++ b/src/core/simulator/simulator-actions.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+import { parseLocationScenarios } from './simulator-actions'
+
+describe('parseLocationScenarios', () => {
+ it('reads the scenario names out of simctl’s table (Xcode 27 output)', () => {
+ const out = [
+ 'Name Description',
+ '========================================================',
+ 'City Run City Run',
+ 'City Bicycle Ride City Bicycle Ride',
+ 'Freeway Drive Freeway Drive',
+ 'Apple Apple',
+ ''
+ ].join('\n')
+ expect(parseLocationScenarios(out)).toEqual(['City Run', 'City Bicycle Ride', 'Freeway Drive', 'Apple'])
+ })
+ it('is empty for no output', () => {
+ expect(parseLocationScenarios('')).toEqual([])
+ })
+})
diff --git a/src/core/simulator/simulator-actions.ts b/src/core/simulator/simulator-actions.ts
new file mode 100644
index 000000000..e13cbcdeb
--- /dev/null
+++ b/src/core/simulator/simulator-actions.ts
@@ -0,0 +1,337 @@
+import { execFile, spawn, type ChildProcess } from 'node:child_process'
+import { mkdir, stat } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { IPC } from '../../shared/ipc'
+import { SIMULATOR_UDID } from '../../shared/run-config'
+import {
+ avdNameOf,
+ normalizeSimulatorAction,
+ type SimulatorAction,
+ type SimulatorActionResult,
+ type SimulatorCaptureTarget,
+ type SimulatorDeviceState
+} from '../../shared/simulator'
+import { androidScreenshot, readAndroidState, runAndroidAction } from './android-actions'
+import { platform } from '../platform'
+
+/**
+ * The Simulator node's ⋯ menu, host side: everything DeviceHub offers that a public `simctl`
+ * command (or a documented simulator notification) can do. HID buttons and touches go through the
+ * node's helper instead (simulator-service); this module never talks to the device's input.
+ *
+ * Every action is re-validated (`normalizeSimulatorAction`) — the renderer is untrusted — and every
+ * argument reaches `simctl` as its own argv entry, never through a shell.
+ */
+
+const run = promisify(execFile)
+const SIMCTL = ['/usr/bin/xcrun', 'simctl'] as const
+
+async function simctl(args: string[], opts: { input?: string; timeout?: number } = {}): Promise<string> {
+ if (opts.input !== undefined) {
+ return await new Promise<string>((resolve, reject) => {
+ const child = spawn(SIMCTL[0], [SIMCTL[1], ...args], { stdio: ['pipe', 'pipe', 'pipe'] })
+ let out = ''
+ let err = ''
+ const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeout ?? 60_000)
+ child.stdout.on('data', (d) => (out += String(d)))
+ child.stderr.on('data', (d) => (err += String(d)))
+ child.on('error', reject)
+ child.on('exit', (code) => {
+ clearTimeout(timer)
+ code === 0 ? resolve(out) : reject(new Error(err.trim().split('\n').pop() || `simctl exited ${code}`))
+ })
+ // simctl exiting before it read stdin (a bad bundle id) is an EPIPE event, not a throw; the
+ // exit handler above already reports why.
+ child.stdin.on('error', (e) => console.warn('[simulator] simctl stdin:', e.message))
+ child.stdin.end(opts.input)
+ })
+ }
+ const { stdout } = await run(SIMCTL[0], [SIMCTL[1], ...args], { timeout: opts.timeout ?? 60_000, maxBuffer: 8 * 1024 * 1024 })
+ return stdout
+}
+
+export function errorText(e: unknown): string {
+ const raw = String((e as { stderr?: string }).stderr || (e as Error).message || e)
+ const line = raw.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? 'failed'
+ return line.replace(/^An error was encountered processing the command \([^)]*\):\s*/i, '')
+}
+
+/** A simulator notification — the documented way the simulator's own debug features are triggered
+ * (shake, biometric match/no-match, enrolment). `-s` sets the state first when given. */
+async function notify(udid: string, name: string, state?: 0 | 1): Promise<void> {
+ if (state !== undefined) await simctl(['spawn', udid, 'notifyutil', '-s', name, String(state)])
+ await simctl(['spawn', udid, 'notifyutil', '-p', name])
+}
+
+const BIOMETRIC = {
+ face: { enrolled: 'com.apple.BiometricKit.enrollmentChanged', match: 'com.apple.BiometricKit_Sim.pearl.match', nomatch: 'com.apple.BiometricKit_Sim.pearl.nomatch' },
+ touch: { enrolled: 'com.apple.BiometricKit.enrollmentChanged', match: 'com.apple.BiometricKit_Sim.fingerTouch.match', nomatch: 'com.apple.BiometricKit_Sim.fingerTouch.nomatch' }
+} as const
+
+const MEDIA_EXT = /\.(png|jpe?g|gif|heic|heif|webp|mov|mp4|m4v)$/i
+
+export async function runSimulatorAction(udidRaw: unknown, raw: unknown): Promise<SimulatorActionResult> {
+ const avd = typeof udidRaw === 'string' ? avdNameOf(udidRaw) : null
+ if (avd) {
+ const action = normalizeSimulatorAction(raw)
+ return action ? runAndroidAction(avd, action) : { ok: false, error: 'That action is not available.' }
+ }
+ if (process.platform !== 'darwin') return { ok: false, error: 'iOS simulators need macOS.' }
+ if (typeof udidRaw !== 'string' || !SIMULATOR_UDID.test(udidRaw)) return { ok: false, error: 'Pick a simulator.' }
+ const udid = udidRaw.toUpperCase()
+ const action = normalizeSimulatorAction(raw)
+ if (!action) return { ok: false, error: 'That action is not available.' }
+ try {
+ return await perform(udid, action)
+ } catch (e) {
+ return { ok: false, error: errorText(e) }
+ }
+}
+
+async function perform(udid: string, a: SimulatorAction): Promise<SimulatorActionResult> {
+ switch (a.a) {
+ case 'appearance':
+ await simctl(['ui', udid, 'appearance', a.value])
+ return { ok: true, message: a.value === 'dark' ? 'Dark appearance' : 'Light appearance' }
+ case 'content-size':
+ await simctl(['ui', udid, 'content_size', a.value])
+ return { ok: true }
+ case 'increase-contrast':
+ await simctl(['ui', udid, 'increase_contrast', a.value ? 'enabled' : 'disabled'])
+ return { ok: true }
+ case 'location-set':
+ await simctl(['location', udid, 'set', `${a.lat},${a.lon}`])
+ return { ok: true, message: `Location set to ${a.lat}, ${a.lon}` }
+ case 'location-run':
+ await simctl(['location', udid, 'run', a.scenario])
+ return { ok: true, message: `Simulating “${a.scenario}”` }
+ case 'location-clear':
+ await simctl(['location', udid, 'clear'])
+ return { ok: true, message: 'Location simulation stopped' }
+ case 'status-bar': {
+ if (a.preset === 'clear') {
+ await simctl(['status_bar', udid, 'clear'])
+ return { ok: true, message: 'Status bar back to normal' }
+ }
+ const args = ['status_bar', udid, 'override']
+ if (a.preset === 'battery') {
+ args.push('--batteryLevel', String(a.batteryLevel), '--batteryState', a.batteryState)
+ await simctl(args)
+ return { ok: true, message: `Battery ${a.batteryLevel}% (${a.batteryState})` }
+ }
+ args.push('--time', '9:41', '--dataNetwork', 'wifi', '--wifiMode', 'active', '--wifiBars', '3', '--cellularMode', 'active', '--cellularBars', '4', '--batteryState', 'charged', '--batteryLevel', '100')
+ await simctl(args)
+ return { ok: true, message: 'Clean status bar (9:41, full battery)' }
+ }
+ case 'shake':
+ await notify(udid, 'com.apple.UIKit.SimulatorShake')
+ return { ok: true, message: 'Shake' }
+ case 'biometric': {
+ const names = BIOMETRIC[a.kind]
+ if (a.op === 'enroll' || a.op === 'unenroll') {
+ await notify(udid, names.enrolled, a.op === 'enroll' ? 1 : 0)
+ return { ok: true, message: `${a.kind === 'face' ? 'Face ID' : 'Touch ID'} ${a.op === 'enroll' ? 'enrolled' : 'not enrolled'}` }
+ }
+ await notify(udid, a.op === 'match' ? names.match : names.nomatch)
+ return { ok: true, message: a.op === 'match' ? 'Matching ' + (a.kind === 'face' ? 'face' : 'finger') : 'Non-matching ' + (a.kind === 'face' ? 'face' : 'finger') }
+ }
+ case 'open-url':
+ await simctl(['openurl', udid, a.url])
+ return { ok: true }
+ case 'push':
+ await simctl(['push', udid, a.bundleId, '-'], { input: a.payload })
+ return { ok: true, message: `Push sent to ${a.bundleId}` }
+ case 'privacy':
+ await simctl(['privacy', udid, a.op, a.service, ...(a.bundleId ? [a.bundleId] : [])])
+ return { ok: true, message: a.op === 'reset' && !a.bundleId ? 'All permissions reset' : `Permissions ${a.op === 'grant' ? 'granted' : a.op === 'revoke' ? 'revoked' : 'reset'}` }
+ case 'pasteboard':
+ // pbsync carries text AND images, in either direction.
+ await simctl(a.dir === 'to-device' ? ['pbsync', 'host', udid] : ['pbsync', udid, 'host'])
+ return { ok: true, message: a.dir === 'to-device' ? 'Mac clipboard sent to the device' : 'Device clipboard copied to the Mac' }
+ case 'install': {
+ const s = await stat(a.path).catch(() => null)
+ if (!s?.isDirectory() || !a.path.endsWith('.app')) return { ok: false, error: 'Choose a built .app (an iOS Simulator build).' }
+ await simctl(['install', udid, a.path], { timeout: 300_000 })
+ return { ok: true, message: `Installed ${path.basename(a.path)}` }
+ }
+ case 'add-media': {
+ const files = a.paths.filter((p) => MEDIA_EXT.test(p))
+ if (files.length === 0) return { ok: false, error: 'Only photos and videos can be added to the library.' }
+ await simctl(['addmedia', udid, ...files], { timeout: 300_000 })
+ return { ok: true, message: `Added ${files.length} ${files.length === 1 ? 'item' : 'items'} to Photos` }
+ }
+ case 'restart':
+ await simctl(['shutdown', udid]).catch(() => undefined)
+ await simctl(['boot', udid])
+ return { ok: true, message: 'Restarting…' }
+ case 'erase':
+ // Erase needs a shut-down device; boot it again so the node keeps showing it.
+ await simctl(['shutdown', udid]).catch(() => undefined)
+ await simctl(['erase', udid], { timeout: 300_000 })
+ await simctl(['boot', udid])
+ return { ok: true, message: 'Content and settings erased' }
+ case 'open-devicehub':
+ await run('/usr/bin/open', ['-b', 'com.apple.dt.Devices'], { timeout: 15_000 })
+ return { ok: true }
+ case 'clipboard-set':
+ return { ok: false, error: 'Not available on iOS (⌘V syncs the clipboard instead).' }
+ }
+}
+
+/** The settings the menu shows a ✓ for, plus the location scenarios to list. Each part is read on
+ * its own: one that fails (an old runtime, a setting a platform lacks) is simply absent. */
+export async function readSimulatorState(udidRaw: unknown): Promise<SimulatorDeviceState> {
+ const avd = typeof udidRaw === 'string' ? avdNameOf(udidRaw) : null
+ if (avd) return readAndroidState(avd)
+ if (process.platform !== 'darwin' || typeof udidRaw !== 'string' || !SIMULATOR_UDID.test(udidRaw)) return {}
+ const udid = udidRaw.toUpperCase()
+ const read = (args: string[]) => simctl(args, { timeout: 15_000 }).then((s) => s.trim()).catch(() => '')
+ const [appearance, contrast, size, scenarios] = await Promise.all([
+ read(['ui', udid, 'appearance']),
+ read(['ui', udid, 'increase_contrast']),
+ read(['ui', udid, 'content_size']),
+ read(['location', udid, 'list'])
+ ])
+ return {
+ ...(appearance === 'light' || appearance === 'dark' ? { appearance } : {}),
+ ...(contrast === 'enabled' || contrast === 'disabled' ? { increaseContrast: contrast === 'enabled' } : {}),
+ ...(size && size !== 'unknown' && size !== 'unsupported' ? { contentSize: size } : {}),
+ locationScenarios: parseLocationScenarios(scenarios)
+ }
+}
+
+/**
+ * `simctl location list` prints a table — MEASURED (Xcode 27):
+ * Name Description
+ * ========================================================
+ * City Run City Run
+ * The name is the first column; columns are separated by runs of spaces (names have single ones).
+ */
+export function parseLocationScenarios(text: string): string[] {
+ return text
+ .split('\n')
+ .map((l) => l.trim())
+ .filter((l) => l && !/^=+$/.test(l) && !/^name\s{2,}description$/i.test(l))
+ .map((l) => l.split(/\s{2,}/)[0])
+ .filter((n) => n && n.length <= 100)
+}
+
+// ── Capture ────────────────────────────────────────────────────────────────────────────────────
+
+export function stamp(): string {
+ const d = new Date()
+ const p = (n: number) => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} at ${p(d.getHours())}.${p(d.getMinutes())}.${p(d.getSeconds())}`
+}
+
+export function safeName(s: string): string {
+ return s.replace(/[^A-Za-z0-9 ()._-]/g, '').trim().slice(0, 60) || 'Simulator'
+}
+
+/** Where captures land: the Desktop, as DeviceHub/Simulator.app put them; the canvas copy goes in
+ * nodeterm's own folder so dropping it on the canvas does not litter the Desktop. */
+export async function captureDir(target: SimulatorCaptureTarget): Promise<string> {
+ const dir = target === 'desktop' ? path.join(os.homedir(), 'Desktop') : path.join(platform().userDataDir, 'simulator-captures')
+ await mkdir(dir, { recursive: true })
+ return dir
+}
+
+export async function takeScreenshot(udidRaw: unknown, screenIdRaw: unknown, targetRaw: unknown, nameRaw: unknown): Promise<SimulatorActionResult & { path?: string }> {
+ const avd = typeof udidRaw === 'string' ? avdNameOf(udidRaw) : null
+ if (avd) {
+ const target: SimulatorCaptureTarget = targetRaw === 'clipboard' || targetRaw === 'canvas' ? targetRaw : 'desktop'
+ return androidScreenshot(avd, target, String(nameRaw ?? ''))
+ }
+ if (process.platform !== 'darwin' || typeof udidRaw !== 'string' || !SIMULATOR_UDID.test(udidRaw)) return { ok: false, error: 'Pick a simulator.' }
+ const target: SimulatorCaptureTarget = targetRaw === 'clipboard' || targetRaw === 'canvas' ? targetRaw : 'desktop'
+ const screenId = Number.isInteger(screenIdRaw) && (screenIdRaw as number) > 0 ? (screenIdRaw as number) : undefined
+ const file = path.join(await captureDir(target === 'desktop' ? 'desktop' : 'canvas'), `Simulator Screenshot - ${safeName(String(nameRaw ?? ''))} - ${stamp()}.png`)
+ try {
+ await simctl(['io', udidRaw.toUpperCase(), 'screenshot', '--type=png', ...(screenId ? [`--display=${screenId}`] : []), file])
+ if (target === 'clipboard') {
+ // macOS's own clipboard, as PNG data (core has no Electron clipboard).
+ await run('/usr/bin/osascript', ['-e', `set the clipboard to (read (POSIX file ${JSON.stringify(file)}) as «class PNGf»)`], { timeout: 15_000 })
+ return { ok: true, message: 'Screenshot copied to the clipboard' }
+ }
+ return { ok: true, path: file, message: target === 'desktop' ? 'Screenshot saved to the Desktop' : undefined }
+ } catch (e) {
+ return { ok: false, error: errorText(e) }
+ }
+}
+
+const recordings = new Map<string, { child: ChildProcess; file: string }>()
+
+export async function startRecording(udidRaw: unknown, screenIdRaw: unknown, nameRaw: unknown): Promise<SimulatorActionResult> {
+ if (typeof udidRaw === 'string' && avdNameOf(udidRaw)) return { ok: false, error: 'Recording an Android device is not supported yet.' }
+ if (process.platform !== 'darwin' || typeof udidRaw !== 'string' || !SIMULATOR_UDID.test(udidRaw)) return { ok: false, error: 'Pick a simulator.' }
+ const udid = udidRaw.toUpperCase()
+ if (recordings.has(udid)) return { ok: false, error: 'Already recording this simulator.' }
+ const screenId = Number.isInteger(screenIdRaw) && (screenIdRaw as number) > 0 ? (screenIdRaw as number) : undefined
+ const file = path.join(await captureDir('desktop'), `Simulator Recording - ${safeName(String(nameRaw ?? ''))} - ${stamp()}.mp4`)
+ const child = spawn(SIMCTL[0], [SIMCTL[1], 'io', udid, 'recordVideo', '--codec=h264', '--force', ...(screenId ? [`--display=${screenId}`] : []), file], { stdio: ['ignore', 'ignore', 'pipe'] })
+ // simctl writes "Recording started" to stderr once the first frame is in.
+ const started = await new Promise<boolean>((resolve) => {
+ let err = ''
+ const t = setTimeout(() => resolve(false), 15_000)
+ child.stderr?.on('data', (d) => {
+ err += String(d)
+ if (/Recording started/i.test(err)) {
+ clearTimeout(t)
+ resolve(true)
+ }
+ })
+ child.on('exit', () => {
+ clearTimeout(t)
+ resolve(false)
+ })
+ })
+ if (!started) {
+ child.kill('SIGINT')
+ return { ok: false, error: 'Recording did not start.' }
+ }
+ recordings.set(udid, { child, file })
+ child.on('exit', () => recordings.delete(udid))
+ return { ok: true }
+}
+
+/** Stop and finalise: SIGINT is simctl's own "stop" (it flushes the in-flight frames). */
+export async function stopRecording(udidRaw: unknown): Promise<SimulatorActionResult & { path?: string }> {
+ if (typeof udidRaw !== 'string') return { ok: false, error: 'Not recording.' }
+ const r = recordings.get(udidRaw.toUpperCase())
+ if (!r) return { ok: false, error: 'Not recording.' }
+ await new Promise<void>((resolve) => {
+ const t = setTimeout(() => {
+ r.child.kill('SIGKILL')
+ resolve()
+ }, 20_000)
+ r.child.on('exit', () => {
+ clearTimeout(t)
+ resolve()
+ })
+ r.child.kill('SIGINT')
+ })
+ recordings.delete(udidRaw.toUpperCase())
+ const s = await stat(r.file).catch(() => null)
+ return s && s.size > 0 ? { ok: true, path: r.file, message: 'Recording saved to the Desktop' } : { ok: false, error: 'The recording was empty.' }
+}
+
+export function isRecording(udidRaw: unknown): boolean {
+ return typeof udidRaw === 'string' && recordings.has(udidRaw.toUpperCase())
+}
+
+export function stopAllRecordings(): void {
+ for (const r of recordings.values()) r.child.kill('SIGINT')
+}
+
+export function registerSimulatorActionIpc(): void {
+ platform().handle(IPC.simulatorAction, (udid: unknown, action: unknown) => runSimulatorAction(udid, action))
+ platform().handle(IPC.simulatorState, (udid: unknown) => readSimulatorState(udid))
+ platform().handle(IPC.simulatorScreenshot, (udid: unknown, screenId: unknown, target: unknown, name: unknown) =>
+ takeScreenshot(udid, screenId, target, name)
+ )
+ platform().handle(IPC.simulatorRecordStart, (udid: unknown, screenId: unknown, name: unknown) => startRecording(udid, screenId, name))
+ platform().handle(IPC.simulatorRecordStop, (udid: unknown) => stopRecording(udid))
+ platform().handle(IPC.simulatorRecording, (udid: unknown) => isRecording(udid))
+}
diff --git a/src/core/simulator/simulator-service.test.ts b/src/core/simulator/simulator-service.test.ts
new file mode 100644
index 000000000..4f8f49e0d
--- /dev/null
+++ b/src/core/simulator/simulator-service.test.ts
@@ -0,0 +1,107 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { NO_DISPLAY_MESSAGE, frameParser, parseBridgeStatus, setSimulatorNodeRefusal, startSimulator } from './simulator-service'
+import { SIMBRIDGE_SOURCE } from './simbridge-source'
+
+function frame(w: number, h: number, display: number, jpeg: Buffer): Buffer {
+ const head = Buffer.alloc(20)
+ head.write('NTF2', 0, 'latin1')
+ head.writeUInt32LE(w, 4)
+ head.writeUInt32LE(h, 8)
+ head.writeUInt32LE(display, 12)
+ head.writeUInt32LE(jpeg.length, 16)
+ return Buffer.concat([head, jpeg])
+}
+
+describe('frameParser', () => {
+ it('reassembles frames split across chunks, and several in one chunk', () => {
+ const got: Array<{ width: number; display: number; bytes: string }> = []
+ const parse = frameParser((f) => got.push({ width: f.width, display: f.display, bytes: Buffer.from(f.jpeg).toString() }))
+ const a = frame(900, 1956, 0, Buffer.from('first'))
+ const b = frame(600, 870, 1, Buffer.from('second'))
+ const all = Buffer.concat([a, b])
+ expect(parse(all.subarray(0, 7))).toBe(true)
+ expect(parse(all.subarray(7, 30))).toBe(true)
+ expect(parse(all.subarray(30))).toBe(true)
+ expect(got).toEqual([
+ { width: 900, display: 0, bytes: 'first' },
+ { width: 600, display: 1, bytes: 'second' }
+ ])
+ })
+ it('rejects a stream that is not frames', () => {
+ expect(frameParser(() => undefined)(Buffer.from('garbage-that-is-long-enough'))).toBe(false)
+ })
+})
+
+describe('parseBridgeStatus', () => {
+ it('reads displays, ready and errors; ignores anything else', () => {
+ expect(parseBridgeStatus('{"ok":"ready"}')).toEqual({ kind: 'ready' })
+ expect(
+ parseBridgeStatus('{"ok":"displays","active":1,"pinned":false,"displays":[{"index":0,"width":2007,"height":2853,"name":"LCD-1","screenID":3},{"index":1,"width":1398,"height":2034,"name":"LCD"}]}')
+ ).toEqual({
+ kind: 'displays',
+ active: 1,
+ pinned: false,
+ displays: [
+ { index: 0, width: 2007, height: 2853, name: 'LCD-1', screenID: 3 },
+ { index: 1, width: 1398, height: 2034, name: 'LCD', screenID: 0 }
+ ]
+ })
+ expect(parseBridgeStatus('{"error":"not-booted","message":"the simulator is Shutdown"}')).toEqual({
+ kind: 'error',
+ code: 'not-booted',
+ message: 'the simulator is Shutdown'
+ })
+ expect(parseBridgeStatus('{"error":"no-display","message":"the simulator has no framebuffer display"}')).toEqual({
+ kind: 'error',
+ code: 'no-display',
+ message: NO_DISPLAY_MESSAGE
+ })
+ expect(parseBridgeStatus('not json')).toBeNull()
+ expect(parseBridgeStatus('{"ok":"fps"}')).toBeNull()
+ })
+})
+
+describe('the embedded Swift helper', () => {
+ it('has no template-literal hazards (it lives in a String.raw)', () => {
+ expect(SIMBRIDGE_SOURCE).not.toContain('${')
+ expect(SIMBRIDGE_SOURCE).toContain('dispatchMain()')
+ })
+
+ let swiftc = false
+ try {
+ // xcode-select, not `xcrun --find`: xcrun leaves a cache file in TMPDIR.
+ execFileSync('/usr/bin/xcode-select', ['-p'], { stdio: 'ignore' })
+ swiftc = process.platform === 'darwin'
+ } catch {
+ swiftc = false
+ }
+ it.skipIf(!swiftc)('parses with this machine’s Swift compiler', () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'nt-simbridge-'))
+ try {
+ const src = path.join(dir, 'nt-simbridge.swift')
+ writeFileSync(src, SIMBRIDGE_SOURCE)
+ // xcrun keeps a cache file in TMPDIR; give it this test's own folder so cleanup takes it too.
+ execFileSync('/usr/bin/xcrun', ['swiftc', '-parse', src], { stdio: 'pipe', timeout: 60_000, env: { ...process.env, TMPDIR: dir } })
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ }, 90_000)
+})
+
+describe('node refusal (SSH projects)', () => {
+ it('refuses a node the shell says may not show devices, before touching any device', async () => {
+ setSimulatorNodeRefusal((id) => (id === 'ssh-node' ? 'Simulators run on this machine — not in SSH projects yet.' : null))
+ try {
+ expect(await startSimulator('ssh-node', '00000000-0000-0000-0000-000000000000')).toEqual({
+ ok: false,
+ error: 'Simulators run on this machine — not in SSH projects yet.'
+ })
+ } finally {
+ setSimulatorNodeRefusal(null)
+ }
+ })
+})
diff --git a/src/core/simulator/simulator-service.ts b/src/core/simulator/simulator-service.ts
new file mode 100644
index 000000000..72ee114b7
--- /dev/null
+++ b/src/core/simulator/simulator-service.ts
@@ -0,0 +1,395 @@
+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdir, rm, stat } from 'node:fs/promises'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { IPC } from '../../shared/ipc'
+import {
+ SIMULATOR_NODE_ID,
+ avdNameOf,
+ normalizeDeviceId,
+ normalizeSimulatorInput,
+ type SimulatorDevice,
+ type SimulatorDevicesResult,
+ type SimulatorDisplayInfo,
+ type SimulatorStartResult,
+ type SimulatorStatusEvent
+} from '../../shared/simulator'
+import { SIMULATOR_UDID } from '../../shared/run-config'
+import { bootSimulatorReport, listSimulatorsChecked } from '../run-service'
+import { VM_SHUTDOWN, vmRunState } from './android-grpc'
+import { androidNodeAvd, androidUnary, sendAndroidInput, startAndroid, stopAllAndroid, stopAndroid, type AndroidHooks } from './android-bridge'
+import { bootAndroid, findRunning, listAndroidDevices } from './android-sdk'
+import { renameAtomic, tempNameFor, writeFileAtomic } from '../fs-atomic'
+import { platform } from '../platform'
+import { SIMBRIDGE_SOURCE, SIMBRIDGE_VERSION } from './simbridge-source'
+import { registerSimulatorActionIpc } from './simulator-actions'
+import { createDeviceOwnership } from './device-ownership'
+
+/**
+ * Host side of the Simulator node: a live iOS simulator screen on the canvas, with touch, keyboard
+ * and hardware buttons. macOS desktop only — the helper talks to Xcode's simulator frameworks.
+ *
+ * `nt-simbridge` (simbridge-source.ts) is compiled here on first use with `xcrun swiftc` into
+ * `<userData>/simulator-bridge/<hash>/`, keyed by the helper's source + version + Xcode's build, so
+ * an Xcode update recompiles instead of running a binary built against frameworks that moved.
+ *
+ * One helper per node. Its frames are pushed on `sim:frame:<nodeId>` (the JPEG as a Uint8Array,
+ * structured-cloned by Electron) and its status lines on `sim:status:<nodeId>`; input arrives as
+ * validated commands and is written to its stdin. A node that unmounts stops its helper; a helper
+ * that dies says why.
+ */
+
+const run = promisify(execFile)
+const MAX_SESSIONS = 8
+const FRAME_HEADER = 20
+const MAX_FRAME_BYTES = 16 * 1024 * 1024
+
+/**
+ * ONE helper per device, shared by every node showing it. MEASURED (Xcode 27): a device takes input
+ * from the FIRST HID client only — a second client's touches are silently dropped — so two nodes on
+ * one device, each with its own helper, would leave the second one unable to touch anything.
+ */
+interface Bridge {
+ child: ChildProcessWithoutNullStreams
+ udid: string
+ nodes: Set<string>
+ stderr: string
+ stopping: boolean
+ /** Replayed to a node that joins a running bridge, which would otherwise never hear them. */
+ lastDisplays: SimulatorStatusEvent | null
+ ready: boolean
+}
+
+const bridges = new Map<string, Bridge>()
+/** nodeId → the device it is showing. */
+const nodeDevice = new Map<string, string>()
+
+// ── Compile ──────────────────────────────────────────────────────────────────────────────────────
+
+let xcodeBuild: Promise<string | null> | null = null
+function xcodeBuildVersion(): Promise<string | null> {
+ if (!xcodeBuild) {
+ xcodeBuild = run('/usr/bin/xcodebuild', ['-version'], { timeout: 20_000 })
+ .then(({ stdout }) => stdout.trim().replace(/\s+/g, ' '))
+ .catch(() => null)
+ }
+ return xcodeBuild
+}
+
+let compiling: Promise<{ ok: true; path: string } | { ok: false; error: string }> | null = null
+
+/** The compiled helper for this Xcode, building it once if needed. A failure is not cached:
+ * installing Xcode (or fixing it) should simply work on the next try. */
+export function ensureBridge(): Promise<{ ok: true; path: string } | { ok: false; error: string }> {
+ if (!compiling) {
+ compiling = buildBridge().then((r) => {
+ if (!r.ok) compiling = null
+ return r
+ })
+ }
+ return compiling
+}
+
+async function buildBridge(): Promise<{ ok: true; path: string } | { ok: false; error: string }> {
+ if (process.platform !== 'darwin') return { ok: false, error: 'iOS simulators need macOS.' }
+ const xcode = await xcodeBuildVersion()
+ if (!xcode) return { ok: false, error: 'Xcode was not found (xcodebuild -version failed). Install Xcode to use simulators.' }
+ const hash = createHash('sha256').update(`${SIMBRIDGE_VERSION}\0${xcode}\0${SIMBRIDGE_SOURCE}`).digest('hex').slice(0, 16)
+ const dir = path.join(platform().userDataDir, 'simulator-bridge', hash)
+ const bin = path.join(dir, 'nt-simbridge')
+ try {
+ if ((await stat(bin)).isFile()) return { ok: true, path: bin }
+ } catch {
+ /* build it */
+ }
+ await mkdir(dir, { recursive: true })
+ const src = path.join(dir, 'nt-simbridge.swift')
+ await writeFileAtomic(src, SIMBRIDGE_SOURCE)
+ const tmpBin = tempNameFor(bin)
+ try {
+ await run('/usr/bin/xcrun', ['swiftc', '-O', src, '-o', tmpBin], { timeout: 300_000, maxBuffer: 8 * 1024 * 1024 })
+ await renameAtomic(tmpBin, bin)
+ return { ok: true, path: bin }
+ } catch (e) {
+ await rm(tmpBin, { force: true }).catch(() => undefined)
+ const msg = String((e as { stderr?: string }).stderr || (e as Error).message)
+ const first = msg.split('\n').find((l) => l.includes('error:')) ?? msg.split('\n')[0]
+ return { ok: false, error: `Could not build the simulator helper with this Xcode: ${first}` }
+ }
+}
+
+// ── Sessions ─────────────────────────────────────────────────────────────────────────────────────
+
+function emitStatus(nodeId: string, event: SimulatorStatusEvent): void {
+ platform().broadcast(IPC.simulatorStatus(nodeId), event)
+}
+
+export const NO_DISPLAY_MESSAGE =
+ 'This simulator booted without a working screen. Restart it from the ⋯ menu; if that does not help, use Reset Content and Settings.'
+
+/** Turn one helper status line into an event for the node. Unknown shapes are ignored. */
+export function parseBridgeStatus(line: string): SimulatorStatusEvent | null {
+ let o: Record<string, unknown>
+ try {
+ o = JSON.parse(line) as Record<string, unknown>
+ } catch {
+ return null
+ }
+ if (o.ok === 'ready') return { kind: 'ready' }
+ if (o.ok === 'displays' && Array.isArray(o.displays)) {
+ const displays: SimulatorDisplayInfo[] = []
+ for (const d of o.displays as Array<Record<string, unknown>>) {
+ if (typeof d.index !== 'number' || typeof d.width !== 'number' || typeof d.height !== 'number') continue
+ displays.push({
+ index: d.index,
+ width: d.width,
+ height: d.height,
+ name: typeof d.name === 'string' ? d.name : '',
+ screenID: typeof d.screenID === 'number' ? d.screenID : 0
+ })
+ }
+ return { kind: 'displays', displays, active: typeof o.active === 'number' ? o.active : 0, pinned: o.pinned === true }
+ }
+ if (typeof o.error === 'string') {
+ // A device CoreSimulator reports as Booted with its display down (input alive, no framebuffer) is
+ // a wedged boot: only shutting it down and booting it again brings the screen back, and an erase
+ // when even that fails. Said here, because the helper's own words name only the symptom.
+ if (o.error === 'no-display') return { kind: 'error', code: o.error, message: NO_DISPLAY_MESSAGE }
+ return { kind: 'error', code: o.error, message: typeof o.message === 'string' ? o.message : o.error }
+ }
+ return null
+}
+
+/** Split the helper's stdout into frames: "NTF2" | w | h | display | len | jpeg. */
+export function frameParser(onFrame: (f: { width: number; height: number; display: number; jpeg: Uint8Array }) => void) {
+ let buf: Buffer = Buffer.alloc(0)
+ return (chunk: Buffer): boolean => {
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk
+ while (buf.length >= FRAME_HEADER) {
+ if (buf.toString('latin1', 0, 4) !== 'NTF2') return false
+ const len = buf.readUInt32LE(16)
+ if (len > MAX_FRAME_BYTES) return false
+ if (buf.length < FRAME_HEADER + len) break
+ onFrame({
+ width: buf.readUInt32LE(4),
+ height: buf.readUInt32LE(8),
+ display: buf.readUInt32LE(12),
+ jpeg: new Uint8Array(buf.subarray(FRAME_HEADER, FRAME_HEADER + len))
+ })
+ buf = buf.subarray(FRAME_HEADER + len)
+ }
+ return true
+ }
+}
+
+const androidHooks: AndroidHooks = {
+ frame: (nodeId, f) => platform().broadcast(IPC.simulatorFrame(nodeId), f),
+ status: (nodeId, e) => emitStatus(nodeId, e)
+}
+
+/** Why a node may not show a device at all (an SSH project's node), from the shell that knows which
+ * project owns a node. Null = allowed. The menus already refuse; this is the backstop for a node that
+ * arrives anyway (a hand-edited project file, a project converted to SSH). */
+type NodeRefusal = (nodeId: string) => string | null
+let nodeRefusal: NodeRefusal = () => null
+export function setSimulatorNodeRefusal(fn: NodeRefusal | null): void {
+ nodeRefusal = fn ?? (() => null)
+}
+
+/** The devices this app's Simulator nodes booted — shut down at quit, and nothing else is. */
+const ownership = createDeviceOwnership({
+ iosBooted: async (udid) => {
+ const r = await listSimulatorsChecked()
+ if (r.error) return null
+ const d = r.devices.find((x) => x.id.toUpperCase() === udid.toUpperCase())
+ return d ? d.state === 'booted' : false
+ },
+ androidPid: async (avd) => (await findRunning(avd))?.pid ?? null,
+ shutdownIos: (udid) => run('/usr/bin/xcrun', ['simctl', 'shutdown', udid], { timeout: 30_000 }),
+ // The emulator saves its quick-boot snapshot and exits on its own after this call; quit does not
+ // wait for that (see shutdownOwnedSimulators).
+ shutdownAndroid: (avd) => androidUnary(avd, 'setVmState', vmRunState(VM_SHUTDOWN), 5_000)
+})
+
+export const OWNED_SHUTDOWN_TIMEOUT_MS = 3_000
+
+/** Quit path: shut down the devices the nodes booted, within a bounded wait. Never throws. */
+export async function shutdownOwnedSimulators(timeoutMs = OWNED_SHUTDOWN_TIMEOUT_MS): Promise<void> {
+ try {
+ const asked = await ownership.shutdownOwned(timeoutMs)
+ if (asked.ios.length || asked.android.length) {
+ console.log(`[simulator] shut down at quit: ${[...asked.ios, ...asked.android.map((a) => `avd:${a}`)].join(', ')}`)
+ }
+ } catch (e) {
+ console.warn('[simulator] shutting down booted devices at quit failed:', (e as Error).message)
+ }
+}
+
+export async function startSimulator(nodeId: unknown, udidRaw: unknown): Promise<SimulatorStartResult> {
+ if (typeof nodeId !== 'string' || !SIMULATOR_NODE_ID.test(nodeId)) return { ok: false, error: 'Invalid node.' }
+ const refused = nodeRefusal(nodeId)
+ if (refused) return { ok: false, error: refused }
+ const id = normalizeDeviceId(udidRaw)
+ if (!id) return { ok: false, error: 'Pick a simulator.' }
+ const avd = avdNameOf(id)
+ if (avd) {
+ if (androidNodeAvd(nodeId) !== avd || nodeDevice.has(nodeId)) stopSimulator(nodeId)
+ return startAndroid(nodeId, avd, androidHooks)
+ }
+ const udid = id
+ if (nodeDevice.get(nodeId) !== udid) stopSimulator(nodeId)
+ const running = bridges.get(udid)
+ if (running && !running.stopping) {
+ running.nodes.add(nodeId)
+ nodeDevice.set(nodeId, udid)
+ if (running.lastDisplays) emitStatus(nodeId, running.lastDisplays)
+ if (running.ready) emitStatus(nodeId, { kind: 'ready' })
+ return { ok: true }
+ }
+ if (bridges.size >= MAX_SESSIONS) return { ok: false, error: `At most ${MAX_SESSIONS} simulators can stream at once.` }
+ const helper = await ensureBridge()
+ if (!helper.ok) return helper
+ const child = spawn(helper.path, [udid, '--fps', '30', '--max-width', '900', '--quality', '0.6'], { stdio: ['pipe', 'pipe', 'pipe'] })
+ const bridge: Bridge = { child, udid, nodes: new Set([nodeId]), stderr: '', stopping: false, lastDisplays: null, ready: false }
+ bridges.set(udid, bridge)
+ nodeDevice.set(nodeId, udid)
+ const each = (fn: (id: string) => void) => {
+ for (const id of bridge.nodes) fn(id)
+ }
+ const parse = frameParser((f) => each((id) => platform().broadcast(IPC.simulatorFrame(id), f)))
+ child.stdout.on('data', (chunk: Buffer) => {
+ if (!parse(chunk)) {
+ each((id) => emitStatus(id, { kind: 'error', code: 'protocol', message: 'The simulator helper sent an unreadable frame.' }))
+ child.kill()
+ }
+ })
+ child.stderr.on('data', (chunk: Buffer) => {
+ bridge.stderr += chunk.toString('utf8')
+ let nl: number
+ while ((nl = bridge.stderr.indexOf('\n')) >= 0) {
+ const line = bridge.stderr.slice(0, nl)
+ bridge.stderr = bridge.stderr.slice(nl + 1)
+ const event = parseBridgeStatus(line)
+ if (!event) continue
+ if (event.kind === 'displays') bridge.lastDisplays = event
+ if (event.kind === 'ready') bridge.ready = true
+ each((id) => emitStatus(id, event))
+ }
+ if (bridge.stderr.length > 64 * 1024) bridge.stderr = bridge.stderr.slice(-8 * 1024)
+ })
+ child.on('error', (e) => each((id) => emitStatus(id, { kind: 'error', code: 'spawn', message: e.message })))
+ child.on('exit', (code, signal) => {
+ if (bridges.get(udid) === bridge) bridges.delete(udid)
+ if (!bridge.stopping) each((id) => emitStatus(id, { kind: 'exited', code: code ?? null, signal: signal ?? null }))
+ for (const id of bridge.nodes) if (nodeDevice.get(id) === udid) nodeDevice.delete(id)
+ })
+ child.stdin.on('error', () => undefined) // the helper exiting closes stdin; its exit event says why
+ return { ok: true }
+}
+
+export function stopSimulator(nodeId: unknown): void {
+ if (typeof nodeId !== 'string') return
+ stopAndroid(nodeId)
+ const udid = nodeDevice.get(nodeId)
+ nodeDevice.delete(nodeId)
+ const b = udid ? bridges.get(udid) : undefined
+ if (!b) return
+ b.nodes.delete(nodeId)
+ if (b.nodes.size > 0) return // another node still shows this device
+ b.stopping = true
+ bridges.delete(b.udid)
+ b.child.stdin.end() // the helper exits when stdin closes
+ setTimeout(() => {
+ if (b.child.exitCode === null && b.child.signalCode === null) b.child.kill('SIGTERM')
+ }, 1000).unref?.()
+}
+
+export function sendSimulatorInput(nodeId: unknown, raw: unknown): boolean {
+ if (typeof nodeId !== 'string') return false
+ const cmd = normalizeSimulatorInput(raw)
+ if (cmd && androidNodeAvd(nodeId)) return sendAndroidInput(nodeId, cmd)
+ const udid = nodeDevice.get(nodeId)
+ const b = udid ? bridges.get(udid) : undefined
+ if (!b || !cmd || b.child.stdin.destroyed) return false
+ b.child.stdin.write(JSON.stringify(cmd) + '\n')
+ return true
+}
+
+export function stopAllSimulators(): void {
+ for (const id of [...nodeDevice.keys()]) stopSimulator(id)
+ stopAllAndroid()
+}
+
+export async function shutdownSimulator(udid: unknown): Promise<boolean> {
+ const avd = typeof udid === 'string' ? avdNameOf(udid) : null
+ if (avd) {
+ // SHUTDOWN is what closing the emulator window does: Android is told, then the emulator exits
+ // (saving its quick-boot snapshot when the AVD keeps one).
+ if (!(await findRunning(avd))) return true
+ try {
+ await androidUnary(avd, 'setVmState', vmRunState(VM_SHUTDOWN))
+ } catch {
+ return false
+ }
+ for (let i = 0; i < 60; i++) {
+ if (!(await findRunning(avd))) {
+ ownership.releaseAndroid(avd)
+ return true
+ }
+ await new Promise((r) => setTimeout(r, 500))
+ }
+ return false
+ }
+ if (process.platform !== 'darwin' || typeof udid !== 'string' || !SIMULATOR_UDID.test(udid)) return false
+ try {
+ await run('/usr/bin/xcrun', ['simctl', 'shutdown', udid], { timeout: 60_000 })
+ ownership.releaseIos(udid)
+ return true
+ } catch (e) {
+ const already = /current state: Shutdown/i.test(String((e as { stderr?: string }).stderr ?? ''))
+ if (already) ownership.releaseIos(udid)
+ return already
+ }
+}
+
+/** Every simulator the node can show: iOS simulators (macOS) and Android virtual devices. */
+export async function listSimulatorDevices(): Promise<SimulatorDevicesResult> {
+ const [sims, android] = await Promise.all([listSimulatorsChecked(), listAndroidDevices()])
+ // A device seen shut down is no longer ours: whoever boots it next owns it.
+ for (const d of sims.devices) if (d.state !== 'booted') ownership.releaseIos(d.id)
+ for (const d of android.devices) if (d.state !== 'booted') ownership.releaseAndroid(avdNameOf(d.id) ?? '')
+ const ios: SimulatorDevice[] = sims.devices
+ .map((d) => ({ id: d.id, name: d.name, platform: 'ios' as const, os: d.platform, state: d.state === 'booted' ? 'booted' : 'shutdown' }))
+ return {
+ devices: [...ios, ...android.devices],
+ ...(sims.error ? { iosError: sims.error } : {}),
+ ...(android.error ? { androidError: android.error } : {})
+ }
+}
+
+export async function bootSimulatorDevice(idRaw: unknown): Promise<{ ok: true } | { ok: false; error: string }> {
+ const id = normalizeDeviceId(idRaw)
+ if (!id) return { ok: false, error: 'Pick a simulator.' }
+ const avd = avdNameOf(id)
+ if (avd) {
+ const r = await bootAndroid(avd)
+ // Only an emulator THIS call started is ours to shut down at quit.
+ if (r.ok && r.started) ownership.claimAndroid(avd, r.started.pid)
+ return r.ok ? { ok: true } : r
+ }
+ // Headless: this node is the device's screen (see BootOptions.openWindow).
+ const booted = await bootSimulatorReport(id, { openWindow: false })
+ if (booted === 'booted') ownership.claimIos(id)
+ return booted ? { ok: true } : { ok: false, error: 'Could not boot this simulator.' }
+}
+
+export function registerSimulatorIpc(): void {
+ platform().handle(IPC.simulatorDevices, () => listSimulatorDevices())
+ platform().handle(IPC.simulatorBoot, (id: unknown) => bootSimulatorDevice(id))
+ platform().handle(IPC.simulatorStart, (nodeId: unknown, udid: unknown) => startSimulator(nodeId, udid))
+ platform().handle(IPC.simulatorStop, (nodeId: unknown) => stopSimulator(nodeId))
+ platform().handle(IPC.simulatorInput, (nodeId: unknown, cmd: unknown) => sendSimulatorInput(nodeId, cmd))
+ platform().handle(IPC.simulatorShutdown, (udid: unknown) => shutdownSimulator(udid))
+ registerSimulatorActionIpc()
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 80ffde8be..80ef808eb 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -374,6 +374,9 @@ import { codexCliCaps, registerCodexCliIpc } from '../core/codex-cli'
import { registerWallpaperIpc, setWallpaperImageOps } from '../core/wallpaper'
import { nativeImageWallpaperOps } from './wallpaper-native-image'
import { registerRunConfigIpc, stopAllRunWatches } from '../core/run-service'
+import { registerSimulatorIpc, setSimulatorNodeRefusal, shutdownOwnedSimulators, stopAllSimulators } from '../core/simulator/simulator-service'
+import { SIMULATOR_SSH_HINT } from '../shared/simulator'
+import { stopAllRecordings } from '../core/simulator/simulator-actions'
import {
bindCodexThreadIdentity,
setCodexThreadIdentityAuthSecret,
@@ -1726,6 +1729,9 @@ app.whenReady().then(async () => {
if (process.platform === 'win32') setWallpaperImageOps(nativeImageWallpaperOps)
registerWallpaperIpc(settingsStore)
registerRunConfigIpc()
+ registerSimulatorIpc()
+ // A node of an SSH project would show THIS machine's devices inside another machine's project.
+ setSimulatorNodeRefusal((nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) !== undefined ? `${SIMULATOR_SSH_HINT}.` : null))
// Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the
// renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agent
// node — resolves from cache instead of racing the probe into a conservative "no auto".
@@ -4271,6 +4277,9 @@ app.whenReady().then(async () => {
revokeAllBrowser(browserRevocation, { userStopped: false })
// Reload-on-save watchers die with the app; the runs themselves live on in tmux.
stopAllRunWatches()
+ // Simulator views' helpers exit with their stdin; end them explicitly at quit.
+ stopAllSimulators()
+ stopAllRecordings()
})
ipcMain.on(
IPC.agentControlResult,
@@ -5462,6 +5471,10 @@ app.on('before-quit', (e) => {
// restart-to-update flushes earlier, in the updater — on macOS its windows are gone by now.
// The renderer's save can itself queue a throttled SSH mirror write AFTER the first remote
// flush took its snapshot, so the remote flush runs again once the renderer answered.
+ // Simulators a Simulator node booted run headless, so nothing would show them after we quit:
+ // shut those down (and only those). Started now so it overlaps the flush; it bounds itself
+ // (OWNED_SHUTDOWN_TIMEOUT_MS) and never throws, so quit is never held by a device.
+ const simulatorsDown = shutdownOwnedSimulators()
const flush = Promise.allSettled([
requestRendererFlush(getMainWindow()?.webContents, ipcMain).then(() => remoteWorkspaceIO.flush()),
remoteWorkspaceIO.flush(),
@@ -5474,6 +5487,7 @@ app.on('before-quit', (e) => {
// Napi::ThreadSafeFunction::CallJS) — see SpeechService.shutdown. It needs its own budget
// because the 1500ms cap above is shorter than a transcription, and it costs nothing at
// all when dictation is idle, which is nearly always.
+ .then(() => simulatorsDown)
.then(() => speechService.shutdown())
.finally(() => app.quit())
})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b69cacedd..566d254de 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -585,6 +585,32 @@ const api: NodeTerminalApi = {
load: (w) => ipcRenderer.invoke(IPC.wallpaperLoad, w),
importImage: (p) => ipcRenderer.invoke(IPC.wallpaperImport, p)
},
+ simulator: {
+ devices: (refresh) => ipcRenderer.invoke(IPC.simulatorDevices, refresh === true),
+ boot: (id) => ipcRenderer.invoke(IPC.simulatorBoot, id),
+ start: (nodeId, udid) => ipcRenderer.invoke(IPC.simulatorStart, nodeId, udid),
+ stop: (nodeId) => ipcRenderer.invoke(IPC.simulatorStop, nodeId),
+ input: (nodeId, cmd) => ipcRenderer.invoke(IPC.simulatorInput, nodeId, cmd),
+ shutdown: (udid) => ipcRenderer.invoke(IPC.simulatorShutdown, udid),
+ action: (udid, action) => ipcRenderer.invoke(IPC.simulatorAction, udid, action),
+ state: (udid) => ipcRenderer.invoke(IPC.simulatorState, udid),
+ screenshot: (udid, screenID, target, name) => ipcRenderer.invoke(IPC.simulatorScreenshot, udid, screenID, target, name),
+ startRecording: (udid, screenID, name) => ipcRenderer.invoke(IPC.simulatorRecordStart, udid, screenID, name),
+ stopRecording: (udid) => ipcRenderer.invoke(IPC.simulatorRecordStop, udid),
+ isRecording: (udid) => ipcRenderer.invoke(IPC.simulatorRecording, udid),
+ onFrame: (nodeId, listener) => {
+ const channel = IPC.simulatorFrame(nodeId)
+ const handler = (_e: unknown, frame: import('../shared/simulator').SimulatorFrame) => listener(frame)
+ ipcRenderer.on(channel, handler)
+ return () => ipcRenderer.removeListener(channel, handler)
+ },
+ onStatus: (nodeId, listener) => {
+ const channel = IPC.simulatorStatus(nodeId)
+ const handler = (_e: unknown, event: import('../shared/simulator').SimulatorStatusEvent) => listener(event)
+ ipcRenderer.on(channel, handler)
+ return () => ipcRenderer.removeListener(channel, handler)
+ }
+ },
runConfig: {
entries: (dir) => ipcRenderer.invoke(IPC.runEntries, dir),
devices: (refresh) => ipcRenderer.invoke(IPC.runDevices, refresh),
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 8bfa2c9f1..e8bf5a4f3 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -344,6 +344,25 @@ export function buildStubApi(): Omit<
load: () => Promise.resolve(null),
importImage: U('wallpaper.importImage')
},
+ simulator: {
+ devices: () => Promise.resolve({ devices: [] }),
+ boot: () => Promise.resolve({ ok: false as const, error: 'Simulator views are only available in the desktop app.' }),
+ // DESKTOP only, deliberately not bridged: the helper talks to the simulator frameworks
+ // of the machine it runs on, and a Server Edition / relay tab's canvas is on another one. The
+ // node is not offered there; these say why if reached anyway.
+ start: () => Promise.resolve({ ok: false as const, error: 'Simulator views are only available in the desktop app.' }),
+ stop: () => Promise.resolve(),
+ input: () => Promise.resolve(false),
+ shutdown: () => Promise.resolve(false),
+ action: () => Promise.resolve({ ok: false as const, error: 'Simulator views are only available in the desktop app.' }),
+ state: () => Promise.resolve({}),
+ screenshot: () => Promise.resolve({ ok: false as const, error: 'Simulator views are only available in the desktop app.' }),
+ startRecording: () => Promise.resolve({ ok: false as const, error: 'Simulator views are only available in the desktop app.' }),
+ stopRecording: () => Promise.resolve({ ok: false as const, error: 'Not recording.' }),
+ isRecording: () => Promise.resolve(false),
+ onFrame: () => () => {},
+ onStatus: () => () => {}
+ },
runConfig: {
// Superseded by the real WS-backed namespace in ws-bridge (registerRunConfigIpc runs in the
// server shell). A RELAY tab keeps this: its terminals run on the PEER, so this machine's
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 87e3b2113..749e698b0 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -117,7 +117,9 @@ import { DinoNode } from '../nodes/DinoNode'
import { TriggerNode } from '../nodes/TriggerNode'
import BrowserNode from '../nodes/BrowserNode'
import { FilesNode } from '../nodes/FilesNode'
+import { SimulatorNode } from '../nodes/SimulatorNode'
import type { RunNodeConfig } from '@shared/run-config'
+import type { SimulatorNodeConfig } from '@shared/simulator'
import { normalizeAddress } from '../nodes/browserUrl'
import VideoNode from '../nodes/VideoNode'
import WebNode from '../nodes/WebNode'
@@ -233,6 +235,7 @@ import {
CONTENT_ADD_ITEMS,
agentEntriesToMenuItems,
buildGroupedAddMenu,
+ simulatorRefusal,
type AgentAddEntry,
type AddHandlers
} from '../lib/addMenuSpec'
@@ -898,6 +901,7 @@ import {
createTriggerNode,
createFilesNode,
createRunNode,
+ createSimulatorNode,
createDiffNode,
createEditorNode,
createGroupNode,
@@ -2309,7 +2313,8 @@ export function Canvas() {
video: withNodeBoundary(VideoNode),
web: withNodeBoundary(WebNode),
browser: withNodeBoundary(BrowserNode),
- files: withNodeBoundary(FilesNode)
+ files: withNodeBoundary(FilesNode),
+ simulator: withNodeBoundary(SimulatorNode)
}),
[]
)
@@ -6329,6 +6334,28 @@ export function Canvas() {
return () => window.removeEventListener('nodeterm:open-run-config', onOpenRun)
}, [setNodes, markDirty])
+ /** A Simulator node (see nodes/SimulatorNode): a live iOS simulator or Android emulator screen.
+ * Desktop app only — the menus disable the row elsewhere and this refuses with the same reason. */
+ const addSimulator = useCallback(
+ (center?: { x: number; y: number }, groupId?: string, config?: SimulatorNodeConfig) => {
+ // A relay tab is the host's project: a node there would show THIS machine's devices and be
+ // written into the host's project file.
+ const activeId = useProjects.getState().activeProjectId || ''
+ const project = useProjects.getState().projects.find((p) => p.id === activeId)
+ const refusal = simulatorRefusal(sessionForProject(activeId).source === 'relay', !!project?.ssh)
+ if (refusal) {
+ setCopyError(refusal)
+ return
+ }
+ setNodes((ns) => {
+ const node = createSimulatorNode(ns.length, config, center ?? emptyNodePos())
+ return [...ns, groupId ? parentInto(node, groupId) : node]
+ })
+ markDirty()
+ },
+ [setNodes, markDirty, emptyNodePos, parentInto]
+ )
+
const addSticky = useCallback(
(center?: { x: number; y: number }, groupId?: string) => {
setNodes((ns) => {
@@ -10997,7 +11024,8 @@ export function Canvas() {
hasCwd: !!(useProjects.getState().getProject(activeProjectId)?.ssh?.remoteCwd ??
useProjects.getState().getProject(activeProjectId)?.cwd),
isSshProject,
- isWindowsCore
+ isWindowsCore,
+ isRelayTab: sessionForProject(activeProjectId || '').source === 'relay'
}),
[activeProjectId, isSshProject, isWindowsCore]
)
@@ -11010,6 +11038,7 @@ export function Canvas() {
sticky: (at) => addSticky(at),
files: (at) => addFiles(at),
run: (at) => void addRun(at),
+ simulator: (at) => addSimulator(at),
dino: (at) => addDino(at),
trigger: (at) => addTrigger(at),
openFile: (at) => void openFileDialog(at),
@@ -11023,6 +11052,7 @@ export function Canvas() {
addBrowser,
addFiles,
addRun,
+ addSimulator,
addWebView,
addSticky,
addDino,
@@ -18402,6 +18432,9 @@ export function Canvas() {
...(isSshProject || isWindowsCore
? []
: [{ id: 'new-run', label: 'New run configuration', icon: <IconPlay />, run: () => void addRun() }]),
+ ...(!simulatorRefusal(activeSession.source === 'relay', isSshProject)
+ ? [{ id: 'new-simulator', label: 'New simulator', icon: <IconPhone />, run: () => addSimulator() }]
+ : []),
{ id: 'new-dino', label: 'New dino game', icon: <IconDino />, run: () => addDino() },
{ id: 'open-file', label: 'Open file…', icon: <IconEditor />, run: () => void openFileDialog() },
// "New file…" needs a project folder to create into — hidden when the project has no cwd.
@@ -18710,6 +18743,7 @@ export function Canvas() {
addAgentNode,
addSticky,
addRun,
+ addSimulator,
addDino,
addWebView,
addBrowser,
@@ -20058,6 +20092,7 @@ export function Canvas() {
onAddTrigger={addTrigger}
onAddFiles={() => addFiles()}
onAddRun={() => void addRun()}
+ onAddSimulator={() => addSimulator()}
onAddAgent={(aid, accountId) => addAgentNode(aid, undefined, undefined, accountId)}
onOpenFile={() => void openFileDialog()}
onAddRemote={() => openRemotePicker({ x: window.innerWidth / 2, y: window.innerHeight / 2 })}
diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsx
index 98b1a637d..45bc392a1 100644
--- a/src/renderer/components/Dock.tsx
+++ b/src/renderer/components/Dock.tsx
@@ -33,6 +33,8 @@ interface DockProps {
onAddFiles: () => void
/** A run node (a launch.json configuration) rooted in the project folder. */
onAddRun: () => void
+ /** A Simulator node (macOS desktop). */
+ onAddSimulator: () => void
onAddAgent: (agentId: AgentId, accountId?: string) => void
onOpenFile: () => void
onAddRemote: () => void
@@ -84,6 +86,7 @@ export function Dock({
onAddTrigger,
onAddFiles,
onAddRun,
+ onAddSimulator,
onAddAgent,
onOpenFile,
onAddRemote,
@@ -199,6 +202,7 @@ export function Dock({
trigger: onAddTrigger,
files: onAddFiles,
run: onAddRun,
+ simulator: onAddSimulator,
openFile: onOpenFile,
newFile: onNewFile,
worktree: onAddWorktree
@@ -206,7 +210,8 @@ export function Dock({
const contentRows = contentAddItemsToDockRows(CONTENT_ADD_ITEMS, dockAddHandlers, {
hasCwd,
isSshProject,
- isWindowsCore
+ isWindowsCore,
+ isRelayTab: !!activeProject?.remote
})
return (
diff --git a/src/renderer/lib/addMenuSpec.test.tsx b/src/renderer/lib/addMenuSpec.test.tsx
index ac82d71ef..355074ec6 100644
--- a/src/renderer/lib/addMenuSpec.test.tsx
+++ b/src/renderer/lib/addMenuSpec.test.tsx
@@ -10,6 +10,8 @@ import {
contentAddItemsToDockRows,
FILES_NO_CWD_HINT,
RUN_SSH_HINT,
+ SIMULATOR_RELAY_HINT,
+ SIMULATOR_SSH_HINT,
RUN_WINDOWS_HINT,
NEW_FILE_NO_CWD_HINT,
WORKTREE_NO_CWD_HINT,
@@ -31,6 +33,7 @@ const handlers = (overrides: Partial<AddHandlers> = {}): AddHandlers => ({
sticky: noop,
files: noop,
run: noop,
+ simulator: noop,
dino: noop,
trigger: noop,
openFile: noop,
@@ -44,6 +47,7 @@ const allKinds: AddItem['kind'][] = [
'terminal',
'remote',
'run',
+ 'simulator',
'browser',
'web',
'sticky',
@@ -80,6 +84,27 @@ describe('Run configuration row', () => {
})
})
+describe('Simulator row', () => {
+ it('is disabled with its reason in a relay tab — the node would show this machine’s devices', () => {
+ const ctx = { hasCwd: true, isSshProject: false, isRelayTab: true }
+ const [row] = contentAddItemsToMenuItems([{ kind: 'simulator' }], handlers(), ctx)
+ expect(row).toMatchObject({ label: 'New simulator', disabled: true, hint: SIMULATOR_RELAY_HINT })
+ const [dock] = contentAddItemsToDockRows([{ kind: 'simulator' }], handlers(), ctx)
+ expect(dock).toMatchObject({ kind: 'simulator', disabled: true, hint: SIMULATOR_RELAY_HINT })
+ })
+ it('is disabled with its reason in an SSH project, as the run row is', () => {
+ const ctx = { hasCwd: true, isSshProject: true }
+ const [row] = contentAddItemsToMenuItems([{ kind: 'simulator' }], handlers(), ctx)
+ expect(row).toMatchObject({ label: 'New simulator', disabled: true, hint: SIMULATOR_SSH_HINT })
+ const [dock] = contentAddItemsToDockRows([{ kind: 'simulator' }], handlers(), ctx)
+ expect(dock).toMatchObject({ kind: 'simulator', disabled: true, hint: SIMULATOR_SSH_HINT })
+ })
+ it('is enabled in a local desktop project', () => {
+ const [row] = contentAddItemsToMenuItems([{ kind: 'simulator' }], handlers(), { hasCwd: true, isSshProject: false })
+ expect((row as { disabled?: boolean }).disabled).toBeFalsy()
+ })
+})
+
describe('CONTENT_ADD_ITEMS', () => {
it('lists every content kind in the canonical order', () => {
expect(CONTENT_ADD_ITEMS.map((i) => i.kind)).toEqual(allKinds)
@@ -98,6 +123,7 @@ describe('contentAddItemsToMenuItems', () => {
'New terminal',
'New remote…',
'New run configuration',
+ 'New simulator',
'New browser',
'New web view…',
'New sticky note',
@@ -201,6 +227,7 @@ describe('contentAddItemsToDockRows', () => {
// "New Remote Connection" flow. Emitting a terminal row here duplicated the Terminal entry.
expect(rows.map((r) => r.kind)).toEqual([
'run',
+ 'simulator',
'browser',
'web',
'sticky',
@@ -329,6 +356,7 @@ describe('buildGroupedAddMenu', () => {
}
expect(children(ADD_GROUP_LABEL.view)).toEqual([
'New run configuration',
+ 'New simulator',
'New browser',
'New web view…',
'New sticky note',
diff --git a/src/renderer/lib/addMenuSpec.tsx b/src/renderer/lib/addMenuSpec.tsx
index c77f1a733..a1f9922a6 100644
--- a/src/renderer/lib/addMenuSpec.tsx
+++ b/src/renderer/lib/addMenuSpec.tsx
@@ -30,6 +30,8 @@
import type { ReactNode } from 'react'
import type { MenuItem } from '../components/ContextMenu'
import { ACCOUNT_CAPABLE_AGENT_IDS } from '@shared/agents/account-binding'
+import { SIMULATOR_SSH_HINT } from '@shared/simulator'
+import { isBrowserRuntime } from '../bridge/runtime'
import {
IconAgent,
IconBranch,
@@ -39,6 +41,7 @@ import {
IconExplorer,
IconGroup,
IconNote,
+ IconPhone,
IconPlay,
IconRemote,
IconTerminal,
@@ -58,6 +61,7 @@ export type AddItem =
| { kind: 'terminal' }
| { kind: 'remote' }
| { kind: 'run' } // disabledOnSsh
+ | { kind: 'simulator' } // macOS desktop only
| { kind: 'browser' }
| { kind: 'web' }
| { kind: 'sticky' }
@@ -80,6 +84,7 @@ export const CONTENT_ADD_ITEMS: readonly AddItem[] = [
{ kind: 'terminal' },
{ kind: 'remote' },
{ kind: 'run' },
+ { kind: 'simulator' },
{ kind: 'browser' },
{ kind: 'web' },
{ kind: 'sticky' },
@@ -101,6 +106,9 @@ export interface AddCtx {
/** Whether the core that owns the active project runs on Windows (`hostPlatformFor`). Disables
* "New run configuration" — its launcher is a POSIX `sh` script. Absent = not Windows. */
isWindowsCore?: boolean
+ /** Whether the active project is a relay tab (another machine's core). Disables "New simulator":
+ * the node would show THIS machine's devices inside the host's project. Absent = not relay. */
+ isRelayTab?: boolean
}
/**
@@ -116,6 +124,8 @@ export interface AddHandlers {
remote: (screenPos: { x: number; y: number }) => void
/** A run node (a `.vscode/launch.json` configuration with Run/Stop/Restart), in the project folder. */
run: (at?: AddPos) => void
+ /** A Simulator node: a live iOS simulator screen with touch, keyboard and buttons. */
+ simulator: (at?: AddPos) => void
browser: (at?: AddPos) => void
web: (at?: AddPos) => void
sticky: (at?: AddPos) => void
@@ -134,6 +144,25 @@ export interface AddHandlers {
export const WORKTREE_SSH_HINT = 'Not supported in SSH projects yet'
/** A run node's launcher, processes and (Flutter) simulators all live on THIS machine. */
export const RUN_SSH_HINT = 'Run configurations run on this machine — not in SSH projects yet'
+/** iOS simulators live on the Mac the desktop app runs on; a browser tab (Server Edition) is not it. */
+export const SIMULATOR_UNAVAILABLE_HINT = 'Simulators need the desktop app'
+/** Whether this renderer can show a Simulator node: the desktop app on any OS — Android emulators
+ * run everywhere; iOS simulators are simply absent from the list off macOS. Not a Server Edition
+ * tab, whose emulators would be the server's. */
+export function simulatorAvailable(relayTab = false): boolean {
+ return !isBrowserRuntime() && !relayTab
+}
+/** A relay tab's project lives on another machine; this machine's simulators do not belong in it. */
+export const SIMULATOR_RELAY_HINT = 'Simulators run on this machine — not in a relay tab'
+export { SIMULATOR_SSH_HINT }
+/** The simulator row's gate, one rule for the menu, the Dock, ⌘K and the canvas refusal. */
+export function simulatorRefusal(relayTab = false, sshProject = false): string | undefined {
+ if (isBrowserRuntime()) return SIMULATOR_UNAVAILABLE_HINT
+ if (relayTab) return SIMULATOR_RELAY_HINT
+ if (sshProject) return SIMULATOR_SSH_HINT
+ return undefined
+}
+
/** The core's launcher is a POSIX `sh` script stopped by POSIX signals (see `RUN_WINDOWS_REASON`). */
export const RUN_WINDOWS_HINT = 'Run configurations that launch a process are not supported on Windows yet'
@@ -188,6 +217,17 @@ export function contentAddItemsToMenuItems(
case 'remote':
out.push({ label: 'New remote…', icon: <IconTerminal />, onClick: () => handlers.remote(remotePos) })
break
+ case 'simulator': {
+ const refusal = simulatorRefusal(ctx.isRelayTab, ctx.isSshProject)
+ out.push({
+ label: 'New simulator',
+ icon: <IconPhone />,
+ disabled: !!refusal,
+ hint: refusal,
+ onClick: () => handlers.simulator(at)
+ })
+ break
+ }
case 'run':
out.push({
label: 'New run configuration',
@@ -297,6 +337,18 @@ export function contentAddItemsToDockRows(
// The Dock uses its own "New Remote Connection" affordance, not the remote picker. Skip
// here so the Dock's content rows don't duplicate it.
break
+ case 'simulator': {
+ const refusal = simulatorRefusal(ctx.isRelayTab, ctx.isSshProject)
+ out.push({
+ kind: 'simulator',
+ label: 'Simulator',
+ icon: <IconPhone />,
+ disabled: !!refusal,
+ hint: refusal,
+ onClick: () => handlers.simulator()
+ })
+ break
+ }
case 'run':
out.push({
kind: 'run',
@@ -398,6 +450,7 @@ export const ADD_ITEM_GROUP: Record<AddItem['kind'], AddGroupId> = {
terminal: 'top',
remote: 'top',
run: 'view',
+ simulator: 'view',
browser: 'view',
web: 'view',
sticky: 'view',
diff --git a/src/renderer/lib/nodeSizing.ts b/src/renderer/lib/nodeSizing.ts
index cd7db2662..a66c4390f 100644
--- a/src/renderer/lib/nodeSizing.ts
+++ b/src/renderer/lib/nodeSizing.ts
@@ -23,7 +23,8 @@ export const NODE_MIN_SIZES: Record<NodeKind, { width: number; height: number }>
subagent: { width: 180, height: 84 },
loop: { width: 180, height: 84 },
dino: { width: 400, height: 160 },
- trigger: { width: 240, height: 120 }
+ trigger: { width: 240, height: 120 },
+ simulator: { width: 200, height: 260 }
}
export interface Rect {
diff --git a/src/renderer/lib/reopenNode.ts b/src/renderer/lib/reopenNode.ts
index 78cb8b452..0f7ee6e81 100644
--- a/src/renderer/lib/reopenNode.ts
+++ b/src/renderer/lib/reopenNode.ts
@@ -14,9 +14,11 @@ import {
createDinoNode,
createFilesNode,
createRunNode,
+ createSimulatorNode,
isAccountLoginNode
} from '@renderer/state/workspace'
import { normalizeRunConfig } from '@shared/run-config'
+import { normalizeSimulatorConfig } from '@shared/simulator'
import { absolutePosition, type FocusableNode } from './nodeFocus'
import { normalizeNodeIcon } from '@shared/node-icon'
@@ -195,6 +197,9 @@ function buildBase(snapshot: ReopenNodeSnapshot, ctx: RecreateContext): CanvasNo
return createBrowserNode(0, d.url ?? '', undefined, d.partition)
case 'dino':
return createDinoNode(0, undefined, d.highScore ?? 0)
+ // A Simulator node's whole state is which device it shows.
+ case 'simulator':
+ return createSimulatorNode(0, normalizeSimulatorConfig(d.simulator))
default:
return null
}
diff --git a/src/renderer/nodes/BrowserNode.tsx b/src/renderer/nodes/BrowserNode.tsx
index 3eb50a521..5fb63c7b6 100644
--- a/src/renderer/nodes/BrowserNode.tsx
+++ b/src/renderer/nodes/BrowserNode.tsx
@@ -1,4 +1,4 @@
-import { Handle, NodeResizer, Position, useReactFlow, type NodeProps } from '@xyflow/react'
+import { Handle, NodeResizer, Position, useReactFlow, useStore, type NodeProps } from '@xyflow/react'
import { Tooltip } from '../components/Tooltip'
import { MaximizeButton } from './MaximizeButton'
import { IconClose } from '../components/icons'
@@ -22,6 +22,8 @@ import { useWebviewKeepAlive } from '../state/webviewKeepAlive'
export default function BrowserNode({ id, data, selected }: NodeProps<CanvasNode>) {
const { deleteElements, updateNodeData } = useReactFlow()
const ghost = data.ghost === true
+ const dockTo = typeof data.dockTo === 'string' ? data.dockTo : undefined
+ const canDock = useStore((st) => !ghost && !!dockTo && st.nodeLookup.get(dockTo)?.data?.runConfig !== undefined)
return (
<>
@@ -54,6 +56,18 @@ export default function BrowserNode({ id, data, selected }: NodeProps<CanvasNode
drives a lease, in every case today). */}
<BrowserDrivingIndicator nodeId={id} />
<span className="term-node__spacer" />
+ {/* Popped out of a run node's browser panel: dock it back. */}
+ {canDock && (
+ <Tooltip label="Dock back into its run node">
+ <button
+ className="term-node__close"
+ aria-label="Dock into run node"
+ onClick={() => window.dispatchEvent(new CustomEvent('nodeterm:dock-preview', { detail: { nodeId: id, runNodeId: data.dockTo } }))}
+ >
+ ⇲
+ </button>
+ </Tooltip>
+ )}
<MaximizeButton id={id} maximized={!!data.premaxRect} />
<Tooltip label="Close">
<button className="term-node__close" aria-label="Close" onClick={() => deleteElements({ nodes: [{ id }] })}>
diff --git a/src/renderer/nodes/BrowserStartPage.test.tsx b/src/renderer/nodes/BrowserStartPage.test.tsx
new file mode 100644
index 000000000..ed1223adf
--- /dev/null
+++ b/src/renderer/nodes/BrowserStartPage.test.tsx
@@ -0,0 +1,26 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it } from 'vitest'
+import { useBrowserHistory } from '../state/browserHistory'
+import { BrowserStartPage } from './BrowserStartPage'
+
+;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+describe('BrowserStartPage', () => {
+ // The page used to select `s.recent(8)` — a NEW array on every read, which zustand 5 never sees
+ // as unchanged: "Maximum update depth exceeded" the moment a blank browser showed this page.
+ it('renders the recent list without looping', () => {
+ useBrowserHistory.setState({
+ entries: [
+ { url: 'https://example.com/a', title: 'A', ts: 2 },
+ { url: 'https://example.com/b', title: 'B', ts: 1 }
+ ]
+ })
+ const host = document.createElement('div')
+ const root = createRoot(host)
+ expect(() => act(() => root.render(<BrowserStartPage onNavigate={() => undefined} />))).not.toThrow()
+ expect(host.querySelectorAll('.startpage__recent-item')).toHaveLength(2)
+ act(() => root.unmount())
+ })
+})
diff --git a/src/renderer/nodes/BrowserStartPage.tsx b/src/renderer/nodes/BrowserStartPage.tsx
index 52bad88da..e8b45649c 100644
--- a/src/renderer/nodes/BrowserStartPage.tsx
+++ b/src/renderer/nodes/BrowserStartPage.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { searchOrUrl } from './browserUrl'
import { SHORTCUTS, SiteIcon } from './browserIcons'
import { useBrowserHistory } from '../state/browserHistory'
@@ -14,7 +14,11 @@ function hostLabel(url: string): string {
/** The Chrome-like new-tab page shown inside a blank browser node. */
export function BrowserStartPage({ onNavigate }: { onNavigate: (url: string) => void }): JSX.Element {
const [q, setQ] = useState('')
- const recent = useBrowserHistory((s) => s.recent(8))
+ // Select the stored list itself and slice it here: a selector that returns a NEW array on every
+ // read (`s.recent(8)`) never compares equal, and zustand 5 re-renders on it forever — "Maximum
+ // update depth exceeded" the moment a blank browser shows this page.
+ const entries = useBrowserHistory((s) => s.entries)
+ const recent = useMemo(() => entries.slice(0, 8), [entries])
const submit = (): void => {
const u = searchOrUrl(q)
if (u) onNavigate(u)
diff --git a/src/renderer/nodes/BrowserSurface.tsx b/src/renderer/nodes/BrowserSurface.tsx
index b6d83ce71..f4ddeeb79 100644
--- a/src/renderer/nodes/BrowserSurface.tsx
+++ b/src/renderer/nodes/BrowserSurface.tsx
@@ -27,6 +27,9 @@ type WebviewEl = HTMLElement & ZoomableWebview & {
}
interface BrowserSurfaceProps {
+ /** What to show while there is no page, instead of the new-tab start page (a run node's browser
+ * panel says it is waiting for the run's address). */
+ blank?: React.ReactNode
/** The node id — registers the guest webContents so main can route its new-window requests. */
nodeId: string
/** Initial URL (seeded once at mount). */
@@ -66,7 +69,8 @@ export function BrowserSurface({
partition,
onUrlChange,
onTitleChange,
- onGuestDiscarded
+ onGuestDiscarded,
+ blank
}: BrowserSurfaceProps) {
const ref = useRef<WebviewEl | null>(null)
const rootRef = useRef<HTMLDivElement | null>(null)
@@ -310,7 +314,8 @@ export function BrowserSurface({
style={{ width: '100%', height: '100%' }}
/>
)}
- {!src && !discarded && (
+ {!src && !discarded && blank}
+ {!src && !discarded && !blank && (
<BrowserStartPage
onNavigate={(u) => {
// A navigation with an initiator: whatever it navigates to is not a restore echo.
diff --git a/src/renderer/nodes/RunBar.tsx b/src/renderer/nodes/RunBar.tsx
index dee18b6b6..2fbf89bb0 100644
--- a/src/renderer/nodes/RunBar.tsx
+++ b/src/renderer/nodes/RunBar.tsx
@@ -15,9 +15,22 @@ import {
type RunStatus
} from '@shared/run-config'
import { isShellCommand } from '@shared/agents/pane'
+import { SIMULATOR_UDID, embedsFlutterWeb } from '@shared/run-config'
+import { INLINE_SIM_HEIGHT, type InlineSimulatorConfig, type SimulatorNodeConfig } from '@shared/simulator'
+import { SimulatorView } from './SimulatorNode'
+import { BrowserSurface } from './BrowserSurface'
+import {
+ isWebDeviceId,
+ isPreviewUrl,
+ localUrlFromOutput,
+ previewKindFor,
+ type PreviewKind,
+ type RunBrowserConfig
+} from '@shared/run-preview'
+import { simulatorAvailable } from '../lib/addMenuSpec'
import { useSession } from '../session/session'
import { useProjects } from '../state/projects'
-import { terminalNodeSize, type CanvasNode } from '../state/workspace'
+import { createBrowserNode, createSimulatorNode, terminalNodeSize, type CanvasNode } from '../state/workspace'
import { IconPlay, IconReload } from '../components/icons'
/**
@@ -51,6 +64,10 @@ interface Props {
config: RunNodeConfig
/** A compound's sibling: start the run once on mount. */
autoStart: boolean
+ /** The simulator shown inside this node, when it is (`data.runSimulator`). */
+ simulator?: InlineSimulatorConfig
+ /** The browser shown inside this node, when it is (`data.runBrowser`). */
+ browser?: RunBrowserConfig
}
/** Node id → title → device, for every run node on the live canvas, as one primitive. */
@@ -86,9 +103,10 @@ function parseSig(sig: string): Array<{ id: string; title: string; runConfig: {
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
-export function RunBar({ nodeId, config, autoStart }: Props) {
- const { api } = useSession()
- const { updateNodeData, setNodes } = useReactFlow()
+export function RunBar({ nodeId, config, autoStart, simulator, browser: browserPanel }: Props) {
+ const session = useSession()
+ const { api } = session
+ const { updateNodeData, setNodes, getNodes } = useReactFlow()
const [listing, setListing] = useState<RunEntriesResult | null>(null)
const [devices, setDevices] = useState<RunDevice[] | null>(null)
const [devicesError, setDevicesError] = useState<string | null>(null)
@@ -103,6 +121,10 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
const cfgRef = useRef(config)
cfgRef.current = config
+ // The preview panel, for the run-start path above it (see the 📱 / 🌐 section below).
+ const browserOpenRef = useRef(false)
+ const popOutRef = useRef<{ kind: PreviewKind; id: string } | null>(null)
+ const setPreviewRef = useRef<(next: { kind: 'browser'; cfg: RunBrowserConfig }) => void>(() => undefined)
/** The entry the node resolves to now (kept current below), for callbacks and the status poll. */
const entryRef = useRef<LaunchEntry | undefined>(undefined)
const running = !!status?.running
@@ -276,8 +298,14 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
}
if (r.kind === 'browser') {
setBusy(null)
- window.dispatchEvent(new CustomEvent('nodeterm:open-url-node', { detail: { url: r.url, sourceNodeId: nodeId } }))
- if (!/^https?:\/\//i.test(r.url)) say('error', `Only http(s) URLs open in a browser node (${r.url}).`)
+ if (!isPreviewUrl(r.url)) {
+ say('error', `Only http(s) URLs open in the browser panel (${r.url}).`)
+ return
+ }
+ // The page opens in this node's browser panel (or the panel popped out of it).
+ const out = popOutRef.current
+ if (out?.kind === 'browser') updateNodeData(out.id, { url: r.url })
+ else setPreviewRef.current({ kind: 'browser', cfg: { url: r.url } })
return
}
if (r.kind === 'compound') {
@@ -302,6 +330,12 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
runningRef.current = { projectDir: cfg.projectDir, deviceId: cfg.deviceId, flavor: target?.flavor, hotReload: r.hotReload }
const sent = await api.pty.sendText(nodeId, r.command)
setNeedsRerun(false)
+ // A Flutter web run that opted in to showing here (the host runs it on Flutter's web server —
+ // see `webServerDevice`): open the browser panel for it, unless it is open or popped out already.
+ const runDevice = target?.pinnedDevice ?? cfg.deviceId
+ if (target?.usesDevice && isWebDeviceId(runDevice) && embedsFlutterWeb(cfg) && !browserOpenRef.current) {
+ setPreviewRef.current({ kind: 'browser', cfg: {} })
+ }
if (sent === 'pasted-not-submitted') say('info', 'The command is in the terminal — press Enter to start.')
else if (sent !== true) say('error', 'Could not type into this terminal.')
const deadline = Date.now() + 15_000
@@ -488,14 +522,225 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
}, [nodeId, setNodes])
useLayoutEffect(() => {
- if (showTerminal) return
+ // With a simulator open the NODE's size is the user's: the panel fills it and scales with it.
+ if (showTerminal || simulator || browserPanel) return
const bar = barRef.current
if (!bar) return
fitCompact()
const ro = new ResizeObserver(() => fitCompact())
ro.observe(bar)
return () => ro.disconnect()
- }, [showTerminal, fitCompact])
+ }, [showTerminal, simulator, browserPanel, fitCompact])
+
+ // ── 📱 / 🌐 The preview panel, inside this node ────────────────────────────────────────────
+ //
+ // One panel under the control rows, of the kind the run calls for (`previewKindFor`): a simulator
+ // for a run on a phone (its device preselected when it is one — an iOS UDID, or an Android
+ // emulator's adb serial, which is what Flutter names it — else empty to pick any), a browser for a
+ // run that targets one or serves a page (its URL from the launch configuration, or picked out of
+ // the run's output once it prints one). The button opens and closes it; ⇱ pops it out into its
+ // own node, whose ⇲ (or this button) docks it back. While it is open the panel fills the node, so
+ // resizing the node scales it; the compact fit above stands down. Opening grows the node by a
+ // panel's worth; closing hands it back (the compact fit, or the same amount with the terminal shown).
+
+ const panelRef = useRef<HTMLDivElement>(null)
+ const previewKind = previewKindFor({
+ picksDevice: showDevice,
+ deviceId: config.deviceId,
+ deviceKind: device?.kind,
+ browserConfig: !!entry?.browser,
+ pinnedDeviceId: entry?.usesDevice ? entry.pinnedDevice : undefined
+ })
+ const panelOpen = !!simulator || !!browserPanel
+ /** A panel popped out of this node into its own: its id and kind. Read as one primitive. */
+ const poppedOutSig = useStore((st) => {
+ for (const n of st.nodeLookup.values()) {
+ if (n.type === 'simulator' && (n.data.simulator as SimulatorNodeConfig | undefined)?.dockTo === nodeId) return `simulator:${n.id}`
+ if (n.type === 'browser' && n.data.dockTo === nodeId) return `browser:${n.id}`
+ }
+ return ''
+ })
+ const poppedOut = poppedOutSig ? { kind: poppedOutSig.slice(0, poppedOutSig.indexOf(':')) as PreviewKind, id: poppedOutSig.slice(poppedOutSig.indexOf(':') + 1) } : null
+ browserOpenRef.current = !!browserPanel || poppedOut?.kind === 'browser'
+ popOutRef.current = poppedOut
+
+ /** The kind the button shows: an open or popped-out panel's own, else what the run calls for. */
+ const shownKind: PreviewKind = simulator ? 'simulator' : browserPanel ? 'browser' : poppedOut ? poppedOut.kind : previewKind
+
+ type Preview = { kind: 'simulator'; cfg: InlineSimulatorConfig } | { kind: 'browser'; cfg: RunBrowserConfig } | undefined
+
+ /** Show `next` inside this node (or nothing), resizing the node around the change. `extra` adds or
+ * removes other nodes in the same update (pop out / dock back). */
+ const setPreview = useCallback(
+ (next: Preview, extra?: (ns: CanvasNode[]) => CanvasNode[]) => {
+ const panelNow = panelRef.current?.offsetHeight || INLINE_SIM_HEIGHT
+ setNodes((all) => {
+ const ns = (extra ? extra(all as CanvasNode[]) : all) as CanvasNode[]
+ return ns.map((n) => {
+ if (n.id !== nodeId) return n
+ const was = !!n.data.runSimulator || !!n.data.runBrowser
+ const data = {
+ ...n.data,
+ runSimulator: next?.kind === 'simulator' ? next.cfg : undefined,
+ runBrowser: next?.kind === 'browser' ? next.cfg : undefined
+ }
+ if (was === !!next) return { ...n, data }
+ const showing = !!(n.data.runConfig as RunNodeConfig | undefined)?.showTerminal
+ // Hidden terminal + closing: the compact fit takes the height back by itself.
+ if (!next && !showing) return { ...n, data }
+ const now = (n.height as number | undefined) ?? n.measured?.height ?? 0
+ const height = Math.max(120, now + (next ? INLINE_SIM_HEIGHT : -panelNow))
+ return { ...n, height, style: { ...n.style, height }, data }
+ })
+ })
+ },
+ [nodeId, setNodes]
+ )
+
+ setPreviewRef.current = setPreview
+
+ /** ⇲ / the button on a popped-out panel: its node goes, and it comes back inside this one. */
+ const dockBack = useCallback(
+ (otherId: string) => {
+ const other = getNodes().find((n) => n.id === otherId)
+ if (!other) return
+ const remove = (ns: CanvasNode[]) => ns.filter((n) => n.id !== otherId)
+ if (other.type === 'browser') {
+ const url = other.data.url as string | undefined
+ setPreview({ kind: 'browser', cfg: isPreviewUrl(url) ? { url } : {} }, remove)
+ return
+ }
+ const { dockTo: _d, ...device } = (other.data.simulator as SimulatorNodeConfig | undefined) ?? {}
+ void _d
+ setPreview({ kind: 'simulator', cfg: device }, remove)
+ },
+ [getNodes, setPreview]
+ )
+
+ // A popped-out node's ⇲ asks for this.
+ useEffect(() => {
+ const onDock = (e: Event) => {
+ const d = (e as CustomEvent<{ nodeId?: string; runNodeId?: string }>).detail
+ if (d?.runNodeId === nodeId && d.nodeId) dockBack(d.nodeId)
+ }
+ window.addEventListener('nodeterm:dock-preview', onDock)
+ return () => window.removeEventListener('nodeterm:dock-preview', onDock)
+ }, [nodeId, dockBack])
+
+ /** The page this run shows: a browser configuration's own URL, else the newest local URL in the
+ * run's output. Null when there is none yet. */
+ const browserUrlNow = useCallback(async (): Promise<RunBrowserConfig> => {
+ if (entry?.browser) {
+ const r = await api.runConfig.start(nodeId, cfgRef.current).catch(() => null)
+ return r?.ok && r.kind === 'browser' && isPreviewUrl(r.url) ? { url: r.url } : {}
+ }
+ const text = await api.pty.capture(nodeId, true).catch(() => '')
+ const url = localUrlFromOutput(text)
+ return url ? { url, auto: true } : {}
+ }, [api, nodeId, entry?.browser])
+
+ // The run's own device (the configuration's, else the pick) — a Flutter web run when it is a
+ // browser device, which shows here only when `embedBrowser` is on.
+ const runDevice = entry?.usesDevice ? (entry.pinnedDevice ?? config.deviceId) : undefined
+ const flutterWebRun = isWebDeviceId(runDevice)
+
+ /** The button: hides an open panel, docks a popped-out one back, and otherwise shows the one this
+ * run calls for — a node runs one thing, so it is never a choice. */
+ const onPreviewButton = () => {
+ if (panelOpen) return setPreview(undefined)
+ if (poppedOut) return dockBack(poppedOut.id)
+ void openPreview(previewKind)
+ }
+
+ const openPreview = async (kind: PreviewKind) => {
+ if (kind === 'browser') {
+ if (flutterWebRun && running && !embedsFlutterWeb(config)) {
+ say('info', 'This Flutter web run is in its own Chrome window — turn on ⋯ → “Show web inside this node” and run again to show it here.')
+ }
+ setPreview({ kind: 'browser', cfg: await browserUrlNow() })
+ return
+ }
+ const id = showDevice ? config.deviceId : undefined
+ let next: InlineSimulatorConfig = {}
+ if (id && SIMULATOR_UDID.test(id)) next = { udid: id.toUpperCase(), name: device?.name ?? config.deviceName }
+ else if (id && /^emulator-\d+$/.test(id)) {
+ const avd = (await api.simulator.devices().catch(() => ({ devices: [] }))).devices.find((d) => d.serial === id)
+ if (avd) next = { udid: avd.id, name: avd.name }
+ }
+ setPreview({ kind: 'simulator', cfg: next })
+ }
+
+ // An open panel follows the run: pick a browser device and the simulator becomes the browser, and
+ // the other way round. The popped-out kind is left alone (the person moved it out on purpose).
+ const openPreviewRef = useRef(openPreview)
+ openPreviewRef.current = openPreview
+ const openKind: PreviewKind | null = simulator ? 'simulator' : browserPanel ? 'browser' : null
+ useEffect(() => {
+ if (openKind && openKind !== previewKind) void openPreviewRef.current(previewKind)
+ }, [openKind, previewKind])
+
+ /** ⇱: the panel becomes its own node beside this one, which can dock back. */
+ const popOut = () => {
+ if (!simulator && !browserPanel) return
+ setPreview(undefined, (ns) => {
+ const src = ns.find((n) => n.id === nodeId)
+ if (!src) return ns
+ let node: CanvasNode
+ if (simulator) node = createSimulatorNode(ns.length, { ...simulator, dockTo: nodeId })
+ else {
+ node = createBrowserNode(ns.length, browserPanel?.url ?? '')
+ node.data = { ...node.data, dockTo: nodeId }
+ }
+ const w = src.measured?.width ?? (src.width as number | undefined) ?? 640
+ node.position = { x: src.position.x + w + 40, y: src.position.y }
+ return [...ns, src.parentId ? { ...node, parentId: src.parentId, extent: 'parent' as const } : node]
+ })
+ }
+
+ const onSimConfig = useCallback(
+ (next: SimulatorNodeConfig) => {
+ updateNodeData(nodeId, (n) => (n.data.runSimulator ? { runSimulator: { ...next, dockTo: undefined } } : {}))
+ },
+ [nodeId, updateNodeData]
+ )
+
+ const onBrowserUrl = useCallback(
+ (url: string) => {
+ if (!isPreviewUrl(url)) return
+ updateNodeData(nodeId, (n) => {
+ const was = n.data.runBrowser as RunBrowserConfig | undefined
+ if (!was || was.url === url) return {}
+ return { runBrowser: { url, ...(was.auto ? { auto: true } : {}) } }
+ })
+ },
+ [nodeId, updateNodeData]
+ )
+
+ // Waiting for a page: while the browser panel has none and the run is up, read its output until
+ // it prints a local URL. A new run starts the wait over when the last URL was picked out of the
+ // output (a dev server may come back on another port); a URL the person typed is kept.
+ const lastRunning = useRef(running)
+ useEffect(() => {
+ const was = lastRunning.current
+ lastRunning.current = running
+ if (!was && running && browserPanel?.auto) updateNodeData(nodeId, { runBrowser: {} })
+ }, [running, browserPanel?.auto, nodeId, updateNodeData])
+ const waitingForUrl = !!browserPanel && !browserPanel.url && running && !entry?.browser
+ useEffect(() => {
+ if (!waitingForUrl) return
+ let live = true
+ const look = async () => {
+ const text = await api.pty.capture(nodeId, true).catch(() => '')
+ const url = live ? localUrlFromOutput(text) : null
+ if (url) updateNodeData(nodeId, (n) => (n.data.runBrowser && !(n.data.runBrowser as RunBrowserConfig).url ? { runBrowser: { url, auto: true } } : {}))
+ }
+ void look()
+ const t = setInterval(() => void look(), 1500)
+ return () => {
+ live = false
+ clearInterval(t)
+ }
+ }, [waitingForUrl, api, nodeId, updateNodeData])
const toggleTerminal = useCallback(() => {
const next = !showTerminal
@@ -575,7 +820,7 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
(entry && !entry.supported ? entry.reason : null)
return (
- <div ref={barRef} className={`run-bar nodrag nowheel${showTerminal ? '' : ' run-bar--compact'}`}>
+ <div ref={barRef} className={`run-bar nodrag nowheel${showTerminal ? '' : ' run-bar--compact'}${panelOpen ? ' run-bar--sim' : ''}`}>
<div className="run-bar__row">
<select
className="run-bar__select run-bar__select--folder"
@@ -737,6 +982,25 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
<span className="run-bar__spacer" />
<span className={`run-bar__status run-bar__status--${statusKind}`}>{statusText}</span>
+ {simulatorAvailable(session.source === 'relay') && (
+ <>
+ {browserPanel && (
+ <button type="button" className="run-bar__icon" title="Pop the browser out into its own node" aria-label="Pop out" onClick={popOut}>
+ ⇱
+ </button>
+ )}
+ <button
+ type="button"
+ className={`run-bar__icon${panelOpen || poppedOut ? ' run-bar__icon--on' : ''}`}
+ title={previewButtonTitle(shownKind, panelOpen, !!poppedOut)}
+ aria-label={panelOpen ? `Hide the ${shownKind}` : `Show the ${shownKind}`}
+ aria-pressed={panelOpen}
+ onClick={onPreviewButton}
+ >
+ {shownKind === 'browser' ? '🌐' : '📱'}
+ </button>
+ </>
+ )}
<button
type="button"
className={`run-bar__icon${showTerminal ? ' run-bar__icon--on' : ''}`}
@@ -763,12 +1027,70 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
e.stopPropagation()
}}
/>
+ {flutterWebRun && (
+ <label
+ className="run-bar__check"
+ title="On: Flutter’s web server serves the app to the browser inside this node. Off: Flutter opens its own Chrome window."
+ >
+ <input
+ type="checkbox"
+ checked={embedsFlutterWeb(config)}
+ onChange={(e) => patch({ embedBrowser: e.target.checked ? true : undefined }, { changesRun: true })}
+ />
+ Show web inside this node
+ </label>
+ )}
</div>
)}
{(note || blocker) && (
<div className={`run-bar__note run-bar__note--${note?.kind ?? 'error'}`}>{note?.text ?? blocker}</div>
)}
+
+ {browserPanel && (
+ <div ref={panelRef} className="run-sim-host">
+ <div className="run-web">
+ <BrowserSurface
+ nodeId={`${nodeId}.web`}
+ url={browserPanel.url ?? ''}
+ onUrlChange={onBrowserUrl}
+ onTitleChange={ignoreTitle}
+ blank={
+ <div className="run-web__waiting">
+ {running ? 'Waiting for the run to print its local address… or type one above.' : 'Run it to show its page here — or type an address above.'}
+ </div>
+ }
+ />
+ </div>
+ </div>
+ )}
+ {simulator && (
+ <div ref={panelRef} className="run-sim-host">
+ <SimulatorView
+ streamId={`${nodeId}.sim`}
+ config={simulator}
+ onConfig={onSimConfig}
+ label={simulator.name ?? 'Simulator'}
+ className="run-sim"
+ barExtras={
+ <button className="run-bar__icon" title="Pop out into its own node" aria-label="Pop out" onClick={popOut}>
+ ⇱
+ </button>
+ }
+ />
+ </div>
+ )}
</div>
)
}
+
+/** The browser panel keeps no title (the run node has its own); stable, so the page's listeners
+ * are not re-attached on every render. */
+function ignoreTitle(): void {}
+
+function previewButtonTitle(kind: PreviewKind, open: boolean, poppedOut: boolean): string {
+ const what = kind === 'browser' ? 'browser' : 'simulator'
+ if (open) return `Hide the ${what}`
+ if (poppedOut) return `Dock the ${what} back into this node`
+ return 'Show a simulator or a browser here'
+}
diff --git a/src/renderer/nodes/SimulatorNode.tsx b/src/renderer/nodes/SimulatorNode.tsx
new file mode 100644
index 000000000..1a6bda3f2
--- /dev/null
+++ b/src/renderer/nodes/SimulatorNode.tsx
@@ -0,0 +1,1029 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { NodeResizer, useReactFlow, useStore, type NodeProps } from '@xyflow/react'
+import {
+ afterTouch,
+ INPUT_HELD_HINT,
+ TOUCH_ANSWER_MS,
+ ORIENTATION_DEGREES,
+ ORIENTATION_PURPLE,
+ displayLabel,
+ displayToFramebuffer,
+ draggedSide,
+ fitNodeToScreen,
+ hidUsageForCode,
+ picturePreRotated,
+ touchEdge,
+ rotateOrientation,
+ simulatorPlatformOf,
+ pointerToScreenRatio,
+ type SimulatorDevice,
+ type SimulatorDisplayInfo,
+ type SimulatorPlatform,
+ type SimulatorAction,
+ type SimulatorCaptureTarget,
+ type SimulatorDeviceState,
+ type SimulatorInput,
+ type SimulatorNodeConfig,
+ type SimulatorOrientation,
+ type SimulatorStatusEvent,
+ type TouchEdge
+} from '@shared/simulator'
+import { useSession } from '../session/session'
+import { SIMULATOR_RELAY_HINT } from '../lib/addMenuSpec'
+import { ContextMenu } from '../components/ContextMenu'
+import { buildAndroidMenu, buildSimulatorMenu, type SimulatorMenuHandlers } from './simulatorMenu'
+import { NODE_MIN_SIZES } from '../lib/nodeSizing'
+import type { CanvasNode } from '../state/workspace'
+
+/**
+ * The Simulator node: a live iOS simulator screen on the canvas (see @shared/simulator and
+ * core/simulator). The mouse is the finger — click = tap, drag = swipe, scroll wheel = a swipe —
+ * the keyboard types into the device while the screen has focus, and Home / Lock are buttons.
+ *
+ * Frames arrive as JPEGs (only when the screen changed) and are drawn `object-fit: contain`, so the
+ * phone keeps its proportions in any node size; `pointerToScreenRatio` maps a click through the
+ * letterbox. The helper streams only while this node is mounted.
+ */
+
+type Phase = 'idle' | 'starting' | 'live' | 'error'
+
+const WHEEL_END_MS = 140
+/** A wheel notch moves the synthetic finger by this fraction of the screen per 100 px of delta. */
+const WHEEL_SCALE = 0.25
+
+/** A Simulator node: the view, in its own box with a title, a close button and resize handles. */
+export function SimulatorNode({ id, data, selected }: NodeProps<CanvasNode>) {
+ const { updateNodeData, deleteElements, setNodes } = useReactFlow()
+ const config = useMemo(() => (data.simulator as SimulatorNodeConfig | undefined) ?? {}, [data.simulator])
+ const dockTo = config.dockTo
+ const canDock = useStore((st) => !!dockTo && st.nodeLookup.get(dockTo)?.data?.runConfig !== undefined)
+ const host = useMemo<SimulatorHost>(
+ () => ({
+ selected: !!selected,
+ color: data.color as string,
+ resize: (width, height) =>
+ setNodes((ns) =>
+ ns.map((n) => (n.id !== id || (n.width === width && n.height === height) ? n : { ...n, width, height, style: { ...n.style, width, height } }))
+ )
+ }),
+ [id, selected, data.color, setNodes]
+ )
+ const onConfig = useCallback(
+ (next: SimulatorNodeConfig, pickedName?: string) =>
+ updateNodeData(id, (n) => ({
+ simulator: { ...next, ...(dockTo ? { dockTo } : {}) },
+ ...(pickedName && n.data.titleAuto !== false ? { title: pickedName } : {})
+ })),
+ [id, dockTo, updateNodeData]
+ )
+ return (
+ <SimulatorView
+ streamId={id}
+ config={config}
+ onConfig={onConfig}
+ label={(data.title as string) || config.name || 'Simulator'}
+ className={`sim-node${selected ? ' selected' : ''}`}
+ host={host}
+ header={
+ <div className="sim-node__header" style={{ background: `${data.color}22` }}>
+ <span className="sim-node__title" title={data.title as string}>
+ {data.title as string}
+ </span>
+ {canDock && dockTo && (
+ <button
+ className="run-bar__icon nodrag"
+ title="Dock back into its run node"
+ aria-label="Dock into run node"
+ onClick={() => window.dispatchEvent(new CustomEvent('nodeterm:dock-preview', { detail: { nodeId: id, runNodeId: dockTo } }))}
+ >
+ ⇲
+ </button>
+ )}
+ <button className="term-node__close nodrag" title="Close" onClick={() => deleteElements({ nodes: [{ id }] })}>
+ ×
+ </button>
+ </div>
+ }
+ />
+ )
+}
+
+/** What a standalone node gives the view: it can size the node to the screen, and draws handles. */
+export interface SimulatorHost {
+ selected: boolean
+ color: string
+ resize: (width: number, height: number) => void
+}
+
+export interface SimulatorViewProps {
+ /** Keys the frame stream (`simulator:frame:<id>`): the node id, or `<runNodeId>.sim` inline. */
+ streamId: string
+ config: SimulatorNodeConfig
+ /** A device pick (with its name) or a rotation, to persist. */
+ onConfig: (next: SimulatorNodeConfig, pickedName?: string) => void
+ /** Names captures. */
+ label: string
+ className: string
+ style?: React.CSSProperties
+ header?: React.ReactNode
+ /** Standalone node only: fit-to-screen, Actual Size and resize handles. */
+ host?: SimulatorHost
+ /** Buttons appended to the toolbar (inline: pop out). */
+ barExtras?: React.ReactNode
+}
+
+/**
+ * The simulator screen with its toolbar, ⋯ menu and input — everything but the box around it, so a
+ * Simulator node and a run node's inline panel show the same thing.
+ */
+export function SimulatorView(props: SimulatorViewProps) {
+ // A relay tab's project belongs to another machine; its simulator nodes would otherwise stream
+ // THIS machine's devices into it. Refused with the reason (the add rows are disabled there too).
+ const { source } = useSession()
+ if (source === 'relay') {
+ return (
+ <div className={props.className} style={props.style}>
+ {props.header}
+ <div className="sim-node__placeholder">{SIMULATOR_RELAY_HINT}.</div>
+ </div>
+ )
+ }
+ return <SimulatorViewLive {...props} />
+}
+
+function SimulatorViewLive({ streamId: id, config, onConfig, label, className, style, header, host, barExtras }: SimulatorViewProps) {
+ const { api } = useSession()
+ const configRef = useRef(config)
+ configRef.current = config
+ const udid = config.udid
+ const orientation: SimulatorOrientation = config.orientation ?? 'portrait'
+ const plat: SimulatorPlatform = simulatorPlatformOf(udid) ?? 'ios'
+ const platRef = useRef(plat)
+ platRef.current = plat
+ // Read by the draw loop and the input path, which live in long-lived closures.
+ const orientationRef = useRef(orientation)
+ orientationRef.current = orientation
+ /** The newest decoded frame, kept so a rotation can redraw it even when the device sends no new
+ * frame (an app that does not rotate leaves the framebuffer unchanged). */
+ const lastBitmap = useRef<ImageBitmap | null>(null)
+
+ const [devices, setDevices] = useState<SimulatorDevice[] | null>(null)
+ /** Why a platform's list is empty when its tools could not run (no Xcode selected, no Android SDK). */
+ const [listError, setListError] = useState<string | undefined>(undefined)
+ const [phase, setPhase] = useState<Phase>('idle')
+ const [message, setMessage] = useState<string | null>(null)
+ const [displays, setDisplays] = useState<SimulatorDisplayInfo[]>([])
+ const [activeDisplay, setActiveDisplay] = useState(0)
+ const [pinned, setPinned] = useState(false)
+ const [frameSize, setFrameSize] = useState<{ w: number; h: number } | null>(null)
+ const [booting, setBooting] = useState(false)
+ const [menuAt, setMenuAt] = useState<{ x: number; y: number } | null>(null)
+ const [devState, setDevState] = useState<SimulatorDeviceState>({})
+ const [recording, setRecording] = useState(false)
+ const [toast, setToast] = useState<{ text: string; error?: boolean } | null>(null)
+ const [prompt, setPrompt] = useState<PromptSpec | null>(null)
+ const [confirm, setConfirm] = useState<ConfirmSpec | null>(null)
+ const [dropping, setDropping] = useState(false)
+ /** "DeviceHub may be holding the input": shown after several touches in a row changed nothing. */
+ const [inputHint, setInputHint] = useState(false)
+ /** Frames received so far; a touch is answered when this moves after it lifts. */
+ const framesSeen = useRef(0)
+ const unanswered = useRef(0)
+ const touchTimers = useRef(new Set<ReturnType<typeof setTimeout>>())
+ const canvasRef = useRef<HTMLCanvasElement>(null)
+ const screenRef = useRef<HTMLDivElement>(null)
+ const rootRef = useRef<HTMLDivElement>(null)
+
+ const sim = devices ?? []
+ const device = sim.find((d) => d.id === udid)
+ const booted = device?.state === 'booted'
+
+ const loadDevices = useCallback(
+ (refresh: boolean) => {
+ void api.simulator.devices(refresh).then((r) => {
+ setDevices(r.devices)
+ setListError([r.iosError, r.androidError].filter(Boolean).join(' ') || undefined)
+ })
+ },
+ [api]
+ )
+ useEffect(() => loadDevices(false), [loadDevices])
+
+ /** Draw the newest frame, turned to match how the device is held: the framebuffer is always
+ * portrait and iOS draws rotated content into it, so the picture is turned, as on a real panel. */
+ const paint = useCallback(() => {
+ const canvas = canvasRef.current
+ const b = lastBitmap.current
+ if (!canvas || !b) return
+ // An Android emulator sends its frames already turned; only iOS frames are always portrait.
+ const deg = picturePreRotated(platRef.current) ? 0 : ORIENTATION_DEGREES[orientationRef.current]
+ const w = deg % 180 ? b.height : b.width
+ const h = deg % 180 ? b.width : b.height
+ if (canvas.width !== w || canvas.height !== h) {
+ canvas.width = w
+ canvas.height = h
+ }
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return
+ ctx.setTransform(1, 0, 0, 1, 0, 0)
+ if (deg === 90) ctx.setTransform(0, 1, -1, 0, w, 0)
+ else if (deg === 180) ctx.setTransform(-1, 0, 0, -1, w, h)
+ else if (deg === 270) ctx.setTransform(0, -1, 1, 0, 0, h)
+ ctx.drawImage(b, 0, 0)
+ ctx.setTransform(1, 0, 0, 1, 0, 0)
+ setFrameSize((s) => (s && s.w === w && s.h === h ? s : { w, h }))
+ }, [])
+ useEffect(() => paint(), [orientation, paint])
+
+ // ── Stream ───────────────────────────────────────────────────────────────────────────────────
+ useEffect(() => {
+ if (!udid || !booted) {
+ setPhase('idle')
+ return
+ }
+ let live = true
+ setPhase('starting')
+ setMessage(null)
+ // Frames are decoded straight to an ImageBitmap and drawn on a canvas. Not an <img> with a
+ // blob: URL: the renderer's CSP allows img-src 'self' data: nt-media: only, so every frame was
+ // a broken image — and a canvas needs no URL at all.
+ let pending: { bitmap: ImageBitmap; w: number; h: number } | null = null
+ let raf = 0
+ let decoding = 0
+ const offFrame = api.simulator.onFrame(id, (f) => {
+ if (!live) return
+ framesSeen.current++
+ const seq = ++decoding
+ void createImageBitmap(new Blob([f.jpeg as BlobPart], { type: f.mime ?? 'image/jpeg' })).then(
+ (bitmap) => {
+ // A newer frame decoded first (or the node went away): this one is stale.
+ if (!live || seq < decoding) {
+ bitmap.close()
+ return
+ }
+ pending?.bitmap.close()
+ pending = { bitmap, w: f.width, h: f.height }
+ // Draw at most once per animation frame: a burst of frames shows the newest.
+ if (!raf) {
+ raf = requestAnimationFrame(() => {
+ raf = 0
+ if (!pending) return
+ const { bitmap } = pending
+ pending = null
+ lastBitmap.current?.close()
+ lastBitmap.current = bitmap
+ paint()
+ setPhase('live')
+ })
+ }
+ },
+ () => undefined
+ )
+ })
+ const offStatus = api.simulator.onStatus(id, (e: SimulatorStatusEvent) => {
+ if (!live) return
+ if (e.kind === 'ready') {
+ // Tell the device how the node holds it: after a reboot it is portrait whatever was saved.
+ void api.simulator.input(id, { t: 'orientation', value: ORIENTATION_PURPLE[orientationRef.current] })
+ } else if (e.kind === 'displays') {
+ setDisplays(e.displays)
+ setActiveDisplay(e.active)
+ setPinned(e.pinned)
+ } else if (e.kind === 'error') {
+ setMessage(e.message)
+ if (e.code !== 'hid-send' && e.code !== 'button') setPhase('error')
+ } else if (e.kind === 'exited') {
+ setPhase('error')
+ // The helper reports why before it exits; keep that sentence when there is one.
+ setMessage((prev) => prev ?? `The simulator view stopped (exit ${e.code ?? e.signal}).`)
+ }
+ })
+ void api.simulator.start(id, udid).then((r) => {
+ if (!live) return
+ if (!r.ok) {
+ setPhase('error')
+ setMessage(r.error)
+ }
+ })
+ return () => {
+ live = false
+ offFrame()
+ offStatus()
+ if (raf) cancelAnimationFrame(raf)
+ pending?.bitmap.close()
+ lastBitmap.current?.close()
+ lastBitmap.current = null
+ void api.simulator.stop(id)
+ }
+ }, [api, id, udid, booted, paint])
+
+ // ── Fit the node to the screen ───────────────────────────────────────────────────────────────
+ //
+ // No black bars: whenever the screen's shape changes (first frame, a rotation, a foldable moving
+ // to its other screen) the node is resized so the screen area has exactly that shape. The longer
+ // side of the screen keeps its length, so a rotation turns a tall phone into a wide one of the
+ // same size rather than shrinking it into the old box. The header and toolbar are measured, not
+ // assumed (the toolbar wraps on a narrow node), so a second pass a frame later settles any wrap.
+ // Layout pixels (offsetWidth/Height), which the canvas zoom does not touch — the same units as
+ // the node's own size.
+ const fitToScreen = useCallback(
+ (by: 'long' | 'width' | 'height' = 'long') => {
+ const root = rootRef.current
+ const screen = screenRef.current
+ if (!host || !root || !screen || !frameSize || screen.offsetWidth <= 0 || screen.offsetHeight <= 0) return
+ const { width, height } = fitNodeToScreen({
+ screenW: screen.offsetWidth,
+ screenH: screen.offsetHeight,
+ chromeW: root.offsetWidth - screen.offsetWidth,
+ chromeH: root.offsetHeight - screen.offsetHeight,
+ aspect: frameSize.w / frameSize.h,
+ by,
+ minW: NODE_MIN_SIZES.simulator.width,
+ minH: NODE_MIN_SIZES.simulator.height
+ })
+ host.resize(width, height)
+ },
+ [frameSize, host]
+ )
+ /** The screen area's size when a hand resize began, to tell which side was dragged. */
+ const resizeFrom = useRef<{ w: number; h: number } | null>(null)
+
+ useEffect(() => {
+ if (!frameSize) return
+ fitToScreen()
+ const raf = requestAnimationFrame(() => fitToScreen())
+ return () => cancelAnimationFrame(raf)
+ // Only when the screen's SHAPE changes — not on every frame.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [frameSize?.w, frameSize?.h])
+
+ // ── Input ────────────────────────────────────────────────────────────────────────────────────
+ const touchEdgeRef = useRef<TouchEdge>(0)
+ // Touches are measured on the (turned) picture and sent in portrait framebuffer coordinates.
+ const send = useCallback(
+ (cmd: SimulatorInput) => {
+ let out: SimulatorInput = cmd
+ if (cmd.t === 'down' || cmd.t === 'move' || cmd.t === 'up') {
+ const p = displayToFramebuffer(cmd.x, cmd.y, orientationRef.current)
+ // The panel edge the finger went down on rides the whole contact: it is how iOS tells the
+ // home swipe (up from the bottom) from a drag in the app. Android has no such flag.
+ if (cmd.t === 'down') touchEdgeRef.current = platRef.current === 'ios' ? touchEdge(p.x, p.y) : 0
+ const edge = touchEdgeRef.current
+ out = { ...cmd, ...p, ...(edge ? { edge } : {}) }
+ if (cmd.t === 'up') touchEdgeRef.current = 0
+ }
+ void api.simulator.input(id, out)
+ },
+ [api, id]
+ )
+
+ // A touch that lifted with no frame after it changed nothing on the screen (see afterTouch).
+ // Counted from the finger going DOWN, so a drag that moved the screen while held is answered.
+ const touchStartFrames = useRef(0)
+ const watchTouch = useCallback(() => {
+ // The hint is about DeviceHub holding an iOS device's input; Android has no such rule.
+ if (platRef.current !== 'ios') return
+ const before = touchStartFrames.current
+ const t = setTimeout(() => {
+ touchTimers.current.delete(t)
+ const r = afterTouch(unanswered.current, framesSeen.current !== before)
+ unanswered.current = r.count
+ setInputHint(r.hint)
+ }, TOUCH_ANSWER_MS)
+ touchTimers.current.add(t)
+ }, [])
+ useEffect(() => {
+ const timers = touchTimers.current
+ return () => {
+ for (const t of timers) clearTimeout(t)
+ timers.clear()
+ }
+ }, [])
+ // A different device starts with a clean slate.
+ useEffect(() => {
+ unanswered.current = 0
+ setInputHint(false)
+ }, [udid])
+
+ const rotate = useCallback(
+ (dir: 'left' | 'right') => {
+ const next = rotateOrientation(orientationRef.current, dir)
+ orientationRef.current = next
+ onConfig({ ...configRef.current, orientation: next })
+ void api.simulator.input(id, { t: 'orientation', value: ORIENTATION_PURPLE[next] })
+ },
+ [api, id, onConfig]
+ )
+
+ const ratioAt = useCallback(
+ (clientX: number, clientY: number) => {
+ const box = screenRef.current?.getBoundingClientRect()
+ if (!box || !frameSize) return null
+ // Client-space on both sides, so the canvas zoom cancels out.
+ return pointerToScreenRatio(clientX - box.left, clientY - box.top, box.width, box.height, frameSize.w, frameSize.h)
+ },
+ [frameSize]
+ )
+
+ const pressed = useRef<{ x: number; y: number } | null>(null)
+ const moveRaf = useRef(0)
+ const onPointerDown = (e: React.PointerEvent) => {
+ if (e.button !== 0 || phase !== 'live') return
+ const p = ratioAt(e.clientX, e.clientY)
+ screenRef.current?.focus()
+ if (!p) return
+ e.currentTarget.setPointerCapture(e.pointerId)
+ pressed.current = p
+ touchStartFrames.current = framesSeen.current
+ send({ t: 'down', ...p })
+ e.preventDefault()
+ }
+ const onPointerMove = (e: React.PointerEvent) => {
+ if (!pressed.current) return
+ const { clientX, clientY } = e
+ if (moveRaf.current) return
+ moveRaf.current = requestAnimationFrame(() => {
+ moveRaf.current = 0
+ const box = screenRef.current?.getBoundingClientRect()
+ if (!box || !frameSize || !pressed.current) return
+ // While pressed, a drag past the screen's edge pins to the edge instead of dropping out.
+ const p = ratioAt(clientX, clientY) ?? clampedRatio(clientX, clientY, box, frameSize)
+ pressed.current = p
+ send({ t: 'move', ...p })
+ })
+ }
+ const onPointerUp = (e: React.PointerEvent) => {
+ if (!pressed.current) return
+ const box = screenRef.current?.getBoundingClientRect()
+ const p = ratioAt(e.clientX, e.clientY) ?? (box && frameSize ? clampedRatio(e.clientX, e.clientY, box, frameSize) : pressed.current)
+ pressed.current = null
+ send({ t: 'up', ...p })
+ watchTouch()
+ }
+
+ // The scroll wheel becomes a swipe: a finger that goes down where the pointer is, follows the
+ // wheel, and lifts once the wheel stops.
+ const wheel = useRef<{ x: number; y: number; timer: ReturnType<typeof setTimeout> } | null>(null)
+ const onWheel = (e: React.WheelEvent) => {
+ if (phase !== 'live') return
+ const box = screenRef.current?.getBoundingClientRect()
+ if (!box || !frameSize) return
+ if (!wheel.current) {
+ const p = ratioAt(e.clientX, e.clientY)
+ if (!p) return
+ touchStartFrames.current = framesSeen.current
+ send({ t: 'down', ...p })
+ wheel.current = { ...p, timer: setTimeout(() => undefined, 0) }
+ }
+ const w = wheel.current
+ clearTimeout(w.timer)
+ w.x = Math.min(1, Math.max(0, w.x - (e.deltaX / 100) * WHEEL_SCALE))
+ w.y = Math.min(1, Math.max(0, w.y - (e.deltaY / 100) * WHEEL_SCALE))
+ send({ t: 'move', x: w.x, y: w.y })
+ w.timer = setTimeout(() => {
+ send({ t: 'up', x: w.x, y: w.y })
+ wheel.current = null
+ watchTouch()
+ }, WHEEL_END_MS)
+ }
+
+ // Keys go to the device as physical keys (it applies its own layout and Shift). ⌘-chords stay
+ // with nodeterm so the app's own shortcuts keep working while the screen has focus.
+ const onKey = (down: boolean) => (e: React.KeyboardEvent) => {
+ if (e.target !== e.currentTarget) return
+ // ⌘V on Android: let the app's own paste happen — the screen's paste event carries the text.
+ if (phase === 'live' && e.metaKey && e.code === 'KeyV' && plat === 'android') return
+ // ⌘V pastes the Mac clipboard: sync it to the device, then press ⌘V there.
+ if (phase === 'live' && e.metaKey && e.code === 'KeyV') {
+ e.preventDefault()
+ e.stopPropagation()
+ if (down && !e.repeat) {
+ void act({ a: 'pasteboard', dir: 'to-device' }).then(() => {
+ send({ t: 'key', usage: 0xe3, down: true })
+ send({ t: 'key', usage: 0x19, down: true })
+ send({ t: 'key', usage: 0x19, down: false })
+ send({ t: 'key', usage: 0xe3, down: false })
+ })
+ }
+ return
+ }
+ // ⌘← / ⌘→ rotate, as they did in Simulator.app.
+ if (phase === 'live' && e.metaKey && (e.code === 'ArrowLeft' || e.code === 'ArrowRight')) {
+ e.preventDefault()
+ e.stopPropagation()
+ if (down && !e.repeat) rotate(e.code === 'ArrowLeft' ? 'left' : 'right')
+ return
+ }
+ if (phase !== 'live' || (e.metaKey && e.code !== 'MetaLeft' && e.code !== 'MetaRight')) return
+ const usage = hidUsageForCode(e.code)
+ if (usage === undefined) return
+ e.preventDefault()
+ e.stopPropagation()
+ if (down && e.repeat) return
+ send({ t: 'key', usage, down })
+ }
+
+ // Android ⌘V: put the host's text on the device clipboard, then press Ctrl+V there (Android's own
+ // paste shortcut in a text field).
+ const onPaste = (e: React.ClipboardEvent) => {
+ if (plat !== 'android' || phase !== 'live') return
+ const text = e.clipboardData.getData('text/plain')
+ e.preventDefault()
+ e.stopPropagation()
+ if (!text) return
+ void act({ a: 'clipboard-set', text }).then(() => {
+ send({ t: 'key', usage: 0xe0, down: true })
+ send({ t: 'key', usage: 0x19, down: true })
+ send({ t: 'key', usage: 0x19, down: false })
+ send({ t: 'key', usage: 0xe0, down: false })
+ })
+ }
+
+ // ── Header actions ───────────────────────────────────────────────────────────────────────────
+ const pick = (value: string) => {
+ const d = sim.find((x) => x.id === value)
+ onConfig({ udid: value, name: d?.name }, d?.name)
+ }
+ const boot = async () => {
+ if (!udid) return
+ setBooting(true)
+ setMessage(null)
+ const r = await api.simulator.boot(udid)
+ setBooting(false)
+ if (!r.ok) setMessage(r.error)
+ loadDevices(true)
+ }
+ const shutdown = async () => {
+ if (!udid) return
+ await api.simulator.shutdown(udid)
+ loadDevices(true)
+ }
+
+ // ── ⋯ menu ───────────────────────────────────────────────────────────────────────────────────
+ useEffect(() => {
+ if (!toast) return
+ const t = setTimeout(() => setToast(null), toast.error ? 6000 : 3500)
+ return () => clearTimeout(t)
+ }, [toast])
+
+ const say = (r: { ok: true; message?: string } | { ok: false; error: string }) => {
+ if (r.ok) {
+ if (r.message) setToast({ text: r.message })
+ } else setToast({ text: r.error, error: true })
+ }
+
+ const act = useCallback(
+ async (a: SimulatorAction) => {
+ if (!udid) return
+ const r = await api.simulator.action(udid, a)
+ say(r)
+ if (r.ok && r.text !== undefined) api.clipboard.writeText(r.text)
+ if (r.ok && (a.a === 'appearance' || a.a === 'increase-contrast' || a.a === 'content-size')) {
+ void api.simulator.state(udid).then(setDevState)
+ }
+ if (r.ok && (a.a === 'restart' || a.a === 'erase')) loadDevices(true)
+ },
+ [api, udid, loadDevices]
+ )
+
+ const activeScreenID = displays[activeDisplay]?.screenID ?? 0
+ const deviceName = label
+
+ const screenshot = async (target: SimulatorCaptureTarget) => {
+ if (!udid) return
+ const r = await api.simulator.screenshot(udid, activeScreenID, target, deviceName)
+ say(r)
+ if (r.ok && target === 'canvas' && r.path) window.dispatchEvent(new CustomEvent('nodeterm:open-file', { detail: { path: r.path } }))
+ }
+
+ const toggleRecording = async () => {
+ if (!udid) return
+ if (recording) {
+ const r = await api.simulator.stopRecording(udid)
+ setRecording(false)
+ say(r)
+ if (r.ok && r.path) window.dispatchEvent(new CustomEvent('nodeterm:open-file', { detail: { path: r.path } }))
+ } else {
+ const r = await api.simulator.startRecording(udid, activeScreenID, deviceName)
+ if (r.ok) setRecording(true)
+ else say(r)
+ }
+ }
+ useEffect(() => {
+ if (udid) void api.simulator.isRecording(udid).then(setRecording)
+ }, [api, udid])
+
+ /** One device point per canvas point: the framebuffer's pixels over the device's scale (2× iPad,
+ * 3× iPhone — the two scales current simulators use). */
+ const actualSize = () => {
+ const disp = displays[activeDisplay]
+ const root = rootRef.current
+ const screen = screenRef.current
+ if (!host || !disp || !root || !screen) return
+ const scale = disp.scale ?? (/ipad/i.test(device?.name ?? config.name ?? '') ? 2 : 3)
+ const turned = ORIENTATION_DEGREES[orientationRef.current] % 180 !== 0
+ const w = Math.round((turned ? disp.height : disp.width) / scale + (root.offsetWidth - screen.offsetWidth))
+ const h = Math.round((turned ? disp.width : disp.height) / scale + (root.offsetHeight - screen.offsetHeight))
+ host.resize(w, h)
+ }
+
+ const pickFile = async (kind: 'install' | 'media') => {
+ const p = await api.dialog.selectFile()
+ if (!p) return
+ if (kind === 'install') void act({ a: 'install', path: p })
+ else void act({ a: 'add-media', paths: [p] })
+ }
+
+ const openMenu = (e: React.MouseEvent) => {
+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
+ setMenuAt({ x: r.left, y: r.bottom + 4 })
+ if (udid) void api.simulator.state(udid).then(setDevState)
+ }
+
+ const menuHandlers: SimulatorMenuHandlers = {
+ button: (name) => send({ t: 'button', name }),
+ rotate,
+ action: (a) => void act(a),
+ screenshot: (t) => void screenshot(t),
+ toggleRecording: () => void toggleRecording(),
+ shutDown: () => void shutdown(),
+ confirmErase: () =>
+ setConfirm({
+ title: 'Reset Content and Settings?',
+ body: `Erases everything on “${deviceName}” — apps, data and settings — like a factory reset. It restarts afterwards.`,
+ confirmLabel: 'Erase',
+ onConfirm: () => void act({ a: 'erase' })
+ }),
+ promptCustomLocation: () =>
+ setPrompt({
+ title: 'Custom Location',
+ fields: [
+ { key: 'lat', label: 'Latitude', placeholder: '37.3349' },
+ { key: 'lon', label: 'Longitude', placeholder: '-122.0090' }
+ ],
+ submitLabel: 'Set Location',
+ onSubmit: (v) => void act({ a: 'location-set', lat: Number(v.lat), lon: Number(v.lon) })
+ }),
+ promptOpenUrl: () =>
+ setPrompt({
+ title: 'Open URL',
+ fields: [{ key: 'url', label: 'URL or deep link', placeholder: 'https://… or myapp://path' }],
+ submitLabel: 'Open',
+ onSubmit: (v) => void act({ a: 'open-url', url: v.url })
+ }),
+ promptPush: () =>
+ setPrompt({
+ title: 'Send Push Notification',
+ fields: [
+ { key: 'bundleId', label: 'App bundle ID', placeholder: 'com.example.app' },
+ {
+ key: 'payload',
+ label: 'Payload (JSON)',
+ multiline: true,
+ value: JSON.stringify({ aps: { alert: { title: 'Hello', body: 'From nodeterm' }, sound: 'default' } }, null, 2)
+ }
+ ],
+ submitLabel: 'Send',
+ onSubmit: (v) => void act({ a: 'push', bundleId: v.bundleId.trim(), payload: v.payload })
+ }),
+ promptPrivacy: (op) =>
+ setPrompt({
+ title: op === 'grant' ? 'Grant All Permissions' : 'Revoke All Permissions',
+ fields: [{ key: 'bundleId', label: 'App bundle ID', placeholder: 'com.example.app' }],
+ submitLabel: op === 'grant' ? 'Grant' : 'Revoke',
+ onSubmit: (v) => void act({ a: 'privacy', op, service: 'all', bundleId: v.bundleId.trim() })
+ }),
+ pickInstall: () => void pickFile('install'),
+ pickMedia: () => void pickFile('media'),
+ actualSize: host ? actualSize : undefined,
+ fitToScreen: host ? () => fitToScreen('long') : undefined
+ }
+ const menuItems =
+ plat === 'android'
+ ? buildAndroidMenu(menuHandlers, { device: devState })
+ : buildSimulatorMenu(menuHandlers, { device: devState, recording })
+
+ // Drop a built .app to install it, photos/videos to add them to the library.
+ const onDrop = (e: React.DragEvent) => {
+ e.preventDefault()
+ setDropping(false)
+ if (!udid || phase !== 'live') return
+ const paths = Array.from(e.dataTransfer.files)
+ .map((f) => window.nodeTerminal.getPathForFile(f))
+ .filter(Boolean)
+ const apps = paths.filter((p) => (plat === 'android' ? /\.apks?$/i : /\.app\/?$/).test(p))
+ const media = paths.filter((p) => /\.(png|jpe?g|gif|heic|heif|webp|mov|mp4|m4v)$/i.test(p))
+ for (const app of apps) void act({ a: 'install', path: app.replace(/\/$/, '') })
+ if (media.length) void act({ a: 'add-media', paths: media })
+ if (!apps.length && !media.length)
+ setToast({
+ text: plat === 'android' ? 'Drop an .apk to install it, or photos and videos to add them to Pictures.' : 'Drop a built .app to install it, or photos and videos to add them to Photos.',
+ error: true
+ })
+ }
+
+ const statusText =
+ booting
+ ? 'Booting…'
+ : phase === 'starting'
+ ? 'Connecting…'
+ : phase === 'live'
+ ? ''
+ : !udid
+ ? ''
+ : device && !booted
+ ? 'Shut down'
+ : ''
+
+ const twins = useMemo(() => new Set(sim.filter((d, i) => sim.findIndex((o) => o.name === d.name && o.os === d.os) !== i).map((d) => `${d.name}|${d.os}`)), [sim])
+ const deviceLabel = (d: SimulatorDevice) =>
+ `${d.name}${d.os ? ` · ${d.os}` : ''}${twins.has(`${d.name}|${d.os}`) ? ` · ${d.id.replace(/^avd:/, '').slice(0, 4)}` : ''}${d.state === 'booted' ? '' : ' (off)'}`
+ const iosDevices = sim.filter((d) => d.platform === 'ios')
+ const androidDevices = sim.filter((d) => d.platform === 'android')
+
+ return (
+ <>
+ <div ref={rootRef} className={className} style={style}>
+ {header}
+ <div className="sim-node__bar nodrag nowheel">
+ <select className="run-bar__select sim-node__device" value={udid ?? ''} onChange={(e) => pick(e.target.value)}>
+ {!udid && <option value="">{devices ? 'Pick a simulator…' : 'Loading…'}</option>}
+ {udid && !device && <option value={udid}>{config.name ?? udid}</option>}
+ {iosDevices.length > 0 && (
+ <optgroup label="iOS">
+ {iosDevices.map((d) => (
+ <option key={d.id} value={d.id}>
+ {deviceLabel(d)}
+ </option>
+ ))}
+ </optgroup>
+ )}
+ {androidDevices.length > 0 && (
+ <optgroup label="Android">
+ {androidDevices.map((d) => (
+ <option key={d.id} value={d.id}>
+ {deviceLabel(d)}
+ </option>
+ ))}
+ </optgroup>
+ )}
+ </select>
+ <button className="run-bar__icon" title="Refresh simulators" onClick={() => loadDevices(true)}>
+ ⟳
+ </button>
+ {udid && device && !booted && (
+ <button className="run-bar__btn run-bar__btn--run" disabled={booting} onClick={() => void boot()}>
+ Boot
+ </button>
+ )}
+ {displays.length > 1 && (
+ <select
+ className="run-bar__select"
+ title="Which screen to show (a foldable has two)"
+ value={pinned ? String(activeDisplay) : '-1'}
+ onChange={(e) => send({ t: 'display', index: Number(e.target.value) })}
+ >
+ <option value="-1">Auto ({displayLabel(displays[activeDisplay] ?? displays[0], displays)})</option>
+ {displays.map((d) => (
+ <option key={d.index} value={d.index}>
+ {displayLabel(d, displays)}
+ </option>
+ ))}
+ </select>
+ )}
+ <span className="run-bar__spacer" />
+ {phase === 'live' && (
+ <>
+ <button className="run-bar__icon" title="Rotate left (⌘←)" onClick={() => rotate('left')}>
+ ↺
+ </button>
+ <button className="run-bar__icon" title="Rotate right (⌘→)" onClick={() => rotate('right')}>
+ ↻
+ </button>
+ {plat === 'android' && (
+ <button className="run-bar__icon" title="Back" onClick={() => send({ t: 'button', name: 'back' })}>
+ ◁
+ </button>
+ )}
+ <button className="run-bar__icon" title="Home" onClick={() => send({ t: 'button', name: 'home' })}>
+ ⌂
+ </button>
+ {plat === 'android' && (
+ <button className="run-bar__icon" title="Recent apps" onClick={() => send({ t: 'button', name: 'recents' })}>
+ ▢
+ </button>
+ )}
+ <button className="run-bar__icon" title="Lock / side button" onClick={() => send({ t: 'button', name: 'lock' })}>
+ ⏻
+ </button>
+ <button className="run-bar__icon" title="Shut down this simulator" onClick={() => void shutdown()}>
+ ⏏
+ </button>
+ </>
+ )}
+ {recording && (
+ <button className="sim-node__rec" title="Recording — click to stop" onClick={() => void toggleRecording()}>
+ ● REC
+ </button>
+ )}
+ {udid && booted && (
+ <button className="run-bar__icon" title={plat === 'android' ? 'More' : 'More (everything DeviceHub offers)'} aria-label="More" onClick={openMenu}>
+ ⋯
+ </button>
+ )}
+ {statusText && <span className="run-bar__status">{statusText}</span>}
+ {barExtras}
+ </div>
+ <div
+ ref={screenRef}
+ className="sim-node__screen nodrag nowheel"
+ tabIndex={0}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ onWheel={onWheel}
+ onKeyDown={onKey(true)}
+ onKeyUp={onKey(false)}
+ onPaste={onPaste}
+ onDragOver={(e) => {
+ if (phase !== 'live') return
+ e.preventDefault()
+ setDropping(true)
+ }}
+ onDragLeave={() => setDropping(false)}
+ onDrop={onDrop}
+ >
+ <canvas ref={canvasRef} className="sim-node__frame" style={{ visibility: phase === 'live' ? 'visible' : 'hidden' }} />
+ {phase !== 'live' && (
+ <div className="sim-node__placeholder">
+ {!udid
+ ? `Pick a simulator above.${listError ? ` ${listError}` : ''}`
+ : device && !booted
+ ? 'This simulator is shut down — Boot it to see its screen.'
+ : phase === 'starting'
+ ? plat === 'android'
+ ? 'Connecting to the emulator…'
+ : 'Connecting to the simulator… (the first time builds a small helper with Xcode)'
+ : (message ?? '')}
+ </div>
+ )}
+ {phase === 'live' && message && <div className="sim-node__note">{message}</div>}
+ {phase === 'live' && inputHint && (
+ <div className="sim-node__hint" role="status">
+ <span>{INPUT_HELD_HINT}</span>
+ <button
+ className="sim-node__hint-close"
+ aria-label="Dismiss"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={() => {
+ unanswered.current = 0
+ setInputHint(false)
+ }}
+ >
+ ×
+ </button>
+ </div>
+ )}
+ {dropping && <div className="sim-node__drop">Drop a .app to install · photos or videos to add</div>}
+ </div>
+ {toast && <div className={`sim-node__toast${toast.error ? ' sim-node__toast--error' : ''}`}>{toast.text}</div>}
+ {prompt && <SimPrompt spec={prompt} onClose={() => setPrompt(null)} />}
+ {confirm && (
+ <div className="sim-node__overlay nodrag nowheel">
+ <div className="sim-node__dialog">
+ <div className="sim-node__dialog-title">{confirm.title}</div>
+ <div className="sim-node__dialog-body">{confirm.body}</div>
+ <div className="sim-node__dialog-actions">
+ <button className="run-bar__btn" onClick={() => setConfirm(null)}>
+ Cancel
+ </button>
+ <button
+ className="run-bar__btn run-bar__btn--stop"
+ onClick={() => {
+ confirm.onConfirm()
+ setConfirm(null)
+ }}
+ >
+ {confirm.confirmLabel}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ {menuAt && <ContextMenu x={menuAt.x} y={menuAt.y} items={menuItems} onClose={() => setMenuAt(null)} />}
+ {host && (
+ <NodeResizer
+ minWidth={NODE_MIN_SIZES.simulator.width}
+ minHeight={NODE_MIN_SIZES.simulator.height}
+ isVisible={host.selected}
+ color={host.color}
+ // A hand resize snaps to the screen's shape when it ends, following the side that was
+ // dragged — widen it and the height follows; make it taller and the width follows.
+ onResizeStart={() => {
+ const sc = screenRef.current
+ resizeFrom.current = sc ? { w: sc.offsetWidth, h: sc.offsetHeight } : null
+ }}
+ onResizeEnd={() =>
+ requestAnimationFrame(() => {
+ const sc = screenRef.current
+ const from = resizeFrom.current
+ resizeFrom.current = null
+ fitToScreen(sc && from ? draggedSide(from, { w: sc.offsetWidth, h: sc.offsetHeight }) : 'long')
+ })
+ }
+ />
+ )}
+ </>
+ )
+}
+
+/** A point outside the drawn screen, pinned to its nearest edge (a drag that leaves the screen). */
+function clampedRatio(clientX: number, clientY: number, box: DOMRect, frame: { w: number; h: number }) {
+ const scale = Math.min(box.width / frame.w, box.height / frame.h)
+ const left = box.left + (box.width - frame.w * scale) / 2
+ const top = box.top + (box.height - frame.h * scale) / 2
+ return {
+ x: Math.min(1, Math.max(0, (clientX - left) / (frame.w * scale))),
+ y: Math.min(1, Math.max(0, (clientY - top) / (frame.h * scale)))
+ }
+}
+
+interface PromptField {
+ key: string
+ label: string
+ placeholder?: string
+ multiline?: boolean
+ value?: string
+}
+interface PromptSpec {
+ title: string
+ fields: PromptField[]
+ submitLabel: string
+ onSubmit: (values: Record<string, string>) => void
+}
+interface ConfirmSpec {
+ title: string
+ body: string
+ confirmLabel: string
+ onConfirm: () => void
+}
+
+/** A small in-node form for the menu items that need a value (URL, push payload, coordinates). */
+function SimPrompt({ spec, onClose }: { spec: PromptSpec; onClose: () => void }) {
+ const [values, setValues] = useState<Record<string, string>>(() =>
+ Object.fromEntries(spec.fields.map((f) => [f.key, f.value ?? '']))
+ )
+ const submit = () => {
+ spec.onSubmit(values)
+ onClose()
+ }
+ return (
+ <div className="sim-node__overlay nodrag nowheel" onKeyDown={(e) => e.stopPropagation()}>
+ <form
+ className="sim-node__dialog"
+ onSubmit={(e) => {
+ e.preventDefault()
+ submit()
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') onClose()
+ }}
+ >
+ <div className="sim-node__dialog-title">{spec.title}</div>
+ {spec.fields.map((f, i) => (
+ <label key={f.key} className="sim-node__field">
+ <span>{f.label}</span>
+ {f.multiline ? (
+ <textarea
+ autoFocus={i === 0}
+ rows={7}
+ spellCheck={false}
+ value={values[f.key]}
+ placeholder={f.placeholder}
+ onChange={(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))}
+ />
+ ) : (
+ <input
+ autoFocus={i === 0}
+ spellCheck={false}
+ value={values[f.key]}
+ placeholder={f.placeholder}
+ onChange={(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))}
+ />
+ )}
+ </label>
+ ))}
+ <div className="sim-node__dialog-actions">
+ <button type="button" className="run-bar__btn" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="run-bar__btn run-bar__btn--run">
+ {spec.submitLabel}
+ </button>
+ </div>
+ </form>
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index fdc11cc9c..b263797be 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -6644,7 +6644,7 @@ export function TerminalNode({
sessions only — a relay tab's or an SSH node's terminal runs on another machine, whose
checkouts and devices this one cannot see. */}
{data.runConfig && session.source === 'local' && !data.ssh && !data.sshRemoteTmux && (
- <RunBar nodeId={id} config={data.runConfig} autoStart={!!data.runAutoStart} />
+ <RunBar nodeId={id} config={data.runConfig} autoStart={!!data.runAutoStart} simulator={data.runSimulator} browser={data.runBrowser} />
)}
{/* Body always mounted (keeps xterm alive); hidden via CSS when collapsed. */}
diff --git a/src/renderer/nodes/simulatorMenu.test.ts b/src/renderer/nodes/simulatorMenu.test.ts
new file mode 100644
index 000000000..859dbfc32
--- /dev/null
+++ b/src/renderer/nodes/simulatorMenu.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { MenuItem } from '../components/ContextMenu'
+import { buildSimulatorMenu, type SimulatorMenuHandlers } from './simulatorMenu'
+
+function handlers(): SimulatorMenuHandlers {
+ return {
+ button: vi.fn(), rotate: vi.fn(), action: vi.fn(), screenshot: vi.fn(), toggleRecording: vi.fn(),
+ shutDown: vi.fn(), confirmErase: vi.fn(), promptCustomLocation: vi.fn(), promptOpenUrl: vi.fn(),
+ promptPush: vi.fn(), promptPrivacy: vi.fn(), pickInstall: vi.fn(), pickMedia: vi.fn(),
+ actualSize: vi.fn(), fitToScreen: vi.fn()
+ }
+}
+
+/** Every clickable leaf, with its path ("Device › Home"). */
+function leaves(items: MenuItem[], prefix = ''): Array<{ path: string; item: Extract<MenuItem, { onClick: () => void }> }> {
+ const out: Array<{ path: string; item: Extract<MenuItem, { onClick: () => void }> }> = []
+ for (const it of items) {
+ if (it.type === 'submenu') out.push(...leaves(it.children, `${prefix}${it.label} › `))
+ else if ('onClick' in it) out.push({ path: prefix + it.label, item: it })
+ }
+ return out
+}
+
+describe('the Simulator ⋯ menu', () => {
+ const menu = buildSimulatorMenu(handlers(), { device: { appearance: 'dark', increaseContrast: true, locationScenarios: ['City Run', 'Freeway Drive'] }, recording: false })
+ const all = leaves(menu)
+
+ it('lists DeviceHub’s groups', () => {
+ const groups = menu.filter((m): m is Extract<MenuItem, { type: 'submenu' }> => m.type === 'submenu').map((m) => m.label)
+ expect(groups).toEqual(['Device', 'Capture', 'Appearance', 'Location', 'Status Bar', 'Biometrics', 'Clipboard', 'Apps', 'View', 'Device Management'])
+ })
+
+ it('greys out every "(Not Supported)" item, each with a reason — and nothing else', () => {
+ for (const { path, item } of all) {
+ const ns = item.label.endsWith('(Not Supported)')
+ expect(!!item.disabled, path).toBe(ns)
+ if (ns) expect(item.hint, path).toBeTruthy()
+ }
+ expect(all.filter((l) => l.item.disabled).map((l) => l.path)).toEqual([
+ 'Device › App Switcher (Not Supported)',
+ 'Device › Action Button (Not Supported)',
+ 'Device › Directional Pad (Not Supported)',
+ 'Device › Simulate Trackpad (Not Supported)',
+ 'Device › Back (Not Supported)',
+ 'Appearance › Grayscale (Not Supported)',
+ 'Appearance › Reduce Motion (Not Supported)',
+ 'Appearance › Reduce Transparency (Not Supported)',
+ 'Appearance › Liquid Glass Look (Not Supported)',
+ 'Biometrics › Optic ID (Not Supported)',
+ 'Apps › Provisioning Profiles (Not Supported)',
+ 'Apps › Crash Reports (Not Supported)',
+ 'Device Management › New Device… (Not Supported)',
+ 'Device Management › Rename… (Not Supported)',
+ 'Device Management › Pair Apple Watch… (Not Supported)',
+ 'Device Management › Pair Nearby Device… (Not Supported)'
+ ])
+ })
+
+ it('marks the current settings and lists the location scenarios', () => {
+ const labels = all.map((l) => l.path)
+ expect(labels).toContain('Appearance › ✓ Dark')
+ expect(labels).toContain('Appearance › Light')
+ expect(labels).toContain('Appearance › ✓ Increase Contrast')
+ expect(labels).toContain('Location › City Run')
+ expect(labels).toContain('Location › Freeway Drive')
+ })
+
+ it('wires every supported item to a handler', () => {
+ const h = handlers()
+ const m = buildSimulatorMenu(h, { device: {}, recording: false })
+ for (const { item } of leaves(m)) if (!item.disabled) item.onClick()
+ for (const [name, fn] of Object.entries(h)) expect(fn, name).toHaveBeenCalled()
+ })
+
+ it('offers Stop while recording', () => {
+ const m = buildSimulatorMenu(handlers(), { device: {}, recording: true })
+ expect(leaves(m).map((l) => l.path)).toContain('Capture › ■ Stop Recording')
+ })
+})
diff --git a/src/renderer/nodes/simulatorMenu.tsx b/src/renderer/nodes/simulatorMenu.tsx
new file mode 100644
index 000000000..6d44d8119
--- /dev/null
+++ b/src/renderer/nodes/simulatorMenu.tsx
@@ -0,0 +1,362 @@
+import type { MenuItem } from '../components/ContextMenu'
+import type {
+ BatteryState,
+ SimulatorAction,
+ SimulatorButton,
+ SimulatorCaptureTarget,
+ SimulatorDeviceState
+} from '@shared/simulator'
+
+/**
+ * The Simulator node's ⋯ menu: everything DeviceHub's menus offer, in the same groups. What
+ * nodeterm can do runs; what it cannot (yet) is listed greyed out with "(Not Supported)" and the
+ * reason as its tooltip — so the menu is a complete map of DeviceHub, not a guess at a subset.
+ *
+ * Pure: the node supplies the handlers and the device state, this decides labels and structure.
+ */
+
+export interface SimulatorMenuHandlers {
+ button(name: SimulatorButton): void
+ rotate(dir: 'left' | 'right'): void
+ action(a: SimulatorAction): void
+ screenshot(target: SimulatorCaptureTarget): void
+ toggleRecording(): void
+ shutDown(): void
+ confirmErase(): void
+ promptCustomLocation(): void
+ promptOpenUrl(): void
+ promptPush(): void
+ promptPrivacy(op: 'grant' | 'revoke'): void
+ pickInstall(): void
+ pickMedia(): void
+ /** Absent inside a run node, which the view does not size. */
+ actualSize?(): void
+ fitToScreen?(): void
+}
+
+export interface SimulatorMenuState {
+ device: SimulatorDeviceState
+ recording: boolean
+}
+
+const NOT_SUPPORTED = ' (Not Supported)'
+
+function notSupported(label: string, why: string): MenuItem {
+ return { label: label + NOT_SUPPORTED, disabled: true, hint: why, onClick: () => undefined }
+}
+
+/** A View-menu sizing item: inside a run node there is no node of its own to size. */
+function sizeItem(label: string, fn: (() => void) | undefined): MenuItem {
+ return fn
+ ? { label, onClick: () => fn() }
+ : { label, disabled: true, hint: 'Pop the simulator out of the run node to size it.', onClick: () => undefined }
+}
+
+const check = (on: boolean | undefined, label: string) => (on ? `✓ ${label}` : label)
+
+export function buildSimulatorMenu(h: SimulatorMenuHandlers, s: SimulatorMenuState): MenuItem[] {
+ const d = s.device
+ const battery = (level: number, state: BatteryState, label: string): MenuItem => ({
+ label,
+ onClick: () => h.action({ a: 'status-bar', preset: 'battery', batteryLevel: level, batteryState: state })
+ })
+ const bio = (kind: 'face' | 'touch'): MenuItem[] => [
+ { label: 'Enrolled', onClick: () => h.action({ a: 'biometric', kind, op: 'enroll' }) },
+ { label: 'Not Enrolled', onClick: () => h.action({ a: 'biometric', kind, op: 'unenroll' }) },
+ { type: 'separator' },
+ { label: kind === 'face' ? 'Matching Face' : 'Matching Touch', onClick: () => h.action({ a: 'biometric', kind, op: 'match' }) },
+ { label: kind === 'face' ? 'Non-matching Face' : 'Non-matching Touch', onClick: () => h.action({ a: 'biometric', kind, op: 'nomatch' }) }
+ ]
+
+ return [
+ {
+ type: 'submenu',
+ label: 'Device',
+ children: [
+ { label: 'Home', onClick: () => h.button('home') },
+ { label: 'Lock', onClick: () => h.button('lock') },
+ { label: 'Side Button', onClick: () => h.button('side') },
+ { label: 'Siri', onClick: () => h.button('siri') },
+ notSupported('App Switcher', 'The swipe-up-and-hold gesture is not recognised when sent from outside DeviceHub yet.'),
+ notSupported('Action Button', 'The Action Button’s input code is not documented.'),
+ { type: 'separator' },
+ { label: 'Volume Up', onClick: () => h.button('volup') },
+ { label: 'Volume Down', onClick: () => h.button('voldown') },
+ { label: 'Play / Pause', onClick: () => h.button('playpause') },
+ { type: 'separator' },
+ { label: 'Shake', onClick: () => h.action({ a: 'shake' }) },
+ { label: 'Rotate Left ⌘←', onClick: () => h.rotate('left') },
+ { label: 'Rotate Right ⌘→', onClick: () => h.rotate('right') },
+ { type: 'separator' },
+ { label: 'Restart', onClick: () => h.action({ a: 'restart' }) },
+ { label: 'Reset Content and Settings…', danger: true, onClick: () => h.confirmErase() },
+ { label: 'Shut Down', onClick: () => h.shutDown() },
+ { type: 'separator' },
+ notSupported('Directional Pad', 'Apple TV only.'),
+ notSupported('Simulate Trackpad', 'Apple TV only.'),
+ notSupported('Back', 'Apple Watch / Apple TV only.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Capture',
+ children: [
+ { label: 'Save Screenshot to Desktop', onClick: () => h.screenshot('desktop') },
+ { label: 'Copy Screenshot', onClick: () => h.screenshot('clipboard') },
+ { label: 'Add Screenshot to Canvas', onClick: () => h.screenshot('canvas') },
+ { type: 'separator' },
+ { label: s.recording ? '■ Stop Recording' : '● Record Screen', onClick: () => h.toggleRecording() }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Appearance',
+ children: [
+ { label: check(d.appearance === 'light', 'Light'), onClick: () => h.action({ a: 'appearance', value: 'light' }) },
+ { label: check(d.appearance === 'dark', 'Dark'), onClick: () => h.action({ a: 'appearance', value: 'dark' }) },
+ { type: 'separator' },
+ { label: 'Larger Text', onClick: () => h.action({ a: 'content-size', value: 'increment' }) },
+ { label: 'Smaller Text', onClick: () => h.action({ a: 'content-size', value: 'decrement' }) },
+ {
+ label: check(d.increaseContrast, 'Increase Contrast'),
+ onClick: () => h.action({ a: 'increase-contrast', value: !d.increaseContrast })
+ },
+ { type: 'separator' },
+ notSupported('Grayscale', 'DeviceHub sets this through Apple internals; there is no public simctl command for it.'),
+ notSupported('Reduce Motion', 'DeviceHub sets this through Apple internals; there is no public simctl command for it.'),
+ notSupported('Reduce Transparency', 'DeviceHub sets this through Apple internals; there is no public simctl command for it.'),
+ notSupported('Liquid Glass Look', 'DeviceHub sets this through Apple internals; there is no public simctl command for it.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Location',
+ children: [
+ { label: 'None', onClick: () => h.action({ a: 'location-clear' }) },
+ ...((d.locationScenarios ?? []).length ? [{ type: 'separator' } as MenuItem] : []),
+ ...(d.locationScenarios ?? []).map(
+ (scenario): MenuItem => ({ label: scenario, onClick: () => h.action({ a: 'location-run', scenario }) })
+ ),
+ { type: 'separator' },
+ { label: 'Custom Location…', onClick: () => h.promptCustomLocation() }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Status Bar',
+ children: [
+ { label: 'Clean (9:41, full battery)', onClick: () => h.action({ a: 'status-bar', preset: 'clean' }) },
+ {
+ type: 'submenu',
+ label: 'Battery',
+ children: [
+ battery(100, 'charged', '100% — Charged'),
+ battery(50, 'charging', '50% — Charging'),
+ battery(50, 'discharging', '50%'),
+ battery(20, 'discharging', '20%'),
+ battery(5, 'discharging', '5%')
+ ]
+ },
+ { type: 'separator' },
+ { label: 'Clear Overrides', onClick: () => h.action({ a: 'status-bar', preset: 'clear' }) }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Biometrics',
+ children: [
+ { type: 'submenu', label: 'Face ID', children: bio('face') },
+ { type: 'submenu', label: 'Touch ID', children: bio('touch') },
+ notSupported('Optic ID', 'Apple Vision Pro only.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Clipboard',
+ children: [
+ { label: 'Paste Mac Clipboard into Device ⌘V', onClick: () => h.action({ a: 'pasteboard', dir: 'to-device' }) },
+ { label: 'Copy Device Clipboard to Mac', onClick: () => h.action({ a: 'pasteboard', dir: 'to-mac' }) }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Apps',
+ children: [
+ { label: 'Install App…', onClick: () => h.pickInstall() },
+ { label: 'Add Photo or Video…', onClick: () => h.pickMedia() },
+ { type: 'separator' },
+ { label: 'Open URL…', onClick: () => h.promptOpenUrl() },
+ { label: 'Send Push Notification…', onClick: () => h.promptPush() },
+ {
+ type: 'submenu',
+ label: 'Privacy',
+ children: [
+ { label: 'Grant All Permissions to App…', onClick: () => h.promptPrivacy('grant') },
+ { label: 'Revoke All Permissions from App…', onClick: () => h.promptPrivacy('revoke') },
+ { type: 'separator' },
+ { label: 'Reset All Permissions', onClick: () => h.action({ a: 'privacy', op: 'reset', service: 'all' }) }
+ ]
+ },
+ { type: 'separator' },
+ notSupported('Provisioning Profiles', 'Managed in DeviceHub.'),
+ notSupported('Crash Reports', 'Managed in DeviceHub.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'View',
+ children: [
+ sizeItem('Actual Size', h.actualSize),
+ sizeItem('Fit to Screen', h.fitToScreen)
+ ]
+ },
+ { type: 'separator' },
+ {
+ label: 'Open in DeviceHub',
+ hint: 'While DeviceHub shows this device, it takes the touch input — close its window to tap here again.',
+ onClick: () => h.action({ a: 'open-devicehub' })
+ },
+ {
+ type: 'submenu',
+ label: 'Device Management',
+ children: [
+ notSupported('New Device…', 'Create devices in DeviceHub.'),
+ notSupported('Rename…', 'Rename devices in DeviceHub.'),
+ notSupported('Pair Apple Watch…', 'Pair devices in DeviceHub.'),
+ notSupported('Pair Nearby Device…', 'Pair devices in DeviceHub.')
+ ]
+ }
+ ]
+}
+
+/**
+ * The ⋯ menu for an Android virtual device. The same shape as the iOS one: what the emulator's own
+ * interface (or adb) can do runs, and what it cannot is listed greyed out with "(Not Supported)".
+ */
+export function buildAndroidMenu(h: SimulatorMenuHandlers, s: Pick<SimulatorMenuState, 'device'>): MenuItem[] {
+ const d = s.device
+ const battery = (level: number, state: BatteryState, label: string): MenuItem => ({
+ label,
+ onClick: () => h.action({ a: 'status-bar', preset: 'battery', batteryLevel: level, batteryState: state })
+ })
+ return [
+ {
+ type: 'submenu',
+ label: 'Device',
+ children: [
+ { label: 'Home', onClick: () => h.button('home') },
+ { label: 'Back', onClick: () => h.button('back') },
+ { label: 'Recent Apps', onClick: () => h.button('recents') },
+ { label: 'Power', onClick: () => h.button('lock') },
+ { type: 'separator' },
+ { label: 'Volume Up', onClick: () => h.button('volup') },
+ { label: 'Volume Down', onClick: () => h.button('voldown') },
+ { label: 'Play / Pause', onClick: () => h.button('playpause') },
+ { type: 'separator' },
+ { label: 'Rotate Left ⌘←', onClick: () => h.rotate('left') },
+ { label: 'Rotate Right ⌘→', onClick: () => h.rotate('right') },
+ { type: 'separator' },
+ { label: 'Restart', onClick: () => h.action({ a: 'restart' }) },
+ { label: 'Shut Down', onClick: () => h.shutDown() },
+ notSupported('Wipe Data…', 'Use Android Studio’s Device Manager → Wipe Data (the emulator must be stopped).'),
+ notSupported('Fold / Unfold', 'Foldable postures are not wired up yet.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Capture',
+ children: [
+ { label: 'Save Screenshot to Desktop', onClick: () => h.screenshot('desktop') },
+ { label: 'Copy Screenshot', onClick: () => h.screenshot('clipboard') },
+ { label: 'Add Screenshot to Canvas', onClick: () => h.screenshot('canvas') },
+ { type: 'separator' },
+ notSupported('Record Screen', 'Screen recording for Android devices is not wired up yet.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Appearance',
+ children: [
+ { label: check(d.appearance === 'light', 'Light'), onClick: () => h.action({ a: 'appearance', value: 'light' }) },
+ { label: check(d.appearance === 'dark', 'Dark'), onClick: () => h.action({ a: 'appearance', value: 'dark' }) },
+ { type: 'separator' },
+ { label: 'Larger Text', onClick: () => h.action({ a: 'content-size', value: 'increment' }) },
+ { label: 'Smaller Text', onClick: () => h.action({ a: 'content-size', value: 'decrement' }) }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Location',
+ children: [
+ { label: 'Custom Location…', onClick: () => h.promptCustomLocation() },
+ notSupported('Routes', 'GPX / KML routes are played from Android Studio’s extended controls.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Status Bar',
+ children: [
+ { label: 'Clean (9:41, full battery)', onClick: () => h.action({ a: 'status-bar', preset: 'clean' }) },
+ {
+ type: 'submenu',
+ label: 'Battery',
+ children: [
+ battery(100, 'charged', '100% — Charged'),
+ battery(50, 'charging', '50% — Charging'),
+ battery(50, 'discharging', '50%'),
+ battery(20, 'discharging', '20%'),
+ battery(5, 'discharging', '5%')
+ ]
+ },
+ { type: 'separator' },
+ { label: 'Clear Overrides', onClick: () => h.action({ a: 'status-bar', preset: 'clear' }) }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Biometrics',
+ children: [
+ { label: 'Matching Fingerprint', onClick: () => h.action({ a: 'biometric', kind: 'touch', op: 'match' }) },
+ { label: 'Non-matching Fingerprint', onClick: () => h.action({ a: 'biometric', kind: 'touch', op: 'nomatch' }) },
+ notSupported('Face Unlock', 'The emulator has no face sensor to simulate.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Clipboard',
+ children: [
+ { label: 'Paste Mac Clipboard into Device ⌘V', disabled: true, hint: 'Press ⌘V while the screen has focus.', onClick: () => undefined },
+ { label: 'Copy Device Clipboard to Mac', onClick: () => h.action({ a: 'pasteboard', dir: 'to-mac' }) }
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'Apps',
+ children: [
+ { label: 'Install APK…', onClick: () => h.pickInstall() },
+ { label: 'Add Photo or Video…', onClick: () => h.pickMedia() },
+ { type: 'separator' },
+ { label: 'Open URL…', onClick: () => h.promptOpenUrl() },
+ notSupported('Send Push Notification…', 'Android push goes through Firebase Cloud Messaging, which the emulator does not simulate.'),
+ notSupported('Permissions…', 'Grant or revoke permissions with adb shell pm grant / revoke.')
+ ]
+ },
+ {
+ type: 'submenu',
+ label: 'View',
+ children: [
+ sizeItem('Actual Size', h.actualSize),
+ sizeItem('Fit to Screen', h.fitToScreen)
+ ]
+ },
+ { type: 'separator' },
+ {
+ type: 'submenu',
+ label: 'Device Management',
+ children: [
+ notSupported('New Device…', 'Create virtual devices in Android Studio’s Device Manager.'),
+ notSupported('Rename…', 'Rename virtual devices in Android Studio’s Device Manager.')
+ ]
+ }
+ ]
+}
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index c1eacfb17..341524444 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -40,7 +40,9 @@ import { isSafeNodeId } from '@shared/safe-id'
import { openerByTarget, recordedOpenerOf } from '../lib/teamProgress'
import { normalizePendingLaunch } from '@shared/pending-launch-shape'
import { normalizeTerminalFontSize } from '../terminal/terminal-font-zoom'
-import { normalizeRunConfig, runNodeTitle, type RunNodeConfig } from '@shared/run-config'
+import { RUN_NODE_ID, normalizeRunConfig, runNodeTitle, type RunNodeConfig } from '@shared/run-config'
+import { normalizeRunBrowserConfig } from '@shared/run-preview'
+import { normalizeInlineSimulatorConfig, normalizeSimulatorConfig, type SimulatorNodeConfig } from '@shared/simulator'
import { useSettings } from './settings'
// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the
@@ -73,6 +75,8 @@ const BROWSER_SIZE = { width: 800, height: 560 }
// Tall and narrow: a file manager is a LIST, and the thing that runs out first is vertical room
// for entries, not horizontal room for names (which ellipsize).
const FILES_SIZE = { width: 340, height: 460 }
+/** A phone held upright, with room for the toolbar. The screen keeps its own aspect inside. */
+const SIMULATOR_SIZE = { width: 360, height: 760 }
/** Height of a node when collapsed (header only). */
export const COLLAPSED_HEIGHT = 40
@@ -188,6 +192,10 @@ export interface NodeData {
* through persistence untouched on Server Edition / mobile, where a browser node has no <webview>.
*/
partition?: string
+ /** browser-only: popped out of a run node's browser panel — that run node's id, to dock back. */
+ dockTo?: string
+ /** Run nodes only: the browser panel inside the node (present = shown). See @shared/run-preview. */
+ runBrowser?: import('@shared/run-preview').RunBrowserConfig
/**
* browser/web-only, NEVER persisted: this node object is a background KEEP-ALIVE GHOST — a
* `display:none` stand-in merged into the `<ReactFlow>` prop so the `<webview>` of a project the
@@ -249,8 +257,12 @@ export interface NodeData {
trigger?: import('@shared/trigger').TriggerSpec
/** Run nodes only: which launch.json configuration runs, where. See @shared/run-config. Persisted. */
runConfig?: import('@shared/run-config').RunNodeConfig
+ /** Run nodes only: a simulator shown inside the node (present = shown). See @shared/simulator. */
+ runSimulator?: import('@shared/simulator').InlineSimulatorConfig
/** Run nodes only, transient: start the run on mount (a compound's sibling). Never persisted. */
runAutoStart?: boolean
+ /** simulator-only: which iOS simulator the node shows. See @shared/simulator. Persisted. */
+ simulator?: import('@shared/simulator').SimulatorNodeConfig
[key: string]: unknown
}
@@ -425,6 +437,30 @@ export function createRunNode(
}
}
+/**
+ * A Simulator node: a live iOS simulator screen (see @shared/simulator, nodes/SimulatorNode). The
+ * device is chosen in the node; `config` pre-selects one (a run node opening its simulator).
+ */
+export function createSimulatorNode(
+ index: number,
+ config: SimulatorNodeConfig = {},
+ center?: { x: number; y: number }
+): CanvasNode {
+ const c = normalizeSimulatorConfig(config)
+ return {
+ id: nextId('sim'),
+ type: 'simulator',
+ ...placeNode('simulator', center, index, SIMULATOR_SIZE.width, SIMULATOR_SIZE.height),
+ data: {
+ title: c.name ?? 'Simulator',
+ color: RUN_NODE_COLOR,
+ group: null,
+ tags: [],
+ simulator: c
+ }
+ }
+}
+
/**
* Creates a terminal node that runs `ssh` to a saved server on the local PTY. The connection
* is snapshotted inline (`data.ssh`) so the node survives the server being edited/deleted.
@@ -2648,6 +2684,8 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
fileMissing: n.fileMissing,
url: n.url,
partition: n.partition,
+ dockTo: n.kind === 'browser' && typeof n.dockTo === 'string' && RUN_NODE_ID.test(n.dockTo) ? n.dockTo : undefined,
+ runBrowser: n.runConfig ? normalizeRunBrowserConfig(n.runBrowser) : undefined,
diffStaged: n.diffStaged,
commitOid: n.commitOid,
highScore: n.highScore,
@@ -2669,7 +2707,9 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
worktree: n.worktree,
trigger: n.trigger,
// Hostile-input seam (git-shared file → live data), like `icon` above.
- runConfig: normalizeRunConfig(n.runConfig)
+ runConfig: normalizeRunConfig(n.runConfig),
+ runSimulator: n.runConfig ? normalizeInlineSimulatorConfig(n.runSimulator) : undefined,
+ simulator: n.kind === 'simulator' ? normalizeSimulatorConfig(n.simulator) : undefined
}
}
})
@@ -2699,7 +2739,9 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = tru
? TRIGGER_SIZE
: kind === 'files'
? FILES_SIZE
- : TERMINAL_SIZE
+ : kind === 'simulator'
+ ? SIMULATOR_SIZE
+ : TERMINAL_SIZE
return nodes
.map((n) => {
const kind: NodeKind = (n.type as NodeKind) ?? 'terminal'
@@ -2739,6 +2781,8 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = tru
fileMissing: n.data.fileMissing,
url: n.data.url,
partition: n.data.partition,
+ dockTo: kind === 'browser' && typeof n.data.dockTo === 'string' && RUN_NODE_ID.test(n.data.dockTo) ? n.data.dockTo : undefined,
+ runBrowser: n.data.runConfig ? normalizeRunBrowserConfig(n.data.runBrowser) : undefined,
diffStaged: n.data.diffStaged,
commitOid: n.data.commitOid,
highScore: n.data.highScore,
@@ -2761,6 +2805,8 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = tru
trigger: n.data.trigger,
// Re-validated on the way OUT too — the shared file is only as good as its last writer.
runConfig: normalizeRunConfig(n.data.runConfig),
+ runSimulator: n.data.runConfig ? normalizeInlineSimulatorConfig(n.data.runSimulator) : undefined,
+ simulator: kind === 'simulator' ? normalizeSimulatorConfig(n.data.simulator) : undefined,
premaxRect: n.data.premaxRect
}
})
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 2800dbd20..12f9e2420 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -4039,6 +4039,48 @@ body,
font-size: 11.5px;
color: var(--text);
}
+/* A simulator inside a run node (SimulatorView under the control rows). It fills what the node has
+ left, so resizing the node scales the screen (letterboxed, like a Simulator node): the bar stops
+ being a fixed strip and takes the space, and the panel takes the bar's. With the terminal shown
+ the two share the node. Positioned so the view's toasts, prompts and dialogs sit over the panel. */
+.run-bar--sim {
+ flex: 1 1 0;
+ min-height: 0;
+}
+.run-sim-host {
+ flex: 1 1 0;
+ min-height: 80px;
+ display: flex;
+ margin: 2px -8px -5px;
+ border-top: 1px solid var(--border);
+}
+.run-web {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+.run-web__waiting {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 16px;
+ text-align: center;
+ font-size: 12px;
+ color: var(--muted);
+ pointer-events: none;
+}
+.run-sim {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
/* Terminal hidden (the default): the node is just the control rows. Same `display: none` path a
collapsed node takes, so xterm and the tmux client stay alive underneath. */
.term-node:has(.run-bar--compact) .term-node__body {
@@ -4171,6 +4213,16 @@ body,
.run-bar__select--config {
max-width: 240px;
}
+.run-bar__check {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex: none;
+ font-size: 11px;
+ color: var(--muted);
+ white-space: nowrap;
+ cursor: pointer;
+}
.run-bar__args {
flex: 1;
min-width: 0;
@@ -17980,3 +18032,230 @@ body.focus-mode .dock:hover {
border-radius: 3px;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 60%, transparent);
}
+
+/* ── Simulator node (nodes/SimulatorNode.tsx) ─────────────────────────────────────────────────
+ A live iOS simulator screen: header, a control row, then the screen, which keeps the phone's
+ proportions (object-fit: contain) inside whatever size the node is. */
+.sim-node {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ overflow: hidden;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, calc(0.35 * var(--shadow-k)));
+}
+.sim-node.selected {
+ border-color: var(--accent);
+}
+.sim-node__header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 8px;
+ cursor: grab;
+ flex-shrink: 0;
+}
+.sim-node__title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text);
+}
+.sim-node__bar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 5px;
+ padding: 4px 8px 6px;
+ border-bottom: 1px solid var(--border);
+ font-size: 11.5px;
+ flex-shrink: 0;
+}
+.sim-node__device {
+ flex: 1;
+ min-width: 0;
+ max-width: none;
+}
+.sim-node__screen {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ /* theme-exempt: the letterbox around a device screen is black in every theme, like a video. */
+ background: #000;
+ outline: none;
+ cursor: pointer;
+ touch-action: none;
+}
+.sim-node__screen:focus-visible {
+ box-shadow: inset 0 0 0 2px var(--accent);
+}
+.sim-node__frame {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ user-select: none;
+ pointer-events: none;
+}
+.sim-node__placeholder {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ text-align: center;
+ font-size: 12px;
+ line-height: 1.5;
+ color: rgba(255, 255, 255, 0.7);
+}
+.sim-node__note {
+ position: absolute;
+ left: 8px;
+ right: 8px;
+ bottom: 8px;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 11px;
+ color: #fff;
+ background: rgba(0, 0, 0, 0.6);
+ pointer-events: none;
+}
+
+.sim-node__hint {
+ position: absolute;
+ left: 8px;
+ right: 8px;
+ top: 8px;
+ display: flex;
+ gap: 8px;
+ align-items: flex-start;
+ padding: 6px 8px;
+ border-radius: 7px;
+ font-size: 11px;
+ line-height: 1.35;
+ color: #fff;
+ background: rgba(0, 0, 0, 0.72);
+}
+.sim-node__hint-close {
+ flex: none;
+ padding: 0 2px;
+ font: inherit;
+ font-size: 13px;
+ line-height: 1;
+ color: inherit;
+ background: none;
+ border: none;
+ cursor: pointer;
+}
+
+.sim-node__rec {
+ height: 22px;
+ padding: 0 7px;
+ font: inherit;
+ font-size: 10.5px;
+ font-weight: 700;
+ color: var(--danger);
+ background: color-mix(in srgb, var(--danger) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--danger) 45%, transparent);
+ border-radius: 5px;
+ cursor: pointer;
+}
+.sim-node__drop {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 16px;
+ text-align: center;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 14%, transparent);
+ border: 2px dashed var(--accent);
+ pointer-events: none;
+}
+.sim-node__toast {
+ position: absolute;
+ left: 10px;
+ right: 10px;
+ bottom: 10px;
+ padding: 6px 10px;
+ border-radius: 7px;
+ font-size: 11.5px;
+ color: var(--text);
+ background: var(--panel);
+ border: 1px solid var(--border);
+ box-shadow: 0 6px 20px rgba(0, 0, 0, calc(0.3 * var(--shadow-k)));
+ pointer-events: none;
+}
+.sim-node__toast--error {
+ color: var(--danger);
+}
+.sim-node__overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 5;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 12px;
+ background: color-mix(in srgb, var(--bg) 55%, transparent);
+}
+.sim-node__dialog {
+ width: 100%;
+ max-width: 340px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 12px;
+ border-radius: 10px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ box-shadow: 0 10px 30px rgba(0, 0, 0, calc(0.4 * var(--shadow-k)));
+ font-size: 12px;
+ color: var(--text);
+}
+.sim-node__dialog-title {
+ font-weight: 600;
+ font-size: 13px;
+}
+.sim-node__dialog-body {
+ color: var(--muted);
+ line-height: 1.45;
+}
+.sim-node__field {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+.sim-node__field span {
+ color: var(--muted);
+ font-size: 11px;
+}
+.sim-node__field input,
+.sim-node__field textarea {
+ font: 11.5px ui-monospace, SFMono-Regular, Menlo, monospace;
+ color: var(--text);
+ background: var(--panel-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 5px 7px;
+ resize: vertical;
+}
+.sim-node__dialog-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 6px;
+ margin-top: 2px;
+}
diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.ts
index dcbb44958..d67e23bcb 100644
--- a/src/shared/host-control.test.ts
+++ b/src/shared/host-control.test.ts
@@ -42,6 +42,14 @@ describe('isHostOnlyChannel', () => {
expect(isHostOnlyChannel(IPC.agentBoardCommentDeliver)).toBe(true)
})
+ it('covers every simulator channel — a relay peer must not drive the host’s devices', () => {
+ for (const ch of (Object.values(IPC) as unknown[]).filter((c): c is string => typeof c === 'string' && c.startsWith('simulator:'))) {
+ expect(isHostOnlyChannel(ch)).toBe(true)
+ }
+ expect(isHostOnlyChannel(IPC.simulatorInput)).toBe(true)
+ expect(isHostOnlyChannel(IPC.simulatorAction)).toBe(true)
+ })
+
it('covers both station-notice request channels', () => {
// A guest may not report a pane verdict about the host's nodes…
expect(isHostOnlyChannel(IPC.stationNoticeDropped)).toBe(true)
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 1948ddaa6..0e4308efc 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -69,6 +69,10 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = [
// Agent-integration consent status: paths in the host's home it kept or wrote. The consent itself
// is in settings (already host-only).
'integrations:',
+ // Simulator node: the host's iOS simulators / Android emulators — boot, erase, install, input.
+ // A relay tab never offers the node (relay-api keeps the namespace local), so a peer sending one
+ // of these is asking to drive the host's devices.
+ 'simulator:',
// `nodeterm://` links: a link clicked on THIS machine opens a node here after THIS machine's user
// approves it. Raw ipcMain handlers (no peer reaches them); listed so a move onto the platform
// table cannot quietly open them.
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index fa4980896..a48bd3aac 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -410,6 +410,19 @@ export const IPC = {
runStop: 'run:stop',
runSignal: 'run:signal',
runWatch: 'run:watch',
+ // Simulator node (core/simulator/simulator-service.ts): live screen + touch/keys/buttons.
+ simulatorDevices: 'simulator:devices',
+ simulatorBoot: 'simulator:boot',
+ simulatorStart: 'simulator:start',
+ simulatorStop: 'simulator:stop',
+ simulatorInput: 'simulator:input',
+ simulatorShutdown: 'simulator:shutdown',
+ simulatorAction: 'simulator:action',
+ simulatorState: 'simulator:state',
+ simulatorScreenshot: 'simulator:screenshot',
+ simulatorRecordStart: 'simulator:record-start',
+ simulatorRecordStop: 'simulator:record-stop',
+ simulatorRecording: 'simulator:recording',
// Trigger nodes (issue #493): machine-local arm/disarm + the card's status/run-now.
triggersArm: 'triggers:arm',
triggersDisarm: 'triggers:disarm',
@@ -434,6 +447,9 @@ export const IPC = {
presencePeer: 'presence:peer',
// Events broadcast from main to the renderer (sessionId is appended to the channel name).
ptyData: (sessionId: string) => `pty:data:${sessionId}`,
+ /** Per-node simulator frames / status (Simulator node). */
+ simulatorFrame: (nodeId: string) => `simulator:frame:${nodeId}`,
+ simulatorStatus: (nodeId: string) => `simulator:status:${nodeId}`,
ptyExit: (sessionId: string) => `pty:exit:${sessionId}`,
/** Authoritative size of a co-attached session: min(cols) × min(rows) over all subscribers.
* Broadcast to every subscriber whenever the subscriber set or any reported size changes. */
diff --git a/src/shared/run-config.test.ts b/src/shared/run-config.test.ts
index dcf6ef70b..2ee772a91 100644
--- a/src/shared/run-config.test.ts
+++ b/src/shared/run-config.test.ts
@@ -12,6 +12,7 @@ import {
flavorOf,
isVmServiceUrl,
gateEntriesForPlatform,
+ embedsFlutterWeb,
normalizeRunConfig,
parseEnvFile,
parseJsonc,
@@ -217,6 +218,31 @@ describe('planLaunch — one row per type', () => {
expect(p.argv).not.toContain('SIM-1')
})
+ it('dart (Flutter): a Chrome device runs on the web server, wherever the device is named', () => {
+ const web = { isFlutterProject: true, webServer: true }
+ // picked
+ expect(proc({ type: 'dart', program: 'lib/main.dart' }, { ...web, deviceId: 'chrome' }).argv).toEqual([
+ 'flutter', 'run', '-t', 'lib/main.dart', '-d', 'web-server', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ // pinned in args, every spelling
+ expect(proc({ type: 'dart', program: 'lib/main.dart', args: ['-d', 'chrome'] }, web).argv).toContain('web-server')
+ expect(proc({ type: 'dart', program: 'lib/main.dart', args: ['-d=edge'] }, web).argv).toContain('-d=web-server')
+ expect(proc({ type: 'dart', program: 'lib/main.dart', toolArgs: ['--device-id', 'chrome'] }, web).argv).not.toContain('chrome')
+ // pinned as Dart-Code's deviceId field: passed as -d at all (it used to be dropped), swapped
+ expect(proc({ type: 'dart', program: 'lib/main.dart', deviceId: 'chrome' }, web).argv).toEqual([
+ 'flutter', 'run', '-t', 'lib/main.dart', '-d', 'web-server', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ // phones and desktops are untouched
+ expect(proc({ type: 'dart', program: 'lib/main.dart' }, { ...web, deviceId: 'SIM-1' }).argv).toContain('SIM-1')
+ })
+
+ it('dart (Flutter): with the panel off, Chrome stays Chrome — and a deviceId field is still passed', () => {
+ expect(proc({ type: 'dart', program: 'lib/main.dart' }, { isFlutterProject: true, deviceId: 'chrome' }).argv).toContain('chrome')
+ expect(proc({ type: 'dart', program: 'lib/main.dart', deviceId: 'macos' }, { isFlutterProject: true }).argv).toEqual([
+ 'flutter', 'run', '-t', 'lib/main.dart', '-d', 'macos', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ })
+
it('dart (Flutter): integration tests run with flutter test on the device', () => {
const p = proc({ type: 'dart', program: 'integration_test/auth_test.dart' }, { isFlutterProject: true, deviceId: 'SIM-1' })
expect(p.argv).toEqual(['flutter', 'test', '-d', 'SIM-1', 'integration_test/auth_test.dart'])
@@ -386,6 +412,15 @@ describe('normalizeRunConfig', () => {
expect(normalizeRunConfig({ projectDir: 'rel' })).toBeUndefined()
expect(normalizeRunConfig({ projectDir: '/a', deviceId: 'x; rm -rf ~', extraArgs: 'a\nb' })).toEqual({ projectDir: '/a', reloadOnSave: true })
})
+ it('keeps the Flutter web embed opt-in: an existing config runs in Chrome as before', () => {
+ const plain = normalizeRunConfig({ projectDir: '/a' })!
+ expect(plain.embedBrowser).toBeUndefined()
+ expect(embedsFlutterWeb(plain)).toBe(false)
+ expect(embedsFlutterWeb(normalizeRunConfig({ projectDir: '/a', embedBrowser: false })!)).toBe(false)
+ const on = normalizeRunConfig({ projectDir: '/a', embedBrowser: true })!
+ expect(on.embedBrowser).toBe(true)
+ expect(embedsFlutterWeb(on)).toBe(true)
+ })
})
describe('presentation', () => {
diff --git a/src/shared/run-config.ts b/src/shared/run-config.ts
index 6912001fb..740754d7b 100644
--- a/src/shared/run-config.ts
+++ b/src/shared/run-config.ts
@@ -47,6 +47,16 @@ export interface RunNodeConfig {
reloadOnSave: boolean
/** Whether the node shows its terminal (and the extra-arguments field). Default hidden. */
showTerminal?: boolean
+ /** Flutter web runs (Chrome / Edge): `true` = show the app INSIDE the run node (Flutter's web
+ * server serves it to the node's browser panel). Absent = Flutter's own Chrome window, what a
+ * Chrome run has always done. Opt-in, so an existing configuration runs exactly as before. */
+ embedBrowser?: boolean
+}
+
+/** Whether a Flutter browser-device run is moved onto Flutter's web server and shown inside the
+ * node. Opt-in: only an explicit `embedBrowser: true` — the one rule for the host and the bar. */
+export function embedsFlutterWeb(config: Pick<RunNodeConfig, 'embedBrowser'>): boolean {
+ return config.embedBrowser === true
}
const MAX_PATH = 4096
@@ -98,6 +108,7 @@ export function normalizeRunConfig(raw: unknown): RunNodeConfig | undefined {
const extraArgs = oneLine(r.extraArgs, MAX_EXTRA_ARGS)
if (extraArgs) out.extraArgs = extraArgs
if (r.showTerminal === true) out.showTerminal = true
+ if (r.embedBrowser === true) out.embedBrowser = true
return out
}
@@ -313,6 +324,19 @@ function str(v: unknown): string | undefined {
return typeof v === 'string' && v.trim() ? v : undefined
}
+/** Flutter's browser devices open a Chrome window of their own; its web server serves the same app
+ * to any browser and prints the address. Every other device is itself. */
+export function webServerDevice(d: string): string {
+ return d === 'chrome' || d === 'edge' ? 'web-server' : d
+}
+
+/** Whether a configuration names its device in its own args (as opposed to the `deviceId` field). */
+function pinnedInArgs(raw: Record<string, unknown>): boolean {
+ return [...strArray(raw.args), ...strArray(raw.toolArgs)].some(
+ (t) => t === '-d' || t === '--device-id' || t.startsWith('-d=') || t.startsWith('--device-id=')
+ )
+}
+
/** The device a Dart configuration pins (`-d x`, `--device-id x`, `-d=x`, or `deviceId`). */
export function pinnedDevice(raw: Record<string, unknown>): string | undefined {
const a = [...strArray(raw.args), ...strArray(raw.toolArgs)]
@@ -589,6 +613,9 @@ export interface PlanContext {
deviceId?: string
/** The node's extra arguments, appended to the program's own. */
extraArgs?: string
+ /** Run a Flutter browser device (chrome / edge) on Flutter's web server instead, so the app is
+ * served to the run node's browser panel rather than to a Chrome window of Flutter's own. */
+ webServer?: boolean
/** Where `flutter run` writes its pid (for hot reload / restart signals). */
flutterPidFile: string
tasks: readonly TaskDef[]
@@ -768,7 +795,22 @@ export function planLaunch(
if (entry.typeLabel === 'Flutter') {
// Dart-Code passes a Flutter config's `args` to `flutter run` too (the legacy behavior a
// config like `"args": ["--flavor", "dev"]` relies on), after `toolArgs`.
- const device = !entry.pinnedDevice && entry.usesDevice && ctx.deviceId ? ['-d', ctx.deviceId] : []
+ // The device: the node's pick, or the one the configuration names — in its args (rewritten
+ // in place) or as Dart-Code's `deviceId` field, which Dart-Code passes as `-d`.
+ const web = (d: string) => (ctx.webServer ? webServerDevice(d) : d)
+ let device: string[] = []
+ if (!entry.pinnedDevice && entry.usesDevice && ctx.deviceId) device = ['-d', web(ctx.deviceId)]
+ else if (entry.pinnedDevice && !pinnedInArgs(raw)) device = ['-d', web(entry.pinnedDevice)]
+ if (ctx.webServer) {
+ for (const list of [args, toolArgs]) {
+ for (let i = 0; i < list.length; i++) {
+ const t = list[i]
+ if ((t === '-d' || t === '--device-id') && list[i + 1]) list[i + 1] = web(list[i + 1])
+ else if (t.startsWith('-d=')) list[i] = `-d=${web(t.slice(3))}`
+ else if (t.startsWith('--device-id=')) list[i] = `--device-id=${web(t.slice('--device-id='.length))}`
+ }
+ }
+ }
const mode = raw.flutterMode === 'profile' ? ['--profile'] : raw.flutterMode === 'release' ? ['--release'] : []
if (isTest) return proc(['flutter', 'test', ...toolArgs, ...args, ...device, ...(program ? [program] : []), ...extra])
if (opts.attach || entry.attach) {
diff --git a/src/shared/run-preview.test.ts b/src/shared/run-preview.test.ts
new file mode 100644
index 000000000..5eebd1f9c
--- /dev/null
+++ b/src/shared/run-preview.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest'
+import { isSimulatorDeviceId, isWebDeviceId, localUrlFromOutput, normalizeRunBrowserConfig, previewKindFor } from './run-preview'
+
+const base = { picksDevice: false, browserConfig: false }
+
+describe('previewKindFor', () => {
+ it('a phone device gets the simulator, a browser device or configuration the browser', () => {
+ expect(previewKindFor({ ...base, picksDevice: true, deviceId: '0A1B2C3D-0000-4000-8000-00000000000A', deviceKind: 'simulator' })).toBe('simulator')
+ expect(previewKindFor({ ...base, picksDevice: true, deviceId: 'emulator-5554', deviceKind: 'emulator' })).toBe('simulator')
+ expect(previewKindFor({ ...base, picksDevice: true, deviceId: 'chrome', deviceKind: 'web' })).toBe('browser')
+ expect(previewKindFor({ ...base, picksDevice: true, deviceId: 'web-server' })).toBe('browser')
+ expect(previewKindFor({ ...base, browserConfig: true })).toBe('browser')
+ })
+
+ it('a dev server (no device) gets the browser', () => {
+ expect(previewKindFor(base)).toBe('browser')
+ })
+
+ it("follows the device a configuration names itself — the case that showed 📱 for a Chrome run", () => {
+ expect(previewKindFor({ ...base, picksDevice: false, pinnedDeviceId: 'chrome' })).toBe('browser')
+ expect(previewKindFor({ ...base, pinnedDeviceId: 'web-server' })).toBe('browser')
+ expect(previewKindFor({ ...base, pinnedDeviceId: 'emulator-5554' })).toBe('simulator')
+ expect(previewKindFor({ ...base, pinnedDeviceId: 'macos' })).toBe('simulator')
+ })
+
+ it('a device picker with nothing picked yet offers the simulator', () => {
+ expect(previewKindFor({ ...base, picksDevice: true })).toBe('simulator')
+ })
+})
+
+describe('localUrlFromOutput', () => {
+ it('reads the address Flutter serves a web app at, not its DevTools URL', () => {
+ const out = [
+ 'Launching lib/main.dart on Web Server in debug mode...',
+ 'Waiting for connection from debug service on Web Server... 12.4s',
+ 'lib/main.dart is being served at http://localhost:54123',
+ 'The web-server device requires the Dart Debug Chrome extension for debugging. Consider using the Chrome or Edge devices for an improved development workflow.',
+ 'The Flutter DevTools debugger and profiler on Web Server is available at: http://127.0.0.1:9101?uri=ws://127.0.0.1:54123/abc=/ws'
+ ].join('\n')
+ expect(localUrlFromOutput(out)).toBe('http://localhost:54123')
+ })
+
+ it('reads Vite and Next.js banners', () => {
+ expect(localUrlFromOutput(' VITE v5.4.0 ready in 312 ms\n\n ➜ Local: http://localhost:5173/\n ➜ Network: use --host to expose')).toBe('http://localhost:5173/')
+ expect(localUrlFromOutput(' ▲ Next.js 14.2.3\n - Local: http://localhost:3000\n')).toBe('http://localhost:3000')
+ })
+
+ it('opens an all-interfaces bind as localhost, and drops trailing punctuation', () => {
+ expect(localUrlFromOutput(' * Running on http://0.0.0.0:8000.')).toBe('http://localhost:8000')
+ })
+
+ it('takes the newest served address, and says nothing before one is printed', () => {
+ expect(localUrlFromOutput('Local: http://localhost:5173/\nport in use, retrying\nLocal: http://localhost:5174/')).toBe('http://localhost:5174/')
+ expect(localUrlFromOutput('Compiling…\nwaiting')).toBeNull()
+ expect(localUrlFromOutput('see https://example.com/docs')).toBeNull()
+ })
+})
+
+describe('isWebDeviceId', () => {
+ it('names Flutter\'s browser devices', () => {
+ expect(['chrome', 'edge', 'web-server'].every(isWebDeviceId)).toBe(true)
+ expect(isWebDeviceId('macos')).toBe(false)
+ })
+})
+
+describe('normalizeRunBrowserConfig', () => {
+ it('keeps only http(s) pages', () => {
+ expect(normalizeRunBrowserConfig({ url: 'http://localhost:5173/', auto: true })).toEqual({ url: 'http://localhost:5173/', auto: true })
+ expect(normalizeRunBrowserConfig({ url: 'file:///etc/passwd' })).toEqual({})
+ expect(normalizeRunBrowserConfig({ url: 'javascript:alert(1)' })).toEqual({})
+ expect(normalizeRunBrowserConfig(null)).toBeUndefined()
+ })
+
+ it('names the simulator device ids', () => {
+ expect(isSimulatorDeviceId('emulator-5554')).toBe(true)
+ expect(isSimulatorDeviceId('chrome')).toBe(false)
+ })
+})
diff --git a/src/shared/run-preview.ts b/src/shared/run-preview.ts
new file mode 100644
index 000000000..d90b5b58b
--- /dev/null
+++ b/src/shared/run-preview.ts
@@ -0,0 +1,93 @@
+/**
+ * The preview panel inside a run node: a simulator for a run that targets a phone, a browser for one
+ * that targets a browser (a `chrome` / `msedge` launch configuration, a Flutter web device) or serves
+ * a page (a dev server: vite, next, a Flask app…). Pure decisions, shared by the run bar and tests.
+ */
+
+// eslint-disable-next-line no-control-regex
+const CONTROL = /[\u0000-\u001f\u007f]/
+
+/** Persisted on a run node as `data.runBrowser`: present = the browser panel is shown. */
+export interface RunBrowserConfig {
+ /** The page shown. Absent until the run prints one (or the person types one). */
+ url?: string
+ /** The URL was picked out of the run's output, so the next run (which may serve on a different
+ * port) looks again rather than keeping a stale one. */
+ auto?: boolean
+}
+
+export function isPreviewUrl(v: unknown): v is string {
+ return typeof v === 'string' && v.length <= 4096 && !CONTROL.test(v) && /^https?:\/\/[^\s]+$/i.test(v)
+}
+
+/** Re-validate a persisted panel (git-shared, hand-editable). Only http(s) pages load in it. */
+export function normalizeRunBrowserConfig(raw: unknown): RunBrowserConfig | undefined {
+ if (!raw || typeof raw !== 'object') return undefined
+ const r = raw as Record<string, unknown>
+ const out: RunBrowserConfig = {}
+ if (isPreviewUrl(r.url)) {
+ out.url = r.url
+ if (r.auto === true) out.auto = true
+ }
+ return out
+}
+
+export type PreviewKind = 'simulator' | 'browser'
+
+export interface PreviewTarget {
+ /** The configuration takes a device (Flutter) and lets the person pick it. */
+ picksDevice: boolean
+ /** The picked device's id and kind, when there is one. */
+ deviceId?: string
+ deviceKind?: string
+ /** The device the configuration names itself (`-d chrome`, `"deviceId": "chrome"`). */
+ pinnedDeviceId?: string
+ /** A `chrome` / `msedge` configuration: it opens a page rather than running a process. */
+ browserConfig: boolean
+}
+
+const IOS_UDID = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/
+
+/** Flutter's browser devices. */
+export function isWebDeviceId(id: string | undefined): boolean {
+ return id === 'chrome' || id === 'edge' || id === 'web-server'
+}
+
+/** Whether a device id names a simulator the simulator panel can show by itself. */
+export function isSimulatorDeviceId(id: string | undefined): boolean {
+ return !!id && (IOS_UDID.test(id) || /^emulator-\d+$/.test(id))
+}
+
+/** Which panel the run calls for (the button offers both; this one is marked and opened on Run). */
+export function previewKindFor(t: PreviewTarget): PreviewKind {
+ if (t.browserConfig) return 'browser'
+ if (t.pinnedDeviceId) return isWebDeviceId(t.pinnedDeviceId) ? 'browser' : 'simulator'
+ if (t.picksDevice) return t.deviceKind === 'web' || isWebDeviceId(t.deviceId) ? 'browser' : 'simulator'
+ // A run with no device at all is most likely a server, whose page is the thing to look at.
+ return 'browser'
+}
+
+const LOCAL_URL = /\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::\d{2,5})?(?:\/[^\s'"<>`)\]]*)?/gi
+/** A line naming where the app is served — preferred over any other URL on screen. */
+const SERVED_LINE = /served at|\blocal:|listening (?:on|at)|running (?:on|at)|available (?:on|at)|ready (?:on|at)|started (?:server )?on|server running/i
+/** URLs that are tools, not the app (Flutter DevTools, the Dart VM service, debugger endpoints). */
+const TOOL_LINE = /devtools|debugger|dart vm|vm service|observatory|inspect|profiler/i
+
+/**
+ * The page a run serves, picked out of its terminal output: the newest local http(s) URL on a line
+ * that says where the app is served, else the newest local URL that is not a tool's. `0.0.0.0` (bound
+ * on every interface) is opened as `localhost`. Null when the output names none yet.
+ */
+export function localUrlFromOutput(text: string): string | null {
+ let served: string | null = null
+ let other: string | null = null
+ for (const line of text.split(/\r?\n/)) {
+ if (TOOL_LINE.test(line)) continue
+ const urls = line.match(LOCAL_URL)
+ if (!urls) continue
+ const url = urls[urls.length - 1].replace(/[.,;:]+$/, '').replace('://0.0.0.0', '://localhost')
+ if (SERVED_LINE.test(line)) served = url
+ else other = url
+ }
+ return served ?? other
+}
diff --git a/src/shared/simulator.test.ts b/src/shared/simulator.test.ts
new file mode 100644
index 000000000..1cabec5a1
--- /dev/null
+++ b/src/shared/simulator.test.ts
@@ -0,0 +1,287 @@
+import { describe, expect, it } from 'vitest'
+import {
+ normalizeInlineSimulatorConfig,
+ touchEdge,
+ TOUCH_EDGE_MARGIN,
+ normalizeDeviceId,
+ simulatorPlatformOf,
+ afterTouch,
+ UNANSWERED_TOUCHES_FOR_HINT,
+ ORIENTATION_DEGREES,
+ ORIENTATION_PURPLE,
+ displayLabel,
+ displayToFramebuffer,
+ draggedSide,
+ fitNodeToScreen,
+ hidUsageForCode,
+ rotateOrientation,
+ type SimulatorOrientation,
+ normalizeSimulatorAction,
+ normalizeSimulatorConfig,
+ normalizeSimulatorInput,
+ pointerToScreenRatio
+} from './simulator'
+
+const UDID = '29AC4878-5509-4AAE-B3D1-AB72177B4549'
+
+describe('normalizeSimulatorConfig', () => {
+ it('keeps a valid udid (upper-cased) and its name', () => {
+ expect(normalizeSimulatorConfig({ udid: UDID.toLowerCase(), name: 'iPhone Duo' })).toEqual({ udid: UDID, name: 'iPhone Duo' })
+ })
+ it('turns anything else into an unconfigured node', () => {
+ expect(normalizeSimulatorConfig({ udid: 'x; rm -rf ~' })).toEqual({})
+ expect(normalizeSimulatorConfig(null)).toEqual({})
+ expect(normalizeSimulatorConfig({ udid: UDID, name: 'a\nb' })).toEqual({ udid: UDID })
+ })
+})
+
+describe('normalizeSimulatorInput', () => {
+ it('rebuilds touches, clamping to the screen', () => {
+ expect(normalizeSimulatorInput({ t: 'down', x: 0.5, y: 1.4, extra: 'x' })).toEqual({ t: 'down', x: 0.5, y: 1 })
+ expect(normalizeSimulatorInput({ t: 'move', x: 'NaN', y: 0 })).toBeNull()
+ })
+ it('accepts only HID usages, known buttons and display indexes', () => {
+ expect(normalizeSimulatorInput({ t: 'key', usage: 4, down: true })).toEqual({ t: 'key', usage: 4, down: true })
+ expect(normalizeSimulatorInput({ t: 'key', usage: 999, down: true })).toBeNull()
+ expect(normalizeSimulatorInput({ t: 'button', name: 'home' })).toEqual({ t: 'button', name: 'home' })
+ expect(normalizeSimulatorInput({ t: 'button', name: 'reboot' })).toBeNull()
+ expect(normalizeSimulatorInput({ t: 'display', index: -1 })).toEqual({ t: 'display', index: -1 })
+ expect(normalizeSimulatorInput({ t: 'shell', cmd: 'x' })).toBeNull()
+ })
+})
+
+describe('pointerToScreenRatio', () => {
+ // A 1000×2000 frame contained in a 400×400 box is drawn 200×400, with 100 px bars left and right.
+ it('maps through the letterbox', () => {
+ expect(pointerToScreenRatio(200, 200, 400, 400, 1000, 2000)).toEqual({ x: 0.5, y: 0.5 })
+ expect(pointerToScreenRatio(100, 0, 400, 400, 1000, 2000)).toEqual({ x: 0, y: 0 })
+ expect(pointerToScreenRatio(300, 400, 400, 400, 1000, 2000)).toEqual({ x: 1, y: 1 })
+ })
+ it('is null in the bars and for an unknown frame', () => {
+ expect(pointerToScreenRatio(50, 200, 400, 400, 1000, 2000)).toBeNull()
+ expect(pointerToScreenRatio(10, 10, 400, 400, 0, 0)).toBeNull()
+ })
+ it('is unit-free, so a zoomed canvas (client pixels on both sides) maps the same', () => {
+ expect(pointerToScreenRatio(400, 400, 800, 800, 1000, 2000)).toEqual({ x: 0.5, y: 0.5 })
+ })
+})
+
+describe('hidUsageForCode', () => {
+ it('maps physical keys to HID keyboard usages', () => {
+ expect(hidUsageForCode('KeyA')).toBe(0x04)
+ expect(hidUsageForCode('KeyZ')).toBe(0x1d)
+ expect(hidUsageForCode('Digit1')).toBe(0x1e)
+ expect(hidUsageForCode('Digit0')).toBe(0x27)
+ expect(hidUsageForCode('Enter')).toBe(0x28)
+ expect(hidUsageForCode('Backspace')).toBe(0x2a)
+ expect(hidUsageForCode('ArrowUp')).toBe(0x52)
+ expect(hidUsageForCode('ShiftLeft')).toBe(0xe1)
+ })
+ it('knows nothing it was not given (including prototype names)', () => {
+ expect(hidUsageForCode('MediaPlayPause')).toBeUndefined()
+ expect(hidUsageForCode('toString')).toBeUndefined()
+ })
+})
+
+describe('displayLabel', () => {
+ const cover = { index: 1, width: 1398, height: 2034, name: 'LCD', screenID: 1 }
+ const inner = { index: 0, width: 2007, height: 2853, name: 'LCD-1', screenID: 3 }
+ it('names a foldable’s screens by size, and a single screen plainly', () => {
+ expect(displayLabel(inner, [inner, cover])).toBe('Inner')
+ expect(displayLabel(cover, [inner, cover])).toBe('Cover')
+ expect(displayLabel(cover, [cover])).toBe('Screen')
+ })
+})
+
+describe('orientation', () => {
+ it('turns a quarter at a time and comes back round', () => {
+ let o: SimulatorOrientation = 'portrait'
+ const seen: SimulatorOrientation[] = []
+ for (let i = 0; i < 4; i++) seen.push((o = rotateOrientation(o, 'left')))
+ expect(seen).toEqual(['landscape-left', 'portrait-upside-down', 'landscape-right', 'portrait'])
+ expect(rotateOrientation('portrait', 'right')).toBe('landscape-right')
+ expect(rotateOrientation(rotateOrientation('landscape-left', 'right'), 'left')).toBe('landscape-left')
+ })
+
+ it('maps a click on the turned picture back to the same framebuffer point the picture was drawn from', () => {
+ // The node draws framebuffer (x,y) at this canvas point (SimulatorNode.paint's transforms).
+ const draw = (x: number, y: number, o: SimulatorOrientation) => {
+ switch (ORIENTATION_DEGREES[o]) {
+ case 90: return { u: 1 - y, v: x }
+ case 180: return { u: 1 - x, v: 1 - y }
+ case 270: return { u: y, v: 1 - x }
+ default: return { u: x, v: y }
+ }
+ }
+ for (const o of ['portrait', 'landscape-left', 'landscape-right', 'portrait-upside-down'] as SimulatorOrientation[]) {
+ for (const [x, y] of [[0, 0], [1, 0], [0.25, 0.75], [0.9, 0.1]]) {
+ const { u, v } = draw(x, y, o)
+ const back = displayToFramebuffer(u, v, o)
+ expect(back.x).toBeCloseTo(x)
+ expect(back.y).toBeCloseTo(y)
+ }
+ }
+ })
+
+ it('turns the picture counter-clockwise for a device turned left (measured: Purple 3 = dock on the left edge)', () => {
+ expect(ORIENTATION_PURPLE['landscape-left']).toBe(3)
+ expect(ORIENTATION_DEGREES['landscape-left']).toBe(270)
+ // The framebuffer's top-left corner ends up bottom-left on screen.
+ expect(displayToFramebuffer(0, 1, 'landscape-left')).toEqual({ x: 0, y: 0 })
+ })
+
+ it('persists a non-portrait orientation and accepts only Purple values 1–4', () => {
+ expect(normalizeSimulatorConfig({ udid: UDID, orientation: 'landscape-left' })).toEqual({ udid: UDID, orientation: 'landscape-left' })
+ expect(normalizeSimulatorConfig({ udid: UDID, orientation: 'sideways' })).toEqual({ udid: UDID })
+ expect(normalizeSimulatorInput({ t: 'orientation', value: 3 })).toEqual({ t: 'orientation', value: 3 })
+ expect(normalizeSimulatorInput({ t: 'orientation', value: 7 })).toBeNull()
+ })
+})
+
+describe('fitNodeToScreen', () => {
+ // An iPhone 17 framebuffer is 1206×2622 (aspect ≈ 0.46); chrome = 2 px border, 70 px header + toolbar.
+ const phone = 1206 / 2622
+ const base = { chromeW: 2, chromeH: 70, minW: 200, minH: 260 }
+
+ it('fits the first frame by the longer side: a default 360×760 node becomes a phone with no bars', () => {
+ const r = fitNodeToScreen({ ...base, screenW: 358, screenH: 690, aspect: phone, by: 'long' })
+ const screenW = r.width - base.chromeW
+ const screenH = r.height - base.chromeH
+ expect(Math.abs(screenH - 690)).toBeLessThanOrEqual(1) // width is rounded first; height follows it
+ expect(Math.abs(screenW / screenH - phone)).toBeLessThan(0.01)
+ })
+
+ it('turns a tall phone into a wide one of the same size on rotation', () => {
+ const r = fitNodeToScreen({ ...base, screenW: 317, screenH: 690, aspect: 1 / phone, by: 'long' })
+ expect(r.width - base.chromeW).toBe(690)
+ expect(Math.abs((r.width - base.chromeW) / (r.height - base.chromeH) - 1 / phone)).toBeLessThan(0.01)
+ })
+
+ it('follows the side that was dragged', () => {
+ const wider = fitNodeToScreen({ ...base, screenW: 500, screenH: 690, aspect: phone, by: 'width' })
+ expect(wider.width - base.chromeW).toBe(500)
+ expect(wider.height - base.chromeH).toBe(Math.round(500 / phone))
+ const taller = fitNodeToScreen({ ...base, screenW: 317, screenH: 900, aspect: phone, by: 'height' })
+ expect(taller.height - base.chromeH).toBeCloseTo(900, -1)
+ })
+
+ it('keeps the screen’s shape when the minimum width clamps', () => {
+ const r = fitNodeToScreen({ ...base, screenW: 50, screenH: 100, aspect: phone, by: 'long' })
+ expect(r.width).toBe(200)
+ expect(Math.abs((r.width - base.chromeW) / (r.height - base.chromeH) - phone)).toBeLessThan(0.01)
+ })
+
+ it('tells which side a hand resize was about', () => {
+ expect(draggedSide({ w: 300, h: 600 }, { w: 450, h: 610 })).toBe('width')
+ expect(draggedSide({ w: 300, h: 600 }, { w: 305, h: 800 })).toBe('height')
+ })
+})
+
+describe('normalizeSimulatorAction', () => {
+ it('accepts each action in its valid form', () => {
+ expect(normalizeSimulatorAction({ a: 'appearance', value: 'dark' })).toEqual({ a: 'appearance', value: 'dark' })
+ expect(normalizeSimulatorAction({ a: 'location-set', lat: 37.33, lon: -122.03 })).toEqual({ a: 'location-set', lat: 37.33, lon: -122.03 })
+ expect(normalizeSimulatorAction({ a: 'status-bar', preset: 'battery', batteryLevel: 20, batteryState: 'discharging' })).toEqual({
+ a: 'status-bar', preset: 'battery', batteryLevel: 20, batteryState: 'discharging'
+ })
+ expect(normalizeSimulatorAction({ a: 'open-url', url: 'myapp://deep/link' })).toEqual({ a: 'open-url', url: 'myapp://deep/link' })
+ expect(normalizeSimulatorAction({ a: 'push', bundleId: 'com.example.app', payload: '{"aps":{"alert":"hi"}}' })).toMatchObject({ a: 'push' })
+ expect(normalizeSimulatorAction({ a: 'privacy', op: 'reset', service: 'all' })).toEqual({ a: 'privacy', op: 'reset', service: 'all' })
+ })
+
+ it('refuses bad values instead of passing them to simctl', () => {
+ expect(normalizeSimulatorAction({ a: 'location-set', lat: 91, lon: 0 })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'status-bar', preset: 'battery', batteryLevel: 150, batteryState: 'charged' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'open-url', url: 'not a url' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'push', bundleId: 'com.example.app', payload: '[1,2]' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'push', bundleId: 'x; rm -rf ~', payload: '{}' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'push', bundleId: 'com.a.b', payload: JSON.stringify({ x: 'y'.repeat(5000) }) })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'privacy', op: 'grant', service: 'all' })).toBeNull() // grant needs an app
+ expect(normalizeSimulatorAction({ a: 'privacy', op: 'grant', service: 'keychain', bundleId: 'com.a.b' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'install', path: 'relative/My.app' })).toBeNull()
+ // Android runs on Windows too: a picked APK there is a drive path. UNC stays refused.
+ expect(normalizeSimulatorAction({ a: 'install', path: 'C:\\Users\\me\\app.apk' })).toEqual({
+ a: 'install',
+ path: 'C:\\Users\\me\\app.apk'
+ })
+ expect(normalizeSimulatorAction({ a: 'add-media', paths: ['D:/pics/a.png', '/tmp/b.png'] })).toEqual({
+ a: 'add-media',
+ paths: ['D:/pics/a.png', '/tmp/b.png']
+ })
+ expect(normalizeSimulatorAction({ a: 'install', path: '\\\\server\\share\\app.apk' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'install', path: 'C:relative.apk' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'add-media', paths: [] })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'erase-everything' })).toBeNull()
+ })
+})
+
+describe('afterTouch', () => {
+ it('shows the hint only after several unanswered touches in a row', () => {
+ let s = { count: 0, hint: false }
+ for (let i = 1; i < UNANSWERED_TOUCHES_FOR_HINT; i++) {
+ s = afterTouch(s.count, false)
+ expect(s.hint).toBe(false)
+ }
+ s = afterTouch(s.count, false)
+ expect(s.hint).toBe(true)
+ })
+ it('an answered touch starts the count again and hides the hint', () => {
+ const s = afterTouch(UNANSWERED_TOUCHES_FOR_HINT + 4, true)
+ expect(s).toEqual({ count: 0, hint: false })
+ expect(afterTouch(s.count, false).hint).toBe(false)
+ })
+})
+
+describe('Android device ids', () => {
+ it('tells the platforms apart and keeps an AVD name as written', () => {
+ expect(simulatorPlatformOf('avd:Pixel_9')).toBe('android')
+ expect(simulatorPlatformOf('0A1B2C3D-0000-4000-8000-00000000000A')).toBe('ios')
+ expect(simulatorPlatformOf('avd:../x')).toBeNull()
+ expect(normalizeDeviceId('avd:Pixel_9')).toBe('avd:Pixel_9')
+ expect(normalizeSimulatorConfig({ udid: 'avd:Pixel_9', name: 'Pixel 9' })).toEqual({ udid: 'avd:Pixel_9', name: 'Pixel 9' })
+ })
+
+ it('validates the clipboard action', () => {
+ expect(normalizeSimulatorAction({ a: 'clipboard-set', text: 'hi' })).toEqual({ a: 'clipboard-set', text: 'hi' })
+ expect(normalizeSimulatorAction({ a: 'clipboard-set', text: 'a\u0000b' })).toBeNull()
+ expect(normalizeSimulatorAction({ a: 'clipboard-set', text: 'x'.repeat(64_001) })).toBeNull()
+ })
+})
+
+describe('touchEdge', () => {
+ it('names the panel edge a touch starts on, by the measured values', () => {
+ expect(touchEdge(0.5, 0.995)).toBe(3) // bottom: the home swipe
+ expect(touchEdge(0.001, 0.5)).toBe(2) // left
+ expect(touchEdge(0.999, 0.5)).toBe(4) // right
+ expect(touchEdge(0.5, 0.001)).toBe(1) // top
+ expect(touchEdge(0.5, 0.5)).toBe(0)
+ expect(touchEdge(0.5, 1 - TOUCH_EDGE_MARGIN - 0.01)).toBe(0)
+ })
+
+ it('picks the nearer edge in a corner', () => {
+ expect(touchEdge(0.02, 0.999)).toBe(3)
+ })
+
+ it('passes a valid edge through input validation and drops anything else', () => {
+ expect(normalizeSimulatorInput({ t: 'down', x: 0.5, y: 1, edge: 3 })).toEqual({ t: 'down', x: 0.5, y: 1, edge: 3 })
+ expect(normalizeSimulatorInput({ t: 'move', x: 0.5, y: 1, edge: 9 })).toEqual({ t: 'move', x: 0.5, y: 1 })
+ expect(normalizeSimulatorInput({ t: 'up', x: 0.5, y: 1, edge: '3' })).toEqual({ t: 'up', x: 0.5, y: 1, edge: 3 })
+ })
+})
+
+describe('inline simulator config', () => {
+ it('keeps the device, and no size of its own (the run node is the size)', () => {
+ expect(normalizeInlineSimulatorConfig({ udid: 'avd:Pixel_9', name: 'Pixel 9', height: 900 })).toEqual({ udid: 'avd:Pixel_9', name: 'Pixel 9' })
+ expect(normalizeInlineSimulatorConfig(null)).toBeUndefined()
+ })
+
+ it('an open panel with no device is still open (an empty object), and never carries a dock link', () => {
+ expect(normalizeInlineSimulatorConfig({})).toEqual({})
+ expect(normalizeInlineSimulatorConfig({ dockTo: 'term-1' })).toEqual({})
+ })
+
+ it('a split-off node keeps a valid link back to its run node', () => {
+ expect(normalizeSimulatorConfig({ dockTo: 'term-abc' })).toEqual({ dockTo: 'term-abc' })
+ expect(normalizeSimulatorConfig({ dockTo: '../x y' })).toEqual({})
+ })
+})
diff --git a/src/shared/simulator.ts b/src/shared/simulator.ts
new file mode 100644
index 000000000..119b2db89
--- /dev/null
+++ b/src/shared/simulator.ts
@@ -0,0 +1,608 @@
+/**
+ * The Simulator node: a live iOS simulator screen on the canvas — touch with the mouse, type with
+ * the keyboard, press home / lock — without DeviceHub. Host side in core/simulator; this module is
+ * the pure half both sides share: the persisted config, input validation, and the two mappings
+ * (pointer → screen ratio, browser key → HID usage).
+ */
+import { SIMULATOR_UDID } from './run-config'
+
+// ── Devices: iOS simulators and Android virtual devices ───────────────────────────────────────
+//
+// One node shows either. An iOS simulator is named by its UDID; an Android virtual device (AVD) by
+// `avd:<name>` — the AVD's name is its stable identity (a running emulator's adb serial changes from
+// run to run). The persisted field keeps its old name, `udid`, so existing nodes load unchanged.
+
+export type SimulatorPlatform = 'ios' | 'android'
+
+/** An AVD's name, as avdmanager allows it. */
+export const ANDROID_AVD_NAME = /^[A-Za-z0-9._-]{1,128}$/
+export const ANDROID_DEVICE_ID = /^avd:[A-Za-z0-9._-]{1,128}$/
+
+export function androidDeviceId(avd: string): string {
+ return `avd:${avd}`
+}
+
+/** The AVD name inside an Android device id, or null for anything else. */
+export function avdNameOf(id: string): string | null {
+ return ANDROID_DEVICE_ID.test(id) ? id.slice(4) : null
+}
+
+/** Which kind of device an id names, or null when it is neither. */
+export function simulatorPlatformOf(id: unknown): SimulatorPlatform | null {
+ if (typeof id !== 'string') return null
+ if (ANDROID_DEVICE_ID.test(id)) return 'android'
+ if (SIMULATOR_UDID.test(id)) return 'ios'
+ return null
+}
+
+/** The canonical form of a device id (UDIDs upper-cased), or null when it is not one. */
+export function normalizeDeviceId(id: unknown): string | null {
+ const p = simulatorPlatformOf(id)
+ if (!p) return null
+ return p === 'ios' ? (id as string).toUpperCase() : (id as string)
+}
+
+export interface SimulatorDevice {
+ id: string
+ name: string
+ platform: SimulatorPlatform
+ /** "iOS 27.1", "API 34". */
+ os?: string
+ state: 'booted' | 'shutdown'
+ /** A running Android device's adb serial (`emulator-5554`) — how Flutter and the run node name it. */
+ serial?: string
+}
+
+export interface SimulatorDevicesResult {
+ devices: SimulatorDevice[]
+ /** Why there are no iOS simulators, when simctl itself could not run (no Xcode selected). */
+ iosError?: string
+ /** Why there are no Android devices, when that is not simply "none installed". */
+ androidError?: string
+}
+
+/** Persisted on a `simulator` node as `data.simulator`. */
+export interface SimulatorNodeConfig {
+ /** The device: an iOS simulator's UDID, or `avd:<name>` for an Android virtual device. Absent
+ * until one is picked. */
+ udid?: string
+ /** Its name when picked, so the node can label it before devices load. */
+ name?: string
+ /** How the device is held. Absent = portrait. */
+ orientation?: SimulatorOrientation
+ /** A Simulator node split off a run node: that run node's id, so it can be docked back in. */
+ dockTo?: string
+}
+
+/**
+ * A simulator shown INSIDE a run node (`data.runSimulator`): present = shown. The device settings
+ * of a Simulator node; its size is the run node's own (the panel fills it), so none is stored.
+ */
+export type InlineSimulatorConfig = Omit<SimulatorNodeConfig, 'dockTo'>
+
+/** How much a run node grows when its simulator opens (it can then be resized like any node). */
+export const INLINE_SIM_HEIGHT = 560
+
+export function normalizeInlineSimulatorConfig(raw: unknown): InlineSimulatorConfig | undefined {
+ if (!raw || typeof raw !== 'object') return undefined
+ const { dockTo: _d, ...out } = normalizeSimulatorConfig(raw)
+ void _d
+ return out
+}
+
+// ── Orientation ────────────────────────────────────────────────────────────────────────────────
+//
+// Rotating a device is two things: the helper tells iOS (a GSEvent to PurpleWorkspacePort), and the
+// node turns the picture — the framebuffer always stays portrait while iOS draws its content rotated
+// inside it, exactly as a real panel does. Touches are then mapped back from the turned picture to
+// framebuffer coordinates. MEASURED (Xcode 27, iPad): Purple value 3 lays the UI out upright for a
+// device turned LEFT (counter-clockwise: dock on the framebuffer's left edge), 4 for one turned right.
+
+export type SimulatorOrientation = 'portrait' | 'landscape-left' | 'landscape-right' | 'portrait-upside-down'
+
+const ORIENTATIONS: readonly SimulatorOrientation[] = ['portrait', 'landscape-left', 'portrait-upside-down', 'landscape-right']
+
+/** The GSEvent orientation value the helper sends for each. */
+export const ORIENTATION_PURPLE: Readonly<Record<SimulatorOrientation, number>> = {
+ portrait: 1,
+ 'portrait-upside-down': 2,
+ 'landscape-left': 3,
+ 'landscape-right': 4
+}
+
+/** How far the picture is turned on screen, clockwise, in degrees. */
+export const ORIENTATION_DEGREES: Readonly<Record<SimulatorOrientation, 0 | 90 | 180 | 270>> = {
+ portrait: 0,
+ 'landscape-right': 90,
+ 'portrait-upside-down': 180,
+ 'landscape-left': 270
+}
+
+export function isSimulatorOrientation(v: unknown): v is SimulatorOrientation {
+ return typeof v === 'string' && (ORIENTATIONS as readonly string[]).includes(v)
+}
+
+/** Turn the device a quarter turn left (counter-clockwise) or right. */
+export function rotateOrientation(o: SimulatorOrientation, dir: 'left' | 'right'): SimulatorOrientation {
+ const i = ORIENTATIONS.indexOf(o)
+ return ORIENTATIONS[(i + (dir === 'left' ? 1 : 3)) % 4]
+}
+
+/** A point on the turned picture (0..1 of what is shown) → the same point in the portrait
+ * framebuffer the digitizer expects. */
+export function displayToFramebuffer(u: number, v: number, o: SimulatorOrientation): { x: number; y: number } {
+ switch (o) {
+ case 'landscape-left': // picture turned 90° counter-clockwise
+ return { x: 1 - v, y: u }
+ case 'landscape-right': // picture turned 90° clockwise
+ return { x: v, y: 1 - u }
+ case 'portrait-upside-down':
+ return { x: 1 - u, y: 1 - v }
+ default:
+ return { x: u, y: v }
+ }
+}
+
+// eslint-disable-next-line no-control-regex
+const CONTROL = /[\u0000-\u001f\u007f]/
+
+/** Re-validate a persisted config (git-shared, hand-editable). Never undefined: a broken value is
+ * an unconfigured node, which asks for a device. */
+export function normalizeSimulatorConfig(raw: unknown): SimulatorNodeConfig {
+ if (!raw || typeof raw !== 'object') return {}
+ const r = raw as Record<string, unknown>
+ const out: SimulatorNodeConfig = {}
+ const id = normalizeDeviceId(r.udid)
+ if (id) {
+ out.udid = id
+ if (typeof r.name === 'string' && r.name.trim() && r.name.length <= 200 && !CONTROL.test(r.name)) out.name = r.name.trim()
+ }
+ if (isSimulatorOrientation(r.orientation) && r.orientation !== 'portrait') out.orientation = r.orientation
+ if (typeof r.dockTo === 'string' && SIMULATOR_NODE_ID.test(r.dockTo)) out.dockTo = r.dockTo
+ return out
+}
+
+/** The simulators a node shows are THIS machine's devices; an SSH project's work runs on another
+ * machine. One sentence for the menus, the Dock and the core's refusal. */
+export const SIMULATOR_SSH_HINT = 'Simulators run on this machine — not in SSH projects yet'
+
+export const SIMULATOR_NODE_ID = /^[A-Za-z0-9._-]{1,128}$/
+
+// ── Input ──────────────────────────────────────────────────────────────────────────────────────
+
+export type SimulatorButton = 'home' | 'lock' | 'side' | 'siri' | 'volup' | 'voldown' | 'playpause' | 'back' | 'recents'
+const BUTTONS: readonly SimulatorButton[] = ['home', 'lock', 'side', 'siri', 'volup', 'voldown', 'playpause', 'back', 'recents']
+
+/**
+ * The panel edge a touch starts on, as the iOS digitizer reports it (Indigo's edge field). iOS
+ * recognises its system edge gestures from this flag, not from where the finger lands: MEASURED
+ * (Xcode 27, iPhone 17 + iPad Pro): a swipe up from the very bottom without the flag only scrolled
+ * the app; with 3 it went home. The values name PHYSICAL edges of the portrait panel — on an iPad
+ * turned left, the home swipe (from the bottom of the turned picture, i.e. the panel's left edge)
+ * was recognised with 2 and not with 1, 3 or 4; turned right, with 4. Top = 1 is inferred.
+ */
+export type TouchEdge = 0 | 1 | 2 | 3 | 4
+/** How close to an edge (as a fraction of that side) a touch must go down to count as from it. */
+export const TOUCH_EDGE_MARGIN = 0.025
+
+/** The edge a touch going down at this PANEL point (0..1 portrait framebuffer) starts on. */
+export function touchEdge(x: number, y: number): TouchEdge {
+ const m = TOUCH_EDGE_MARGIN
+ const candidates: Array<[number, TouchEdge]> = [
+ [y, 1],
+ [x, 2],
+ [1 - y, 3],
+ [1 - x, 4]
+ ]
+ let best: [number, TouchEdge] | null = null
+ for (const c of candidates) if (c[0] <= m && (!best || c[0] < best[0])) best = c
+ return best ? best[1] : 0
+}
+
+/**
+ * An Android emulator's hardware buttons, as the W3C key names its gRPC interface maps to Android
+ * keys. MEASURED (emulator 36.6.11): GoHome, GoBack and AppSwitch each did what the device's own
+ * buttons do. iOS-only buttons have no entry and are refused.
+ */
+export const ANDROID_BUTTON_KEYS: Readonly<Partial<Record<SimulatorButton, string>>> = {
+ home: 'GoHome',
+ back: 'GoBack',
+ recents: 'AppSwitch',
+ lock: 'Power',
+ side: 'Power',
+ volup: 'AudioVolumeUp',
+ voldown: 'AudioVolumeDown',
+ playpause: 'MediaPlayPause'
+}
+
+/**
+ * How far an Android emulator is turned for each orientation (the `orientation` input's value is
+ * the iOS GSEvent number, shared by both platforms). MEASURED: z = 90 turns the device left — the
+ * frames then arrive already turned, camera on the left — while touches stay in portrait panel
+ * coordinates, so the node maps them exactly as it does for iOS.
+ */
+export const ANDROID_ROTATION_Z: Readonly<Record<number, number>> = { 1: 0, 2: 180, 3: 90, 4: -90 }
+
+/** Whether a platform sends its frames already turned (Android) or always portrait (iOS, where the
+ * node turns the picture itself). */
+export function picturePreRotated(p: SimulatorPlatform): boolean {
+ return p === 'android'
+}
+
+export type SimulatorInput =
+ /** `edge`: the panel edge the contact started on (see touchEdge); 0 / absent = none. */
+ | { t: 'down' | 'move' | 'up'; x: number; y: number; edge?: TouchEdge }
+ | { t: 'key'; usage: number; down: boolean }
+ | { t: 'button'; name: SimulatorButton }
+ | { t: 'display'; index: number }
+ | { t: 'orientation'; value: number }
+
+/** The only commands that reach the helper, re-built field by field (renderer input is untrusted
+ * in the Server Edition and the relay; the helper also clamps). */
+export function normalizeSimulatorInput(raw: unknown): SimulatorInput | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ switch (r.t) {
+ case 'down':
+ case 'move':
+ case 'up': {
+ const x = Number(r.x)
+ const y = Number(r.y)
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null
+ const out: SimulatorInput = { t: r.t, x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) }
+ const edge = Number(r.edge)
+ if (Number.isInteger(edge) && edge >= 1 && edge <= 4) out.edge = edge as TouchEdge
+ return out
+ }
+ case 'key': {
+ const usage = Number(r.usage)
+ if (!Number.isInteger(usage) || usage < 0 || usage > 255 || typeof r.down !== 'boolean') return null
+ return { t: 'key', usage, down: r.down }
+ }
+ case 'button':
+ return BUTTONS.includes(r.name as SimulatorButton) ? { t: 'button', name: r.name as SimulatorButton } : null
+ case 'orientation': {
+ const value = Number(r.value)
+ return Number.isInteger(value) && value >= 1 && value <= 4 ? { t: 'orientation', value } : null
+ }
+ case 'display': {
+ const index = Number(r.index)
+ return Number.isInteger(index) && index >= -1 && index < 16 ? { t: 'display', index } : null
+ }
+ default:
+ return null
+ }
+}
+
+/**
+ * Where a pointer landed on the device screen, as a 0..1 ratio — or null when it is in the
+ * letterbox around it. The frame is drawn `object-fit: contain` inside a box of `boxW × boxH`, so
+ * the picture is centred with bars on two sides; offsets are measured from the box's top-left.
+ */
+export function pointerToScreenRatio(
+ offsetX: number,
+ offsetY: number,
+ boxW: number,
+ boxH: number,
+ frameW: number,
+ frameH: number
+): { x: number; y: number } | null {
+ if (boxW <= 0 || boxH <= 0 || frameW <= 0 || frameH <= 0) return null
+ const scale = Math.min(boxW / frameW, boxH / frameH)
+ const drawnW = frameW * scale
+ const drawnH = frameH * scale
+ const left = (boxW - drawnW) / 2
+ const top = (boxH - drawnH) / 2
+ const x = (offsetX - left) / drawnW
+ const y = (offsetY - top) / drawnH
+ if (x < 0 || x > 1 || y < 0 || y > 1) return null
+ return { x, y }
+}
+
+/**
+ * Browser `KeyboardEvent.code` → USB HID keyboard usage (page 0x07), the codes the simulator's
+ * keyboard service takes. Physical-key codes, not characters: the device applies its own layout
+ * and Shift, exactly as a hardware keyboard attached to an iPhone does.
+ */
+export const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = (() => {
+ const m: Record<string, number> = {}
+ for (let i = 0; i < 26; i++) m[`Key${String.fromCharCode(65 + i)}`] = 0x04 + i
+ for (let i = 1; i <= 9; i++) m[`Digit${i}`] = 0x1e + (i - 1)
+ m.Digit0 = 0x27
+ Object.assign(m, {
+ Enter: 0x28, NumpadEnter: 0x58, Escape: 0x29, Backspace: 0x2a, Tab: 0x2b, Space: 0x2c,
+ Minus: 0x2d, Equal: 0x2e, BracketLeft: 0x2f, BracketRight: 0x30, Backslash: 0x31,
+ Semicolon: 0x33, Quote: 0x34, Backquote: 0x35, Comma: 0x36, Period: 0x37, Slash: 0x38,
+ CapsLock: 0x39, Delete: 0x4c, Home: 0x4a, End: 0x4d, PageUp: 0x4b, PageDown: 0x4e,
+ ArrowRight: 0x4f, ArrowLeft: 0x50, ArrowDown: 0x51, ArrowUp: 0x52,
+ ControlLeft: 0xe0, ShiftLeft: 0xe1, AltLeft: 0xe2, MetaLeft: 0xe3,
+ ControlRight: 0xe4, ShiftRight: 0xe5, AltRight: 0xe6, MetaRight: 0xe7
+ })
+ for (let i = 1; i <= 12; i++) m[`F${i}`] = 0x3a + (i - 1)
+ return m
+})()
+
+export function hidUsageForCode(code: string): number | undefined {
+ return Object.prototype.hasOwnProperty.call(HID_USAGE_BY_CODE, code) ? HID_USAGE_BY_CODE[code] : undefined
+}
+
+// ── Host API ───────────────────────────────────────────────────────────────────────────────────
+
+export interface SimulatorDisplayInfo {
+ index: number
+ width: number
+ height: number
+ /** The device's own name for it: "LCD" (cover / only screen), "LCD-1" (a foldable's inner). */
+ name: string
+ /** simctl's screen id for it (`simctl io --display=<id>`), 0 when unknown. */
+ screenID: number
+ /** Device pixels per point, when known (an Android AVD's density / 160). */
+ scale?: number
+}
+
+export type SimulatorStatusEvent =
+ | { kind: 'ready' }
+ | { kind: 'displays'; displays: SimulatorDisplayInfo[]; active: number; pinned: boolean }
+ | { kind: 'error'; code: string; message: string }
+ | { kind: 'exited'; code: number | null; signal: string | null }
+
+export interface SimulatorFrame {
+ width: number
+ height: number
+ display: number
+ /** The encoded picture (JPEG from the iOS helper, PNG from an Android emulator — see `mime`). */
+ jpeg: Uint8Array
+ /** Absent = JPEG. */
+ mime?: 'image/png'
+}
+
+export type SimulatorStartResult = { ok: true } | { ok: false; error: string }
+
+export interface SimulatorApi {
+ /** Every iOS simulator and Android virtual device installed on this machine. */
+ devices(refresh?: boolean): Promise<SimulatorDevicesResult>
+ /** Boot a device (an Android one headless: the node is its screen). */
+ boot(id: string): Promise<{ ok: true } | { ok: false; error: string }>
+ /** Start streaming `udid` into this node (compiles the helper on first use). */
+ start(nodeId: string, udid: string): Promise<SimulatorStartResult>
+ stop(nodeId: string): Promise<void>
+ /** Touch / key / button / display — validated again on the host. */
+ input(nodeId: string, cmd: SimulatorInput): Promise<boolean>
+ shutdown(udid: string): Promise<boolean>
+ /** The ⋯ menu's device actions (simctl / simulator notifications). */
+ action(udid: string, action: SimulatorAction): Promise<SimulatorActionResult>
+ /** Settings the menu marks with ✓, and the location scenarios. */
+ state(udid: string): Promise<SimulatorDeviceState>
+ /** A full-resolution screenshot of a screen, to the Desktop, the clipboard, or for the canvas. */
+ screenshot(udid: string, screenID: number, target: SimulatorCaptureTarget, name: string): Promise<SimulatorActionResult & { path?: string }>
+ startRecording(udid: string, screenID: number, name: string): Promise<SimulatorActionResult>
+ stopRecording(udid: string): Promise<SimulatorActionResult & { path?: string }>
+ isRecording(udid: string): Promise<boolean>
+ onFrame(nodeId: string, listener: (frame: SimulatorFrame) => void): () => void
+ onStatus(nodeId: string, listener: (event: SimulatorStatusEvent) => void): () => void
+}
+
+/** A friendlier label for a display than the device's own ("LCD-1"). */
+export function displayLabel(d: SimulatorDisplayInfo, all: readonly SimulatorDisplayInfo[]): string {
+ if (all.length < 2) return 'Screen'
+ // A foldable: the larger screen is the inner one.
+ const largest = all.reduce((a, b) => (a.width * a.height >= b.width * b.height ? a : b))
+ return d.index === largest.index ? 'Inner' : 'Cover'
+}
+
+// ── Fitting the node to the screen ─────────────────────────────────────────────────────────────
+
+export interface FitInput {
+ /** The screen area's current size (layout px) and the node's chrome around it. */
+ screenW: number
+ screenH: number
+ chromeW: number
+ chromeH: number
+ /** The picture's width / height, as shown (after rotation). */
+ aspect: number
+ /** Which side keeps its length: the longer one (a shape change — rotation, first frame), or the
+ * side the user just dragged (a hand resize). */
+ by: 'long' | 'width' | 'height'
+ minW: number
+ minH: number
+}
+
+/** The node size whose screen area has exactly the picture's shape — no letterbox bars. */
+export function fitNodeToScreen(f: FitInput): { width: number; height: number } {
+ const long = Math.max(f.screenW, f.screenH)
+ const screenW =
+ f.by === 'width'
+ ? f.screenW
+ : f.by === 'height'
+ ? f.screenH * f.aspect
+ : f.aspect >= 1
+ ? long
+ : long * f.aspect
+ const width = Math.max(f.minW, Math.round(screenW + f.chromeW))
+ // A width clamped up to the minimum still gets a screen of the right shape.
+ const height = Math.max(f.minH, Math.round((width - f.chromeW) / f.aspect + f.chromeH))
+ return { width, height }
+}
+
+/** Which side a hand resize was about: the one that changed more, relative to where it started. */
+export function draggedSide(before: { w: number; h: number }, after: { w: number; h: number }): 'width' | 'height' {
+ const dw = Math.abs(after.w - before.w) / Math.max(1, before.w)
+ const dh = Math.abs(after.h - before.h) / Math.max(1, before.h)
+ return dw >= dh ? 'width' : 'height'
+}
+
+// ── The ⋯ menu: device actions ─────────────────────────────────────────────────────────────────
+
+export type ContentSizeStep = 'increment' | 'decrement'
+export type BatteryState = 'charging' | 'charged' | 'discharging'
+export type PrivacyService =
+ | 'all' | 'calendar' | 'contacts-limited' | 'contacts' | 'location' | 'location-always' | 'photos-add'
+ | 'photos' | 'media-library' | 'microphone' | 'motion' | 'reminders' | 'siri'
+const PRIVACY_SERVICES: readonly PrivacyService[] = [
+ 'all', 'calendar', 'contacts-limited', 'contacts', 'location', 'location-always', 'photos-add',
+ 'photos', 'media-library', 'microphone', 'motion', 'reminders', 'siri'
+]
+
+export type SimulatorAction =
+ | { a: 'appearance'; value: 'light' | 'dark' }
+ | { a: 'content-size'; value: ContentSizeStep }
+ | { a: 'increase-contrast'; value: boolean }
+ | { a: 'location-set'; lat: number; lon: number }
+ | { a: 'location-run'; scenario: string }
+ | { a: 'location-clear' }
+ | { a: 'status-bar'; preset: 'clean' | 'clear' }
+ | { a: 'status-bar'; preset: 'battery'; batteryLevel: number; batteryState: BatteryState }
+ | { a: 'shake' }
+ | { a: 'biometric'; kind: 'face' | 'touch'; op: 'enroll' | 'unenroll' | 'match' | 'nomatch' }
+ | { a: 'open-url'; url: string }
+ | { a: 'push'; bundleId: string; payload: string }
+ | { a: 'privacy'; op: 'grant' | 'revoke' | 'reset'; service: PrivacyService; bundleId?: string }
+ | { a: 'pasteboard'; dir: 'to-device' | 'to-mac' }
+ /** Android: set the device clipboard to this text (⌘V then presses Ctrl+V there). */
+ | { a: 'clipboard-set'; text: string }
+ | { a: 'install'; path: string }
+ | { a: 'add-media'; paths: string[] }
+ | { a: 'restart' }
+ | { a: 'erase' }
+ | { a: 'open-devicehub' }
+
+/** `text` is the device clipboard, for the Android "copy the device clipboard" action (core has no
+ * clipboard of its own, so the renderer writes it). */
+export type SimulatorActionResult = { ok: true; message?: string; text?: string } | { ok: false; error: string }
+
+/** Longest text the clipboard action carries (the same bound the relay uses for a paste). */
+export const MAX_CLIPBOARD_TEXT = 64_000
+export type SimulatorCaptureTarget = 'desktop' | 'clipboard' | 'canvas'
+
+/** What the menu shows a ✓ for, and the location scenarios to offer. Parts that could not be read
+ * are absent — never guessed. */
+export interface SimulatorDeviceState {
+ appearance?: 'light' | 'dark'
+ increaseContrast?: boolean
+ contentSize?: string
+ locationScenarios?: string[]
+}
+
+/** A bundle identifier: reverse-DNS, letters/digits/hyphen/dot. */
+export const BUNDLE_ID = /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/
+const MAX_PUSH_BYTES = 4096 // APNs' own payload limit
+
+/** An absolute path on the machine running the devices: POSIX (`/…`) or a Windows drive path
+ * (`C:\…`, `C:/…`) — Android emulators run on every desktop OS, so an APK or media path picked
+ * on Windows is a drive path. UNC (`\\server\share`) is refused, as file links refuse it. */
+function absPath(v: unknown): v is string {
+ if (typeof v !== 'string' || v.length >= 4096 || CONTROL.test(v)) return false
+ return v.startsWith('/') || /^[A-Za-z]:[\\/]/.test(v)
+}
+
+/** The only actions that reach `simctl`, rebuilt field by field. */
+export function normalizeSimulatorAction(raw: unknown): SimulatorAction | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ switch (r.a) {
+ case 'appearance':
+ return r.value === 'light' || r.value === 'dark' ? { a: 'appearance', value: r.value } : null
+ case 'content-size':
+ return r.value === 'increment' || r.value === 'decrement' ? { a: 'content-size', value: r.value } : null
+ case 'increase-contrast':
+ return typeof r.value === 'boolean' ? { a: 'increase-contrast', value: r.value } : null
+ case 'location-set': {
+ const lat = Number(r.lat)
+ const lon = Number(r.lon)
+ return Number.isFinite(lat) && Number.isFinite(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180
+ ? { a: 'location-set', lat, lon }
+ : null
+ }
+ case 'location-run':
+ return typeof r.scenario === 'string' && r.scenario.trim() && r.scenario.length <= 100 && !CONTROL.test(r.scenario)
+ ? { a: 'location-run', scenario: r.scenario.trim() }
+ : null
+ case 'location-clear':
+ return { a: 'location-clear' }
+ case 'status-bar':
+ if (r.preset === 'clean' || r.preset === 'clear') return { a: 'status-bar', preset: r.preset }
+ if (r.preset === 'battery') {
+ const level = Number(r.batteryLevel)
+ const state = r.batteryState
+ if (!Number.isInteger(level) || level < 0 || level > 100) return null
+ if (state !== 'charging' && state !== 'charged' && state !== 'discharging') return null
+ return { a: 'status-bar', preset: 'battery', batteryLevel: level, batteryState: state }
+ }
+ return null
+ case 'shake':
+ return { a: 'shake' }
+ case 'biometric':
+ return (r.kind === 'face' || r.kind === 'touch') && (r.op === 'enroll' || r.op === 'unenroll' || r.op === 'match' || r.op === 'nomatch')
+ ? { a: 'biometric', kind: r.kind, op: r.op }
+ : null
+ case 'open-url': {
+ if (typeof r.url !== 'string' || r.url.length > 4096 || CONTROL.test(r.url)) return null
+ // Any scheme an app might register (deep links), but it must BE a URL with a scheme.
+ return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(r.url.trim()) ? { a: 'open-url', url: r.url.trim() } : null
+ }
+ case 'push': {
+ if (typeof r.bundleId !== 'string' || !BUNDLE_ID.test(r.bundleId) || typeof r.payload !== 'string') return null
+ if (new TextEncoder().encode(r.payload).length > MAX_PUSH_BYTES) return null
+ try {
+ const doc = JSON.parse(r.payload) as unknown
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return null
+ } catch {
+ return null
+ }
+ return { a: 'push', bundleId: r.bundleId, payload: r.payload }
+ }
+ case 'privacy': {
+ if (r.op !== 'grant' && r.op !== 'revoke' && r.op !== 'reset') return null
+ if (!PRIVACY_SERVICES.includes(r.service as PrivacyService)) return null
+ if (r.bundleId !== undefined && (typeof r.bundleId !== 'string' || !BUNDLE_ID.test(r.bundleId))) return null
+ // grant/revoke need an app; reset may be device-wide.
+ if (r.op !== 'reset' && r.bundleId === undefined) return null
+ return { a: 'privacy', op: r.op, service: r.service as PrivacyService, ...(r.bundleId ? { bundleId: r.bundleId as string } : {}) }
+ }
+ case 'pasteboard':
+ return r.dir === 'to-device' || r.dir === 'to-mac' ? { a: 'pasteboard', dir: r.dir } : null
+ case 'clipboard-set':
+ // NUL is the one character a clipboard string cannot carry to the device.
+ return typeof r.text === 'string' && r.text.length <= MAX_CLIPBOARD_TEXT && !r.text.includes('\u0000')
+ ? { a: 'clipboard-set', text: r.text }
+ : null
+ case 'install':
+ return absPath(r.path) ? { a: 'install', path: r.path } : null
+ case 'add-media':
+ return Array.isArray(r.paths) && r.paths.length > 0 && r.paths.length <= 50 && r.paths.every(absPath)
+ ? { a: 'add-media', paths: r.paths as string[] }
+ : null
+ case 'restart':
+ return { a: 'restart' }
+ case 'erase':
+ return { a: 'erase' }
+ case 'open-devicehub':
+ return { a: 'open-devicehub' }
+ default:
+ return null
+ }
+}
+
+// ── "Is anyone getting my touches?" ─────────────────────────────────────────────────────────────
+//
+// A device takes input from its FIRST HID client only (measured on Xcode 27): while DeviceHub shows
+// a device, our touches are dropped without an error, and the node keeps streaming frames, so it
+// looks alive and ignores the user. Nothing reports the drop, so the node watches for its symptom:
+// the helper sends a frame only when the screen changed, so a touch followed by no frame at all
+// changed nothing. One such touch proves little (a tap on an inert spot changes nothing either), so
+// the hint waits for several in a row, and any touch that IS answered starts the count again.
+
+/** How long after a touch lifts the screen gets to change before the touch counts as unanswered. */
+export const TOUCH_ANSWER_MS = 1500
+/** Unanswered touches in a row before the node says something may be holding the input. */
+export const UNANSWERED_TOUCHES_FOR_HINT = 3
+
+export const INPUT_HELD_HINT =
+ 'Touches are not changing the screen. If DeviceHub is showing this simulator, it keeps the touch input: pick another device in DeviceHub or quit it.'
+
+/** The count after one more touch, and whether the hint should now show. */
+export function afterTouch(count: number, answered: boolean): { count: number; hint: boolean } {
+ if (answered) return { count: 0, hint: false }
+ const next = count + 1
+ return { count: next, hint: next >= UNANSWERED_TOUCHES_FOR_HINT }
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 183742193..c4f26f4d1 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -431,7 +431,7 @@ export interface RecycledInfo {
// 'subagent' and 'loop' are render-only (ephemeral hook-driven viz) and never persisted.
// 'trigger' is a first-class PERSISTED kind (issue #493) — the canvas-owned schedule node; its
// spec rides `CanvasNodeState.trigger` and is sanitized on every load path (@shared/trigger).
-export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'video' | 'web' | 'browser' | 'files' | 'subagent' | 'loop' | 'dino' | 'trigger'
+export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'video' | 'web' | 'browser' | 'files' | 'subagent' | 'loop' | 'dino' | 'trigger' | 'simulator'
/** Persisted state of a single canvas node (terminal, sticky note, group frame, or editor). */
/**
@@ -602,6 +602,10 @@ export interface CanvasNodeState {
* `normalizeRunConfig` (@shared/run-config) on every load AND save.
*/
runConfig?: import('./run-config').RunNodeConfig
+ /** Run nodes: a simulator shown inside the node. Read through `normalizeInlineSimulatorConfig`. */
+ runSimulator?: import('./simulator').InlineSimulatorConfig
+ /** simulator-only: which iOS simulator the node shows. Read through `normalizeSimulatorConfig`. */
+ simulator?: import('./simulator').SimulatorNodeConfig
// sticky-only
text?: string
/**
@@ -630,6 +634,10 @@ export interface CanvasNodeState {
* through untouched on Server Edition / mobile, where a browser node renders with no <webview>.
*/
partition?: string
+ /** browser-only: popped out of a run node's browser panel — that run node's id. */
+ dockTo?: string
+ /** Run nodes: the browser panel inside the node. Read through `normalizeRunBrowserConfig`. */
+ runBrowser?: import('./run-preview').RunBrowserConfig
/** diff-only: true = staged diff (HEAD vs index), false = unstaged (index vs working). */
diffStaged?: boolean
/** diff-only: when set, the diff shows parent (<oid>^) vs commit (<oid>) for a file from history. */
@@ -4428,6 +4436,8 @@ export interface NodeTerminalApi {
wallpaper: import('./wallpaper').WallpaperApi
/** Run node host side (launch.json, devices, launcher, status, stop, signals, reload on save). */
runConfig: import('./run-config').RunConfigApi
+ /** Simulator node host side (macOS desktop): live iOS simulator screen + input. */
+ simulator: import('./simulator').SimulatorApi
triggers: TriggersApi
context: ContextApi
canvas: CanvasApi