simcast-host 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,166 @@
1
+ // agent-status.json: what the running agent tells `simcast-host status`,
2
+ // `serve` and the checks (pid, port, version, busy, ...). Only the agent writes it.
3
+ import fs from 'node:fs';
4
+ import http from 'node:http';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { DEFAULT_PORT, VERSION } from '../common.js';
8
+ import { HOST_NAMES, STATUS_FILE } from './paths.js';
9
+ import { readAgentConfigSafe } from './state.js';
10
+
11
+ // Writes are batched: the first writeStatus() after a flush schedules one write
12
+ // this many ms later, and later patches join it (so a busy agent writes at most
13
+ // ~5 times a second, and a patch is on disk within this delay).
14
+ export const STATUS_DEBOUNCE_MS = 200;
15
+
16
+ let current = null; // what this process last wrote or will write; null = not loaded yet
17
+ let timer = null;
18
+ let exitHooked = false;
19
+
20
+ export function readStatus() {
21
+ try {
22
+ const s = JSON.parse(fs.readFileSync(STATUS_FILE, 'utf8'));
23
+ return s && typeof s === 'object' ? s : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ // Shallow merge into the status (the file's contents on first use in this
30
+ // process, so `serve` starts with { replace: true }).
31
+ // { now: true } writes at once, for changes a reader must not miss (busy, which
32
+ // `clean` checks before deleting builds). { replace: true } drops what was there
33
+ // (a fresh `serve` replacing a dead agent's file without deleting it first).
34
+ export function writeStatus(patch = {}, { now = false, replace = false } = {}) {
35
+ if (replace) current = {};
36
+ else if (!current) current = readStatus() || {};
37
+ Object.assign(current, patch);
38
+ if (!exitHooked) {
39
+ exitHooked = true;
40
+ process.once('exit', flushStatus);
41
+ }
42
+ if (!timer) {
43
+ timer = setTimeout(flushStatus, STATUS_DEBOUNCE_MS);
44
+ timer.unref();
45
+ }
46
+ if (now) flushStatus();
47
+ }
48
+
49
+ // Writes any pending patch now. Synchronous, so it is safe in an exit handler.
50
+ // A failed write is retried (Windows refuses the rename while another process
51
+ // has the file open for reading), so a status change is never lost; the error is
52
+ // logged once a write has failed STATUS_RETRIES times in a row.
53
+ const STATUS_RETRIES = 20;
54
+ const STATUS_RETRY_MS = 50;
55
+ let failures = 0;
56
+ export function flushStatus() {
57
+ if (!timer) return;
58
+ clearTimeout(timer);
59
+ timer = null;
60
+ try {
61
+ fs.mkdirSync(path.dirname(STATUS_FILE), { recursive: true });
62
+ // Readers never see half a file: write a temp file, then rename over.
63
+ const tmp = `${STATUS_FILE}.${process.pid}.tmp`;
64
+ fs.writeFileSync(tmp, JSON.stringify(current, null, 2));
65
+ fs.renameSync(tmp, STATUS_FILE);
66
+ failures = 0;
67
+ } catch (err) {
68
+ failures += 1;
69
+ if (failures === STATUS_RETRIES) console.error(`Could not write ${STATUS_FILE}: ${err.message}`);
70
+ if (failures < STATUS_RETRIES * 10) {
71
+ timer = setTimeout(flushStatus, STATUS_RETRY_MS);
72
+ timer.unref();
73
+ }
74
+ }
75
+ }
76
+
77
+ // Drops pending writes and deletes the file (agent shutdown).
78
+ export function clearStatus() {
79
+ if (timer) clearTimeout(timer);
80
+ timer = null;
81
+ current = {};
82
+ fs.rmSync(STATUS_FILE, { force: true });
83
+ }
84
+
85
+ // Signal 0 only checks the pid. EPERM means it exists but belongs to someone else.
86
+ export function pidAlive(pid) {
87
+ if (!Number.isInteger(pid) || pid <= 0) return false;
88
+ try {
89
+ process.kill(pid, 0);
90
+ return true;
91
+ } catch (err) {
92
+ return err.code === 'EPERM';
93
+ }
94
+ }
95
+
96
+ const validPort = (value) => {
97
+ if (value === null || value === undefined || value === '') return null;
98
+ const port = Number(value);
99
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;
100
+ };
101
+
102
+ // The port the agent listens on: the running agent's (live pid), then a valid
103
+ // SIMCAST_PORT, then agent.json's, then the default. Invalid values are skipped.
104
+ export function agentPort(status = readStatus()) {
105
+ const candidates = [status && pidAlive(status.pid) ? status.port : null, process.env.SIMCAST_PORT, readAgentConfigSafe().port];
106
+ for (const value of candidates) {
107
+ const port = validPort(value);
108
+ if (port) return port;
109
+ }
110
+ return DEFAULT_PORT;
111
+ }
112
+
113
+ // GET /health on this Mac. Resolves { ...body, status } for any HTTP answer (no
114
+ // body fields when it isn't JSON), or null when nothing answers in time.
115
+ // isAgentHealth() tells a simcast agent from another program on the port.
116
+ export function agentHealth(port = agentPort(), timeoutMs = 1500) {
117
+ return new Promise((resolve) => {
118
+ const req = http.get({ host: '127.0.0.1', port, path: '/health', timeout: timeoutMs }, (res) => {
119
+ const chunks = [];
120
+ res.on('data', (c) => chunks.push(c));
121
+ res.on('end', () => {
122
+ let body = {};
123
+ try {
124
+ const parsed = JSON.parse(Buffer.concat(chunks).toString());
125
+ if (parsed && typeof parsed === 'object') body = parsed;
126
+ } catch { /* not JSON, so not our agent */ }
127
+ resolve({ ...body, status: res.statusCode });
128
+ });
129
+ res.on('error', () => resolve(null));
130
+ });
131
+ req.on('timeout', () => req.destroy());
132
+ req.on('error', () => resolve(null));
133
+ });
134
+ }
135
+
136
+ export const isAgentHealth = (h) => h?.status === 200 && HOST_NAMES.includes(h.name);
137
+
138
+ // The version installed on disk now: package.json next to the running bin
139
+ // (process.argv[1], as launchd gave it), else next to this module. Read each call; null when unreadable.
140
+ export function installedVersion() {
141
+ const fromBin = process.argv[1] && /bin[\\/]simcast-host\.js$/.test(process.argv[1]) ? path.resolve(path.dirname(process.argv[1]), '..') : null;
142
+ const root = fromBin || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
143
+ try {
144
+ return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version || null;
145
+ } catch {
146
+ return null; // mid-upgrade: try again next time
147
+ }
148
+ }
149
+
150
+ // After `npm i -g simcast-host@latest` the running agent is
151
+ // old. Every intervalMs, once the installed version differs and the agent is
152
+ // idle, it logs and exits 0; the LaunchAgent (KeepAlive) starts the new one.
153
+ export function watchForUpgrade({ isBusy, exit, intervalMs = 60000 }) {
154
+ // What was installed at start, so a package.json that disagrees with VERSION
155
+ // can't restart the agent every minute.
156
+ const started = installedVersion() || VERSION;
157
+ const timer = setInterval(() => {
158
+ const v = installedVersion();
159
+ if (!v || v === started || isBusy()) return;
160
+ clearInterval(timer);
161
+ console.log(`upgraded to ${v}, restarting`);
162
+ exit(0);
163
+ }, intervalMs);
164
+ timer.unref();
165
+ return () => clearInterval(timer);
166
+ }
@@ -0,0 +1,285 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { run } from './exec.js';
5
+ import * as live from './live.js';
6
+
7
+ // The fallback view (GET /stream, POST /input), for when the window can't use
8
+ // /live: simctl screenshots of the simulator's own display (not the Mac's
9
+ // screen), shared by every viewer of that device, at a few frames per second.
10
+ // Its input goes through idb_companion's HID service, as /live's does.
11
+
12
+ // ---- JPEG helpers ----------------------------------------------------------
13
+
14
+ // Finds where the JPEG starting at `start` ends, by walking its structure.
15
+ // A plain search for the first FF D9 marker isn't enough: frames can carry an
16
+ // embedded thumbnail (EXIF) with its own end marker.
17
+ // Returns the end offset, -1 if more data is needed, or -2 if it's not valid.
18
+ export function findJpegEnd(buf, start) {
19
+ let i = start + 2;
20
+ while (true) {
21
+ if (i + 1 >= buf.length) return -1;
22
+ if (buf[i] !== 0xff) return -2;
23
+ let m = buf[i + 1];
24
+ if (m === 0xff) { i++; continue; } // fill byte
25
+ if (m === 0xd9) return i + 2; // end of image
26
+ if ((m >= 0xd0 && m <= 0xd7) || m === 0x01) { i += 2; continue; } // no length
27
+ if (i + 3 >= buf.length) return -1;
28
+ const len = (buf[i + 2] << 8) | buf[i + 3];
29
+ if (len < 2) return -2;
30
+ if (m !== 0xda) { i += 2 + len; continue; } // skip the whole segment, thumbnails included
31
+ // Start of scan: compressed data runs until the next real marker.
32
+ let j = i + 2 + len;
33
+ while (true) {
34
+ j = buf.indexOf(0xff, j);
35
+ if (j < 0 || j + 1 >= buf.length) return -1;
36
+ m = buf[j + 1];
37
+ if (m === 0x00 || (m >= 0xd0 && m <= 0xd7)) { j += 2; continue; } // stuffed byte or restart
38
+ if (m === 0xff) { j++; continue; }
39
+ break;
40
+ }
41
+ i = j; // EOI, or another segment in progressive JPEGs
42
+ }
43
+ }
44
+
45
+ const SOI = Buffer.from([0xff, 0xd8, 0xff]);
46
+
47
+ // Splits a byte stream (raw JPEGs or an MJPEG/multipart stream) into whole images.
48
+ export class JpegSplitter {
49
+ constructor(onFrame) {
50
+ this.onFrame = onFrame;
51
+ this.buf = Buffer.alloc(0);
52
+ }
53
+
54
+ push(chunk) {
55
+ this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
56
+ while (true) {
57
+ const start = this.buf.indexOf(SOI);
58
+ if (start < 0) {
59
+ this.buf = this.buf.subarray(Math.max(0, this.buf.length - 2));
60
+ return;
61
+ }
62
+ const end = findJpegEnd(this.buf, start);
63
+ if (end === -1) {
64
+ if (start > 0) this.buf = this.buf.subarray(start);
65
+ if (this.buf.length > 32 * 1024 * 1024) this.buf = Buffer.alloc(0); // corrupt stream guard
66
+ return;
67
+ }
68
+ if (end === -2) { // not a real image start; look further on
69
+ this.buf = this.buf.subarray(start + 2);
70
+ continue;
71
+ }
72
+ this.onFrame(Buffer.from(this.buf.subarray(start, end)));
73
+ this.buf = this.buf.subarray(end);
74
+ }
75
+ }
76
+ }
77
+
78
+ export function jpegSize(buf) {
79
+ let i = 2;
80
+ while (i + 9 < buf.length) {
81
+ if (buf[i] !== 0xff) { i++; continue; }
82
+ const marker = buf[i + 1];
83
+ const len = buf.readUInt16BE(i + 2);
84
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
85
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
86
+ }
87
+ i += 2 + len;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ const log = (msg) => console.log(`[${new Date().toISOString()}] ${msg}`);
93
+
94
+ // ---- frame hub -------------------------------------------------------------
95
+
96
+ const hubs = new Map(); // udid -> hub
97
+
98
+ function startProducer(hub) {
99
+ const { udid } = hub;
100
+ const emit = (frame) => {
101
+ hub.last = frame;
102
+ hub.size = jpegSize(frame) || hub.size;
103
+ hub.frames++;
104
+ for (const client of hub.clients) client(frame);
105
+ };
106
+
107
+ log(`stream ${udid}: using simctl screenshots`);
108
+
109
+ // simctl screenshots in a loop.
110
+ const file = path.join(os.tmpdir(), `simcast-live-${udid}.jpg`);
111
+ const loop = async () => {
112
+ hub.child = { kill() {} }; // placeholder so subscribe() doesn't start a second loop
113
+ while (hub.clients.size && !hub.stopped) {
114
+ const t0 = Date.now();
115
+ const r = await run('xcrun', ['simctl', 'io', udid, 'screenshot', '--type=jpeg', file]).catch(() => ({ code: 1 }));
116
+ if (r.code === 0) {
117
+ try { emit(fs.readFileSync(file)); } catch { /* ignore */ }
118
+ const wait = 150 - (Date.now() - t0); // at most ~6 fps; screenshots are expensive
119
+ if (wait > 0) await new Promise((res) => setTimeout(res, wait));
120
+ } else {
121
+ hub.lastError = `simctl screenshot failed: ${(r.tail || []).slice(-2).join(' ')}`;
122
+ await new Promise((res) => setTimeout(res, 1000));
123
+ }
124
+ }
125
+ fs.rmSync(file, { force: true });
126
+ hub.child = null;
127
+ };
128
+ loop();
129
+ }
130
+
131
+ export async function subscribe(udid, fps, onFrame) {
132
+ let hub = hubs.get(udid);
133
+ if (!hub) {
134
+ hub = {
135
+ udid, fps, clients: new Set(), last: null, size: null, frames: 0,
136
+ child: null, stopped: false, lastError: null, mode: 'screenshot',
137
+ };
138
+ hubs.set(udid, hub);
139
+ }
140
+ clearTimeout(hub.idleTimer);
141
+ hub.clients.add(onFrame);
142
+ if (hub.last) onFrame(hub.last); // show something immediately
143
+ if (!hub.child && hub.clients.size === 1) {
144
+ hub.stopped = false;
145
+ startProducer(hub);
146
+ }
147
+ return () => {
148
+ hub.clients.delete(onFrame);
149
+ if (hub.clients.size) return;
150
+ // Keep the producer briefly so switching windows doesn't restart it.
151
+ hub.idleTimer = setTimeout(() => {
152
+ if (hub.clients.size) return;
153
+ hub.stopped = true; // ends the screenshot loop
154
+ hubs.delete(udid);
155
+ }, 5000);
156
+ };
157
+ }
158
+
159
+ // How many fallback (JPEG) viewers are watching, over every device.
160
+ export const fallbackViewers = () => [...hubs.values()].reduce((n, hub) => n + hub.clients.size, 0);
161
+
162
+ export function hubInfo(udid) {
163
+ const hub = hubs.get(udid);
164
+ return hub ? { mode: hub.mode, size: hub.size, frames: hub.frames, viewers: hub.clients.size, lastError: hub.lastError } : null;
165
+ }
166
+
167
+ // ---- coordinates -----------------------------------------------------------
168
+
169
+ // Screen size in points, which is what touch coordinates use: idb_companion's,
170
+ // else worked out from the last frame's pixels. Follows the frame's orientation.
171
+ export function screenPoints(udid) {
172
+ const px = hubs.get(udid)?.size;
173
+ let pts = live.companionPoints(udid);
174
+ if (!pts && px) {
175
+ // Modern iPhones are 3x, iPads and older iPhones 2x.
176
+ const scale = Math.min(px.width, px.height) >= 1080 && Math.min(px.width, px.height) < 1500 ? 3 : 2;
177
+ pts = { width: Math.round(px.width / scale), height: Math.round(px.height / scale) };
178
+ }
179
+ if (!pts) throw new Error('The screen size is unknown until the first frame arrives.');
180
+ // The companion reports portrait; match the frame's orientation.
181
+ if (px && (px.width > px.height) !== (pts.width > pts.height)) pts = { width: pts.height, height: pts.width };
182
+ return { ...pts, at: Date.now() };
183
+ }
184
+
185
+ // ---- input -----------------------------------------------------------------
186
+
187
+ const queues = new Map(); // udid -> promise chain, so events stay in order
188
+
189
+ // POST /input button names -> the companion's.
190
+ const BUTTONS = { home: 'HOME', lock: 'LOCK', 'side-button': 'SIDE_BUTTON', siri: 'SIRI', 'apple-pay': 'APPLE_PAY' };
191
+ const clamp01 = (v) => Math.min(1, Math.max(0, Number(v) || 0));
192
+ const secs = (ms, min, max) => Math.min(max, Math.max(min, Number(ms) / 1000));
193
+ const SWIPE_STEPS = 10;
194
+
195
+ // Checks a POST /input event; throws the message for a bad one.
196
+ export function checkInput(ev) {
197
+ switch (ev.kind) {
198
+ case 'tap': case 'longpress': case 'swipe': return;
199
+ case 'button':
200
+ if (!Object.hasOwn(BUTTONS, ev.button)) throw new Error(`Unknown button "${ev.button}"`);
201
+ return;
202
+ case 'text': {
203
+ if (typeof ev.text !== 'string' || !ev.text || ev.text.length > 2000) throw new Error('Text must be 1 to 2000 characters');
204
+ const bad = [...ev.text.replace(/\r\n?/g, '\n')].find((ch) => !live.hid.US_KEYS[ch]);
205
+ if (bad) throw new Error(`"${bad}" can't be typed on a US keyboard; paste it instead`);
206
+ return;
207
+ }
208
+ case 'key':
209
+ if (!Number.isInteger(ev.key) || ev.key < 0 || ev.key > 255) throw new Error('Key must be a HID keycode');
210
+ return;
211
+ default: throw new Error(`Unknown input "${ev.kind}"`);
212
+ }
213
+ }
214
+
215
+ // The HID events for a checked POST /input event. `pts` is the screen size in
216
+ // points, needed for tap, longpress and swipe.
217
+ export function inputEvents(ev, pts) {
218
+ const { press, keyPress, touchAt, delay, SHIFT, US_KEYS } = live.hid;
219
+ const at = (nx, ny) => [Math.round(clamp01(nx) * pts.width * 100) / 100, Math.round(clamp01(ny) * pts.height * 100) / 100];
220
+ switch (ev.kind) {
221
+ case 'tap': {
222
+ const [x, y] = at(ev.nx, ev.ny);
223
+ return [touchAt(x, y, 'DOWN'), touchAt(x, y, 'UP')];
224
+ }
225
+ case 'longpress': {
226
+ const [x, y] = at(ev.nx, ev.ny);
227
+ return [touchAt(x, y, 'DOWN'), delay(secs(ev.ms ?? 800, 0.3, 5)), touchAt(x, y, 'UP')];
228
+ }
229
+ case 'swipe': {
230
+ const [x1, y1] = at(ev.nx, ev.ny);
231
+ const [x2, y2] = at(ev.nx2, ev.ny2);
232
+ const step = secs(ev.ms ?? 300, 0.05, 2) / SWIPE_STEPS;
233
+ const events = [touchAt(x1, y1, 'DOWN')];
234
+ for (let i = 1; i <= SWIPE_STEPS; i++) {
235
+ const f = i / SWIPE_STEPS;
236
+ events.push(delay(step), touchAt(x1 + (x2 - x1) * f, y1 + (y2 - y1) * f, 'DOWN'));
237
+ }
238
+ events.push(touchAt(x2, y2, 'UP'));
239
+ return events;
240
+ }
241
+ case 'button': {
242
+ const btn = { button: { button: BUTTONS[ev.button] } };
243
+ return [press(btn, 'DOWN'), press(btn, 'UP')];
244
+ }
245
+ case 'text': {
246
+ const events = [];
247
+ for (const ch of ev.text.replace(/\r\n?/g, '\n')) {
248
+ const [code, shift] = US_KEYS[ch];
249
+ if (shift) events.push(keyPress(SHIFT, 'DOWN'));
250
+ events.push(keyPress(code, 'DOWN'), keyPress(code, 'UP'));
251
+ if (shift) events.push(keyPress(SHIFT, 'UP'));
252
+ }
253
+ return events;
254
+ }
255
+ case 'key':
256
+ return [keyPress(ev.key, 'DOWN'), keyPress(ev.key, 'UP')];
257
+ default: throw new Error(`Unknown input "${ev.kind}"`);
258
+ }
259
+ }
260
+
261
+ // Sends a POST /input event through idb_companion (started if needed).
262
+ export async function sendInput(udid, ev) {
263
+ checkInput(ev);
264
+ const prev = queues.get(udid) || Promise.resolve();
265
+ const next = prev.catch(() => {}).then(async () => {
266
+ const { client } = await live.companionFor(udid);
267
+ const pts = ['tap', 'longpress', 'swipe'].includes(ev.kind) ? screenPoints(udid) : null;
268
+ try {
269
+ await live.sendHid(client, inputEvents(ev, pts));
270
+ } catch (err) {
271
+ throw new Error(`${ev.kind} failed: ${err.message}`);
272
+ }
273
+ });
274
+ queues.set(udid, next);
275
+ return next;
276
+ }
277
+
278
+ // Stop every stream, e.g. when the agent shuts down.
279
+ export function stopAll() {
280
+ for (const hub of hubs.values()) {
281
+ hub.stopped = true;
282
+ clearTimeout(hub.idleTimer);
283
+ }
284
+ hubs.clear();
285
+ }