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,709 @@
1
+ import { spawn } from 'node:child_process';
2
+ import net from 'node:net';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import grpc from '@grpc/grpc-js';
6
+ import protoLoader from '@grpc/proto-loader';
7
+ import { agentEnv, run, which } from './exec.js';
8
+ import { discardAllRecordings, discardRecording } from './record.js';
9
+ import * as sim from './sim.js';
10
+
11
+ // Real-time simulator streaming through Meta's idb_companion
12
+ // (simcast-host setup installs it from the facebook/fb tap):
13
+ // video: hardware H.264 from the simulator's own framebuffer, sent only when the screen changes
14
+ // input: touches streamed live over the companion's HID service, which uses Indigo on
15
+ // Xcode 26 and dtuhidd on Xcode 27, so simcast needs no per-version code.
16
+
17
+ const log = (msg) => console.log(`[${new Date().toISOString()}] live: ${msg}`);
18
+ const PROTO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'proto', 'idb.proto');
19
+
20
+ let Companion = null;
21
+ function companionClientClass() {
22
+ if (!Companion) {
23
+ const def = protoLoader.loadSync(PROTO, { keepCase: true, longs: Number, enums: String, defaults: true, oneofs: true });
24
+ Companion = grpc.loadPackageDefinition(def).idb.CompanionService;
25
+ }
26
+ return Companion;
27
+ }
28
+
29
+ let companionPath = null;
30
+ // Only a hit is remembered, so installing idb_companion later works without a restart.
31
+ export async function findCompanion() {
32
+ if (companionPath) return companionPath;
33
+ companionPath = which('idb_companion');
34
+ return companionPath;
35
+ }
36
+
37
+ function freePort() {
38
+ return new Promise((resolve, reject) => {
39
+ const srv = net.createServer();
40
+ srv.unref();
41
+ srv.on('error', reject);
42
+ srv.listen(0, '127.0.0.1', () => {
43
+ const { port } = srv.address();
44
+ srv.close(() => resolve(port));
45
+ });
46
+ });
47
+ }
48
+
49
+ function runWithTimeout(cmd, args, ms) {
50
+ return new Promise((resolve) => {
51
+ const child = spawn(cmd, args, { env: agentEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
52
+ let out = '';
53
+ child.stdout.on('data', (d) => { out += d; });
54
+ child.stderr.on('data', (d) => { out += d; });
55
+ const timer = setTimeout(() => child.kill('SIGKILL'), ms);
56
+ child.on('error', () => { clearTimeout(timer); resolve({ code: -1, out }); });
57
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, out }); });
58
+ });
59
+ }
60
+
61
+ const unary = (client, method, req, ms = 10000) => new Promise((resolve, reject) => {
62
+ client[method](req, { deadline: Date.now() + ms }, (err, res) => (err ? reject(err) : resolve(res)));
63
+ });
64
+
65
+ // ---- host app check ------------------------------------------------------------
66
+
67
+ // A simulator shown in Device Hub or Simulator.app has its framebuffer taken by that
68
+ // app, so the companion gets no picture.
69
+ export async function hostAppRunning() {
70
+ for (const name of ['DeviceHub', 'Simulator']) {
71
+ const r = await run('pgrep', ['-x', name]).catch(() => ({ code: 1 }));
72
+ if (r.code === 0) return name === 'DeviceHub' ? 'Device Hub' : 'Simulator';
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // ---- companions ------------------------------------------------------------------
78
+
79
+ const companions = new Map(); // udid -> { proc, port, client, ready, description }
80
+
81
+ async function bootHeadless(dev) {
82
+ if (dev.state === 'Booted') return 'already booted';
83
+ log(`booting ${dev.name} headlessly through idb_companion`);
84
+ const r = await runWithTimeout('idb_companion', ['--boot', dev.udid], 180000);
85
+ const now = (await sim.listDevices()).find((d) => d.udid === dev.udid);
86
+ if (now?.state === 'Booted') return 'idb_companion --boot';
87
+ log(`idb_companion --boot didn't boot it (code ${r.code}): ${r.out.trim().slice(-300)}; using simctl`);
88
+ await sim.boot(dev.udid);
89
+ return 'simctl boot';
90
+ }
91
+
92
+ export async function companionFor(udid) {
93
+ const existing = companions.get(udid);
94
+ if (existing) return existing.ready;
95
+
96
+ const entry = { proc: null, port: null, client: null, ready: null, description: null };
97
+ companions.set(udid, entry);
98
+ entry.ready = (async () => {
99
+ if (!(await findCompanion())) {
100
+ throw new Error('idb_companion is not installed on the Mac. Install it with: simcast-host setup --only idb-companion');
101
+ }
102
+ const dev = (await sim.listDevices()).find((d) => d.udid === udid);
103
+ if (!dev) throw new Error(`Simulator ${udid} not found`);
104
+ await bootHeadless(dev);
105
+
106
+ entry.port = await freePort();
107
+ log(`starting idb_companion for ${dev.name} on port ${entry.port}`);
108
+ const proc = spawn('idb_companion', ['--udid', udid, '--grpc-port', String(entry.port)], {
109
+ env: agentEnv(), stdio: ['ignore', 'pipe', 'pipe'],
110
+ });
111
+ entry.proc = proc;
112
+ let lastOutput = '';
113
+ const capture = (d) => {
114
+ lastOutput = (lastOutput + d.toString()).slice(-2000);
115
+ };
116
+ proc.stdout.on('data', capture);
117
+ proc.stderr.on('data', capture);
118
+ proc.on('close', (code) => {
119
+ log(`idb_companion for ${dev.name} exited (code ${code}). ${lastOutput.trim().split('\n').slice(-3).join(' | ')}`);
120
+ if (companions.get(udid) === entry) companions.delete(udid);
121
+ entry.client?.close();
122
+ for (const s of sessions.values()) if (s.udid === udid) s.companionGone(code, lastOutput);
123
+ });
124
+
125
+ const Client = companionClientClass();
126
+ entry.client = new Client(`127.0.0.1:${entry.port}`, grpc.credentials.createInsecure(), {
127
+ 'grpc.max_receive_message_length': 64 * 1024 * 1024,
128
+ });
129
+ const deadline = Date.now() + 45000;
130
+ let lastErr = null;
131
+ while (Date.now() < deadline) {
132
+ if (proc.exitCode !== null) throw new Error(`idb_companion exited during startup: ${lastOutput.trim().slice(-400)}`);
133
+ try {
134
+ const res = await unary(entry.client, 'describe', { fetch_diagnostics: false }, 3000);
135
+ entry.description = res.target_description;
136
+ log(`idb_companion ready for ${dev.name}: ${JSON.stringify(entry.description?.screen_dimensions || {})}`);
137
+ return entry;
138
+ } catch (err) {
139
+ lastErr = err;
140
+ await new Promise((r) => setTimeout(r, 500));
141
+ }
142
+ }
143
+ proc.kill('SIGKILL');
144
+ throw new Error(`idb_companion didn't respond in time (${lastErr?.details || lastErr?.message}). ${lastOutput.trim().slice(-300)}`);
145
+ })();
146
+ entry.ready.catch(() => {
147
+ if (companions.get(udid) === entry) companions.delete(udid);
148
+ entry.proc?.kill('SIGKILL');
149
+ });
150
+ return entry.ready;
151
+ }
152
+
153
+ // ---- rotation --------------------------------------------------------------------
154
+
155
+ // Each one a quarter turn to the left of the one before: turning the device
156
+ // left from portrait puts its bottom on the right, which iOS calls landscape left.
157
+ const ORIENTATIONS = ['PORTRAIT', 'LANDSCAPE_LEFT', 'PORTRAIT_UPSIDE_DOWN', 'LANDSCAPE_RIGHT'];
158
+ const lastOrientation = new Map(); // udid -> what we last set, for companions that can't report it
159
+
160
+ async function reportedOrientation(client) {
161
+ try {
162
+ const res = await unary(client, 'get_orientation', {}, 3000);
163
+ return ORIENTATIONS.includes(res.orientation) ? res.orientation : null;
164
+ } catch {
165
+ return null; // older companion
166
+ }
167
+ }
168
+
169
+ // Turns the simulated device a quarter turn, 'left' (like Simulator's Rotate
170
+ // Left) or 'right'. The picture follows by itself: the video stream changes shape.
171
+ // Returns what was asked and what the companion reports afterwards.
172
+ export async function rotate(udid, dir) {
173
+ if (dir !== 'left' && dir !== 'right') throw new Error('Rotate "left" or "right"');
174
+ const { client } = await companionFor(udid);
175
+ const before = await reportedOrientation(client);
176
+ const current = before || lastOrientation.get(udid) || 'PORTRAIT';
177
+ const next = ORIENTATIONS[(ORIENTATIONS.indexOf(current) + (dir === 'left' ? 1 : 3)) % 4];
178
+ // Two routes: the set_orientation RPC, and the older HID orientation event.
179
+ // Some companions accept the RPC without turning the device, so both are sent;
180
+ // each names the target orientation, so doing both is harmless.
181
+ const via = [];
182
+ const errors = [];
183
+ try {
184
+ await unary(client, 'set_orientation', { orientation: next }, 5000);
185
+ via.push('set_orientation');
186
+ } catch (err) {
187
+ if (err.code !== grpc.status.UNIMPLEMENTED) errors.push(`set_orientation: ${err.details || err.message}`);
188
+ }
189
+ try {
190
+ await new Promise((resolve, reject) => {
191
+ const call = client.hid((e) => (e ? reject(e) : resolve()));
192
+ call.write({ orientation: { orientation: next } });
193
+ call.end();
194
+ });
195
+ via.push('hid');
196
+ } catch (err) {
197
+ errors.push(`hid: ${err.details || err.message}`);
198
+ }
199
+ if (!via.length) throw new Error(`Couldn't rotate (${errors.join('; ')})`);
200
+ lastOrientation.set(udid, next);
201
+ const after = await reportedOrientation(client);
202
+ log(`rotate ${udid} ${dir}: ${before || '?'} -> ${next} via ${via.join('+')}; companion now reports ${after || '?'}${errors.length ? ` (${errors.join('; ')})` : ''}`);
203
+ return { from: before, to: next, reported: after, via, errors };
204
+ }
205
+
206
+ export function stopAllCompanions() {
207
+ discardAllRecordings();
208
+ for (const s of sessions.values()) s.close('agent stopping');
209
+ for (const c of companions.values()) c.proc?.kill('SIGKILL');
210
+ companions.clear();
211
+ }
212
+
213
+ // ---- H.264 Annex B -> access units -----------------------------------------------
214
+
215
+ const START4 = Buffer.from([0, 0, 0, 1]);
216
+ // 0 flushes at the end of every gRPC message, which saves the delay but is only
217
+ // safe if the companion never splits a frame across messages (unverified).
218
+ const FLUSH_MS = Number(process.env.SIMCAST_AU_FLUSH_MS ?? 4);
219
+
220
+ // Groups H.264 NAL units into whole frames ("access units") for the decoder.
221
+ export class AnnexBAssembler {
222
+ constructor(onAccessUnit, { flushDelayMs = FLUSH_MS } = {}) {
223
+ this.onAccessUnit = onAccessUnit;
224
+ this.flushDelayMs = flushDelayMs;
225
+ this.buf = Buffer.alloc(0);
226
+ this.nals = [];
227
+ this.hasVcl = false;
228
+ this.isKey = false;
229
+ this.timer = null;
230
+ }
231
+
232
+ push(chunk) {
233
+ this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : Buffer.from(chunk);
234
+ this.extract(false);
235
+ // VideoToolbox delivers whole frames; flushing shortly after the data stops
236
+ // means a frame is shown right away instead of waiting for the next one.
237
+ clearTimeout(this.timer);
238
+ if (this.flushDelayMs <= 0) this.flush();
239
+ else this.timer = setTimeout(() => this.flush(), this.flushDelayMs);
240
+ }
241
+
242
+ flush() {
243
+ clearTimeout(this.timer);
244
+ this.extract(true);
245
+ this.emit();
246
+ }
247
+
248
+ extract(final) {
249
+ const starts = [];
250
+ let i = 0;
251
+ while (true) {
252
+ const j = this.buf.indexOf(0x01, i + 2);
253
+ if (j < 0) break;
254
+ if (this.buf[j - 1] === 0 && this.buf[j - 2] === 0) {
255
+ const codeStart = j >= 3 && this.buf[j - 3] === 0 ? j - 3 : j - 2;
256
+ starts.push({ codeStart, dataStart: j + 1 });
257
+ }
258
+ i = j - 1;
259
+ }
260
+ if (!starts.length) {
261
+ if (final) this.buf = Buffer.alloc(0);
262
+ return;
263
+ }
264
+ for (let k = 0; k < starts.length - 1; k++) {
265
+ this.addNal(this.buf.subarray(starts[k].dataStart, starts[k + 1].codeStart));
266
+ }
267
+ const last = starts[starts.length - 1];
268
+ if (final) {
269
+ this.addNal(this.buf.subarray(last.dataStart));
270
+ this.buf = Buffer.alloc(0);
271
+ } else {
272
+ this.buf = Buffer.from(this.buf.subarray(last.codeStart));
273
+ }
274
+ }
275
+
276
+ addNal(nal) {
277
+ if (!nal.length) return;
278
+ const type = nal[0] & 0x1f;
279
+ const vcl = type === 1 || type === 5;
280
+ const startsNewFrame = this.hasVcl
281
+ && (type === 9 || type === 7 || type === 8 || type === 6 || (vcl && (nal[1] & 0x80)));
282
+ if (startsNewFrame) this.emit();
283
+ this.nals.push(Buffer.from(nal));
284
+ if (vcl) {
285
+ this.hasVcl = true;
286
+ if (type === 5) this.isKey = true;
287
+ }
288
+ }
289
+
290
+ emit() {
291
+ if (!this.hasVcl) return; // keep SPS/PPS for the frame they belong to
292
+ const parts = [];
293
+ for (const n of this.nals) parts.push(START4, n);
294
+ const au = Buffer.concat(parts);
295
+ const key = this.isKey;
296
+ this.nals = [];
297
+ this.hasVcl = false;
298
+ this.isKey = false;
299
+ this.onAccessUnit(au, key);
300
+ }
301
+ }
302
+
303
+ // ---- keyboard ------------------------------------------------------------------
304
+
305
+ const SHIFT = 225;
306
+ const US_KEYS = (() => {
307
+ const map = {};
308
+ for (let c = 0; c < 26; c++) {
309
+ map[String.fromCharCode(97 + c)] = [4 + c, false];
310
+ map[String.fromCharCode(65 + c)] = [4 + c, true];
311
+ }
312
+ '1234567890'.split('').forEach((d, idx) => { map[d] = [30 + idx, false]; });
313
+ '!@#$%^&*()'.split('').forEach((d, idx) => { map[d] = [30 + idx, true]; });
314
+ Object.assign(map, {
315
+ '\n': [40, false], '\t': [43, false], ' ': [44, false],
316
+ '-': [45, false], _: [45, true], '=': [46, false], '+': [46, true],
317
+ '[': [47, false], '{': [47, true], ']': [48, false], '}': [48, true],
318
+ '\\': [49, false], '|': [49, true], ';': [51, false], ':': [51, true],
319
+ "'": [52, false], '"': [52, true], '`': [53, false], '~': [53, true],
320
+ ',': [54, false], '<': [54, true], '.': [55, false], '>': [55, true],
321
+ '/': [56, false], '?': [56, true],
322
+ });
323
+ return map;
324
+ })();
325
+
326
+ const press = (action, direction) => ({ press: { action, direction } });
327
+ const keyPress = (code, dir) => press({ key: { keycode: code } }, dir);
328
+ const touchAt = (x, y, dir) => press({ touch: { point: { x, y } } }, dir);
329
+ const delay = (s) => ({ delay: { duration: s } });
330
+
331
+ // The HID event builders and the US keyboard map, for the fallback view's input
332
+ // (screen.js sendInput), which goes through the companion the same way.
333
+ export const hid = { press, keyPress, touchAt, delay, SHIFT, US_KEYS };
334
+
335
+ // Sends HID events to a companion as one stream; resolves when it has taken them.
336
+ export function sendHid(client, events) {
337
+ return new Promise((resolve, reject) => {
338
+ const call = client.hid((err) => {
339
+ if (err && err.code !== grpc.status.CANCELLED) reject(new Error(err.details || err.message));
340
+ else resolve();
341
+ });
342
+ for (const e of events) call.write(e);
343
+ call.end();
344
+ });
345
+ }
346
+
347
+ // The screen size in points (portrait) of a running companion's simulator, or null.
348
+ export function companionPoints(udid) {
349
+ const d = companions.get(udid)?.description?.screen_dimensions;
350
+ return d?.width_points && d?.height_points ? { width: d.width_points, height: d.height_points } : null;
351
+ }
352
+ const MODIFIERS = { shift: 225, ctrl: 224, alt: 226, meta: 227 };
353
+ const BUTTONS = new Set(['HOME', 'LOCK', 'SIDE_BUTTON', 'SIRI', 'VOLUME_UP', 'VOLUME_DOWN', 'APPLE_PAY']);
354
+
355
+ // ---- live sessions -------------------------------------------------------------
356
+
357
+ const QUALITY = {
358
+ sharp: { scale_factor: 1, avg_bitrate: 14e6 },
359
+ balanced: { scale_factor: 0.75, avg_bitrate: 8e6 },
360
+ light: { scale_factor: 0.5, avg_bitrate: 4e6 },
361
+ };
362
+ const MAX_GOP_BYTES = 48 * 1024 * 1024;
363
+ // How much video may queue up for a viewer before it skips to the next keyframe:
364
+ // one keyframe plus about 250 ms of stream, so a slow link costs a short skip
365
+ // instead of seconds of lag.
366
+ const MAX_LAG_SECONDS = 0.25;
367
+ const MIN_BUFFERED = 256 * 1024;
368
+
369
+ const sessions = new Map(); // udid -> LiveSession
370
+
371
+ class LiveSession {
372
+ constructor(udid, name) {
373
+ this.udid = udid;
374
+ this.name = name;
375
+ this.viewers = new Set();
376
+ this.gop = [];
377
+ this.gopBytes = 0;
378
+ this.gopValid = false;
379
+ this.video = null;
380
+ this.quality = 'balanced';
381
+ this.frames = 0;
382
+ this.closed = false;
383
+ }
384
+
385
+ get companion() {
386
+ return companions.get(this.udid);
387
+ }
388
+
389
+ info() {
390
+ const d = this.companion?.description?.screen_dimensions || {};
391
+ return {
392
+ t: 'info', device: this.name, udid: this.udid, quality: this.quality,
393
+ points: { w: d.width_points || 0, h: d.height_points || 0 },
394
+ pixels: { w: d.width || 0, h: d.height || 0 }, density: d.density || 0,
395
+ };
396
+ }
397
+
398
+ broadcast(obj) {
399
+ const text = JSON.stringify(obj);
400
+ for (const v of this.viewers) if (v.ws.readyState === 1) v.ws.send(text);
401
+ }
402
+
403
+ async startVideo() {
404
+ const { client } = await companionFor(this.udid);
405
+ if (this.closed) return;
406
+ const q = QUALITY[this.quality] || QUALITY.balanced;
407
+ log(`starting H.264 stream for ${this.name} (${this.quality})`);
408
+ const call = client.video_stream();
409
+ this.video = call;
410
+ this.gop = [];
411
+ this.gopBytes = 0;
412
+ this.gopValid = false;
413
+ const assembler = new AnnexBAssembler((au, key) => this.onFrame(au, key));
414
+ let gotData = false;
415
+ const noPicture = setTimeout(async () => {
416
+ if (gotData || this.video !== call) return;
417
+ const host = await hostAppRunning();
418
+ const msg = host
419
+ ? `No picture yet. ${host} is open on the Mac and holds the simulator's screen; quit it there.`
420
+ : 'No picture yet from idb_companion.';
421
+ log(msg);
422
+ this.broadcast({ t: 'warn', msg });
423
+ }, 6000);
424
+ call.on('data', (res) => {
425
+ if (res.payload?.data?.length) {
426
+ gotData = true;
427
+ assembler.push(res.payload.data);
428
+ } else if (res.log_output?.length) {
429
+ log(`companion: ${res.log_output.toString().trim().slice(0, 300)}`);
430
+ }
431
+ });
432
+ const ended = (err) => {
433
+ clearTimeout(noPicture);
434
+ assembler.flush();
435
+ if (this.video !== call) return;
436
+ this.video = null;
437
+ const why = err ? (err.details || err.message) : 'stream ended';
438
+ log(`video stream for ${this.name} stopped: ${why}`);
439
+ if (this.viewers.size && !this.closed) {
440
+ this.broadcast({ t: 'warn', msg: `Video restarting (${why})` });
441
+ this.restartTimer = setTimeout(() => this.startVideo().catch((e) => this.fail(e)), 1000);
442
+ }
443
+ };
444
+ call.on('error', ended);
445
+ call.on('end', () => ended(null));
446
+ call.write({
447
+ start: {
448
+ file_path: '', fps: 0, format: 'H264', compression_quality: 0,
449
+ scale_factor: q.scale_factor, avg_bitrate: q.avg_bitrate, key_frame_rate: 2,
450
+ },
451
+ });
452
+ }
453
+
454
+ stopVideo() {
455
+ clearTimeout(this.restartTimer);
456
+ const call = this.video;
457
+ this.video = null;
458
+ if (call) {
459
+ try { call.write({ stop: {} }); call.end(); } catch { /* already closed */ }
460
+ setTimeout(() => call.cancel(), 1000).unref();
461
+ }
462
+ }
463
+
464
+ maxBuffered() {
465
+ const { avg_bitrate } = QUALITY[this.quality] || QUALITY.balanced;
466
+ return Math.max(MIN_BUFFERED, (this.lastKeyBytes || 0) + (avg_bitrate / 8) * MAX_LAG_SECONDS);
467
+ }
468
+
469
+ onFrame(au, key) {
470
+ this.frames++;
471
+ if (key) {
472
+ this.lastKeyBytes = au.length;
473
+ this.gop = [au];
474
+ this.gopBytes = au.length;
475
+ this.gopValid = true;
476
+ } else if (this.gopValid) {
477
+ this.gopBytes += au.length;
478
+ if (this.gopBytes > MAX_GOP_BYTES) { this.gop = []; this.gopValid = false; } else this.gop.push(au);
479
+ }
480
+ const msg = Buffer.concat([Buffer.from([key ? 1 : 0]), au]);
481
+ const maxBuffered = this.maxBuffered();
482
+ for (const v of this.viewers) {
483
+ if (v.ws.readyState !== 1) continue;
484
+ if (v.needsKey) {
485
+ if (!key) continue;
486
+ v.needsKey = false;
487
+ }
488
+ // A slow connection skips ahead to the next keyframe instead of lagging behind.
489
+ if (v.ws.bufferedAmount > maxBuffered) {
490
+ v.needsKey = true;
491
+ continue;
492
+ }
493
+ v.ws.send(msg);
494
+ }
495
+ }
496
+
497
+ replayTo(viewer) {
498
+ if (!this.gopValid || !this.gop.length) {
499
+ viewer.needsKey = true;
500
+ return;
501
+ }
502
+ for (const [i, au] of this.gop.entries()) viewer.ws.send(Buffer.concat([Buffer.from([i === 0 ? 1 : 0]), au]));
503
+ viewer.needsKey = false;
504
+ }
505
+
506
+ fail(err) {
507
+ log(`${this.name}: ${err.message}`);
508
+ this.broadcast({ t: 'error', msg: err.message });
509
+ }
510
+
511
+ companionGone(code, output) {
512
+ this.video = null;
513
+ const tail = output.trim().split('\n').slice(-2).join(' ');
514
+ this.broadcast({ t: 'warn', msg: `idb_companion stopped (code ${code}). Reconnecting… ${tail}` });
515
+ if (this.viewers.size && !this.closed) {
516
+ this.restartTimer = setTimeout(() => this.startVideo().catch((e) => this.fail(e)), 2000);
517
+ }
518
+ }
519
+
520
+ close(reason) {
521
+ this.closed = true;
522
+ // Nobody is watching any more, so nobody will collect a recording.
523
+ discardRecording(this.udid);
524
+ this.stopVideo();
525
+ for (const v of this.viewers) {
526
+ try { v.ws.close(1001, reason); } catch { /* ignore */ }
527
+ }
528
+ sessions.delete(this.udid);
529
+ }
530
+
531
+ // ---- input ----
532
+
533
+ points(nx, ny) {
534
+ const { w, h } = this.info().points;
535
+ if (!w || !h) throw new Error('Screen size unknown');
536
+ const pix = this.lastFrameLandscape;
537
+ // The companion reports portrait points; follow the picture's orientation.
538
+ const [pw, ph] = pix !== undefined && pix !== (w > h) ? [h, w] : [w, h];
539
+ const clamp = (v) => Math.min(1, Math.max(0, Number(v) || 0));
540
+ return [Math.round(clamp(nx) * pw * 100) / 100, Math.round(clamp(ny) * ph * 100) / 100];
541
+ }
542
+
543
+ hidCall(viewer, label) {
544
+ const { client } = this.companion || {};
545
+ if (!client) throw new Error('idb_companion is not ready');
546
+ return client.hid((err) => {
547
+ if (err && err.code !== grpc.status.CANCELLED) {
548
+ log(`${label} failed: ${err.details || err.message}`);
549
+ if (viewer.ws.readyState === 1) viewer.ws.send(JSON.stringify({ t: 'error', msg: `${label} failed: ${err.details || err.message}` }));
550
+ }
551
+ });
552
+ }
553
+
554
+ sendEvents(viewer, label, events) {
555
+ const call = this.hidCall(viewer, label);
556
+ for (const e of events) call.write(e);
557
+ call.end();
558
+ }
559
+
560
+ handleInput(viewer, m) {
561
+ switch (m.t) {
562
+ case 'touch': {
563
+ const [x, y] = this.points(m.x, m.y);
564
+ if (m.p === 'down') {
565
+ viewer.gesture?.end();
566
+ // One HID stream per gesture: moves are sent as they happen, so drags track
567
+ // the pointer live; ending the stream also completes the gesture.
568
+ viewer.gesture = this.hidCall(viewer, 'Touch');
569
+ viewer.gesture.write(touchAt(x, y, 'DOWN'));
570
+ viewer.lastTouch = [x, y];
571
+ } else if (m.p === 'move' && viewer.gesture) {
572
+ viewer.gesture.write(touchAt(x, y, 'DOWN'));
573
+ viewer.lastTouch = [x, y];
574
+ } else if (m.p === 'up' && viewer.gesture) {
575
+ if (m.fling === false) viewer.gesture.write(touchAt(x, y, 'DOWN'));
576
+ viewer.gesture.write(touchAt(x, y, 'UP'));
577
+ viewer.gesture.end();
578
+ viewer.gesture = null;
579
+ }
580
+ break;
581
+ }
582
+ case 'scroll': {
583
+ const [x, y] = this.points(m.x, m.y);
584
+ const { w, h } = this.info().points;
585
+ const dx = Math.max(-w * 0.45, Math.min(w * 0.45, Number(m.dx) || 0));
586
+ const dy = Math.max(-h * 0.45, Math.min(h * 0.45, Number(m.dy) || 0));
587
+ const steps = 6;
588
+ const events = [touchAt(x, y, 'DOWN')];
589
+ for (let i = 1; i <= steps; i++) {
590
+ events.push(delay(0.012), touchAt(x - (dx * i) / steps, y - (dy * i) / steps, 'DOWN'));
591
+ }
592
+ events.push(touchAt(x - dx, y - dy, 'UP'));
593
+ this.sendEvents(viewer, 'Scroll', events);
594
+ break;
595
+ }
596
+ case 'button': {
597
+ if (!BUTTONS.has(m.name)) throw new Error(`Unknown button ${m.name}`);
598
+ const btn = { button: { button: m.name } };
599
+ this.sendEvents(viewer, 'Button', m.hold
600
+ ? [press(btn, 'DOWN'), delay(Math.min(5, Number(m.hold) || 1)), press(btn, 'UP')]
601
+ : [press(btn, 'DOWN'), press(btn, 'UP')]);
602
+ break;
603
+ }
604
+ case 'key': {
605
+ const code = Number(m.code);
606
+ if (!Number.isInteger(code) || code < 4 || code > 231) throw new Error('Bad keycode');
607
+ const mods = Object.entries(MODIFIERS).filter(([k]) => m[k]).map(([, v]) => v);
608
+ this.sendEvents(viewer, 'Key', [
609
+ ...mods.map((c) => keyPress(c, 'DOWN')),
610
+ keyPress(code, 'DOWN'), keyPress(code, 'UP'),
611
+ ...mods.reverse().map((c) => keyPress(c, 'UP')),
612
+ ]);
613
+ break;
614
+ }
615
+ case 'text': {
616
+ const text = String(m.text || '').slice(0, 2000);
617
+ const events = [];
618
+ let skipped = 0;
619
+ for (const ch of text.replace(/\r\n?/g, '\n')) {
620
+ const k = US_KEYS[ch];
621
+ if (!k) { skipped++; continue; }
622
+ const [code, shift] = k;
623
+ if (shift) events.push(keyPress(SHIFT, 'DOWN'));
624
+ events.push(keyPress(code, 'DOWN'), keyPress(code, 'UP'));
625
+ if (shift) events.push(keyPress(SHIFT, 'UP'));
626
+ }
627
+ if (events.length) this.sendEvents(viewer, 'Typing', events);
628
+ if (skipped) viewer.ws.send(JSON.stringify({ t: 'warn', msg: `${skipped} characters can't be typed on a US keyboard and were skipped` }));
629
+ break;
630
+ }
631
+ case 'orientation':
632
+ this.lastFrameLandscape = !!m.landscape;
633
+ break;
634
+ default:
635
+ throw new Error(`Unknown message ${m.t}`);
636
+ }
637
+ }
638
+ }
639
+
640
+ export async function attachViewer(ws, { device, quality }) {
641
+ const dev = await sim.resolveDevice(device);
642
+ let session = sessions.get(dev.udid);
643
+ if (!session) {
644
+ session = new LiveSession(dev.udid, dev.name);
645
+ sessions.set(dev.udid, session);
646
+ }
647
+ clearTimeout(session.idleTimer);
648
+ const viewer = { ws, needsKey: true, gesture: null };
649
+ session.viewers.add(viewer);
650
+ log(`viewer joined ${dev.name} (${session.viewers.size} watching)`);
651
+
652
+ ws.on('message', (data, isBinary) => {
653
+ if (isBinary) return;
654
+ try {
655
+ session.handleInput(viewer, JSON.parse(data.toString()));
656
+ } catch (err) {
657
+ if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'error', msg: err.message }));
658
+ }
659
+ });
660
+ ws.on('close', () => {
661
+ session.viewers.delete(viewer);
662
+ if (viewer.gesture) {
663
+ // Lift a finger that was still down when the window closed.
664
+ try {
665
+ const [x, y] = viewer.lastTouch || [0, 0];
666
+ viewer.gesture.write(touchAt(x, y, 'UP'));
667
+ viewer.gesture.end();
668
+ } catch { /* ignore */ }
669
+ }
670
+ log(`viewer left ${dev.name} (${session.viewers.size} watching)`);
671
+ if (!session.viewers.size) {
672
+ session.idleTimer = setTimeout(() => {
673
+ if (session.viewers.size) return;
674
+ session.close('idle');
675
+ const c = companions.get(dev.udid);
676
+ c?.proc?.kill('SIGTERM');
677
+ companions.delete(dev.udid);
678
+ }, 30000);
679
+ }
680
+ });
681
+
682
+ ws.send(JSON.stringify({ t: 'status', msg: `Starting idb_companion for ${dev.name}…` }));
683
+ try {
684
+ const wanted = QUALITY[quality] ? quality : session.quality;
685
+ await companionFor(dev.udid);
686
+ ws.send(JSON.stringify(session.info()));
687
+ if (!session.video || wanted !== session.quality) {
688
+ session.quality = wanted;
689
+ session.stopVideo();
690
+ await session.startVideo();
691
+ } else {
692
+ session.replayTo(viewer);
693
+ }
694
+ session.broadcast(session.info());
695
+ } catch (err) {
696
+ log(`could not start live view for ${dev.name}: ${err.message}`);
697
+ if (ws.readyState === 1) {
698
+ ws.send(JSON.stringify({ t: 'fatal', msg: err.message }));
699
+ ws.close(1011, 'live view unavailable');
700
+ }
701
+ }
702
+ }
703
+
704
+ export function liveStatus() {
705
+ return [...sessions.values()].map((s) => ({
706
+ device: s.name, udid: s.udid, viewers: s.viewers.size, frames: s.frames,
707
+ streaming: !!s.video, quality: s.quality,
708
+ }));
709
+ }