dsh-apk-vm 0.12.0 → 0.12.2

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,608 @@
1
+ /**
2
+ * Remote VM instance: a VM living behind an SSH tunnel.
3
+ *
4
+ * `RemoteVmInstance` exposes the same public surface as `ExtraVmInstance`
5
+ * (lib/instances.js) so the existing per-instance HTTP routes — panel, touch,
6
+ * input, clipboard, install, debug, snapshots, network, flows, skills and
7
+ * controls — can serve a remote session with no route changes.
8
+ *
9
+ * The lifecycle is inverted compared to a local AVD:
10
+ * 1. `start()` makes sure the SSH tunnel is running, which exposes the remote
11
+ * emulator's adb port on 127.0.0.1:<localPort>.
12
+ * 2. `vm.connect(serial)` runs `adb connect 127.0.0.1:<localPort>` and polls
13
+ * until the device is online.
14
+ * 3. `vm.attachDevice(serial)` attaches that already-online device to the VM
15
+ * (AndroidVm then waits for boot + prepares the debug system).
16
+ * 4. `stop({killRemote:true})` can additionally run the fixed remote
17
+ * `adb emu kill` command before detaching the local adb device.
18
+ *
19
+ * Everything is injectable for hermetic tests: `options.vm` (mock AndroidVm),
20
+ * `options.tunnel` (mock SshAdbTunnel), `options.runSsh`, `options.exec`,
21
+ * `options.now`, `options.sleep`, `options.streamFactory`.
22
+ */
23
+ import { AndroidVm } from './android.js';
24
+ import { ScrcpyStream } from './video-stream.js';
25
+ import { buildRemoteEmulatorStopCommand, runSshCommand } from './remote.js';
26
+ import path from 'node:path';
27
+
28
+ function shortHash(value) {
29
+ let hash = 0;
30
+ const text = String(value || '');
31
+ for (let i = 0; i < text.length; i += 1) {
32
+ hash = ((hash << 5) - hash + text.charCodeAt(i)) | 0;
33
+ }
34
+ return Math.abs(hash);
35
+ }
36
+
37
+ function errorText(error) {
38
+ return error && error.message ? error.message : String(error);
39
+ }
40
+
41
+ function defaultSleep(ms) {
42
+ return new Promise((resolve) => {
43
+ const timer = setTimeout(resolve, ms);
44
+ if (typeof timer.unref === 'function') timer.unref();
45
+ });
46
+ }
47
+
48
+ export class RemoteVmInstance {
49
+ /**
50
+ * @param {object} args
51
+ * @param {string} args.id session/instance id
52
+ * @param {object} args.profile normalized remote profile
53
+ * @param {object} args.tunnel SshAdbTunnel (or mock with start/stop/status)
54
+ * @param {object|null} [args.launchInfo] {consolePort,adbPort,logPath,startedAt}
55
+ * @param {object} [args.options] runtime options
56
+ * @param {Function} [args.log]
57
+ */
58
+ constructor({ id, profile, tunnel, launchInfo = null, options = {}, log }) {
59
+ this.id = id;
60
+ this.kind = 'remote';
61
+ this.profile = profile && typeof profile === 'object' ? profile : {};
62
+ this.tunnel = tunnel;
63
+ this.launchInfo = launchInfo && typeof launchInfo === 'object' ? launchInfo : null;
64
+ this.options = options && typeof options === 'object' ? options : {};
65
+ this.logSink = typeof log === 'function' ? log : null;
66
+
67
+ this.frame = { buffer: null, at: 0, inFlight: null };
68
+ this.lastApk = null;
69
+ this.installInFlight = null;
70
+ this.owner = null;
71
+ this.lastUsedAt = Date.now();
72
+
73
+ this.connectTimeoutMs = Math.max(1000, Number(this.options.connectTimeoutMs) || 180000);
74
+ this.connectRetryDelayMs = Math.max(10, Number(this.options.connectRetryDelayMs) || 2000);
75
+ this.remoteStopTimeoutMs = Math.max(1000, Number(this.options.remoteStopTimeoutMs) || 15000);
76
+ this.now = typeof this.options.now === 'function' ? this.options.now : Date.now;
77
+ this.sleep = typeof this.options.sleep === 'function' ? this.options.sleep : defaultSleep;
78
+ this.runSsh = typeof this.options.runSsh === 'function' ? this.options.runSsh : runSshCommand;
79
+ this.exec = typeof this.options.exec === 'function' ? this.options.exec : null;
80
+
81
+ this.lastAttachError = null;
82
+ this._attachPromise = null;
83
+ this.lastRemoteKill = null;
84
+
85
+ this.vm = this._createVm();
86
+ this.stream = this._createStream();
87
+ }
88
+
89
+ // -------------------------------------------------------------------------
90
+ // construction helpers (mockable)
91
+ // -------------------------------------------------------------------------
92
+
93
+ _initialSerial() {
94
+ if (this.options.serial) return String(this.options.serial);
95
+ const status = this._tunnelStatus();
96
+ return status && status.serial ? status.serial : null;
97
+ }
98
+
99
+ _createVm() {
100
+ if (this.options.vm && typeof this.options.vm === 'object') return this.options.vm;
101
+ if (typeof this.options.vmFactory === 'function') {
102
+ return this.options.vmFactory({
103
+ serial: this._initialSerial(),
104
+ profile: this.profile,
105
+ options: this.options,
106
+ log: (line) => this._log(line),
107
+ });
108
+ }
109
+ const vmOptions = { ...(this.options.vmOptions || {}) };
110
+ for (const key of [
111
+ 'sdkRoot',
112
+ 'adbPath',
113
+ 'gpuMode',
114
+ 'quickBoot',
115
+ 'snapshotName',
116
+ 'bootTimeoutMs',
117
+ 'connectTimeoutMs',
118
+ 'pollIntervalMs',
119
+ 'networkMode',
120
+ 'dnsServers',
121
+ // Media (virtual camera/mic) flags must stay on the AndroidVm so an
122
+ // SSH detach/attach restart keeps the same launch arguments.
123
+ 'extraEmulatorArgs',
124
+ 'enableAudio',
125
+ ]) {
126
+ if (this.options[key] !== undefined && vmOptions[key] === undefined) vmOptions[key] = this.options[key];
127
+ }
128
+ return new AndroidVm({
129
+ ...vmOptions,
130
+ // The remote host owns the emulator process: never spawn or kill locally.
131
+ spawnEmulator: false,
132
+ avdName: '',
133
+ serial: this._initialSerial() || undefined,
134
+ log: (line) => this._log(line),
135
+ });
136
+ }
137
+
138
+ _createStream() {
139
+ if (!this.options.scrcpyJarPath && typeof this.options.streamFactory !== 'function') return null;
140
+ const args = {
141
+ vm: this.vm,
142
+ jarPath: this.options.scrcpyJarPath,
143
+ maxSize: this.options.scrcpyMaxSize || 960,
144
+ bitrate: this.options.scrcpyBitrate || 6_000_000,
145
+ maxFps: this.options.scrcpyMaxFps || 60,
146
+ // Keep remote scrcpy ports out of the range used by local extra instances
147
+ // (27183 + emulator port) and let ScrcpyStream pick a free one anyway.
148
+ preferredPort: Number(this.options.streamPort) || 29183 + (shortHash(this.id) % 1000),
149
+ log: (line) => this._log(line),
150
+ };
151
+ if (typeof this.options.streamFactory === 'function') return this.options.streamFactory(args);
152
+ return new ScrcpyStream(args);
153
+ }
154
+
155
+ // -------------------------------------------------------------------------
156
+ // basic instance surface
157
+ // -------------------------------------------------------------------------
158
+
159
+ touch() {
160
+ this.lastUsedAt = Date.now();
161
+ }
162
+
163
+ _log(line) {
164
+ if (this.logSink) this.logSink(`[${this.id}] ${line}`);
165
+ }
166
+
167
+ _tunnelStatus() {
168
+ if (!this.tunnel || typeof this.tunnel.status !== 'function') return null;
169
+ try {
170
+ return this.tunnel.status();
171
+ } catch {
172
+ return null;
173
+ }
174
+ }
175
+
176
+ serial() {
177
+ const tunnelStatus = this._tunnelStatus();
178
+ return this.options.serial || (tunnelStatus && tunnelStatus.serial) || null;
179
+ }
180
+
181
+ async status() {
182
+ let status;
183
+ try {
184
+ status = await this.vm.status();
185
+ } catch (error) {
186
+ status = { state: 'error', error: errorText(error) };
187
+ }
188
+ const tunnel = this._tunnelStatus();
189
+ const serial = (status && status.serial) || this.serial();
190
+ return {
191
+ ...status,
192
+ id: this.id,
193
+ kind: 'remote',
194
+ host: this.profile.host || null,
195
+ user: this.profile.user || null,
196
+ sshPort: this.profile.sshPort || null,
197
+ avdName: this.profile.avdName || (status && status.avd) || '',
198
+ port: null,
199
+ serial: serial || null,
200
+ tunnel,
201
+ launch: this.launchInfo ? { ...this.launchInfo } : null,
202
+ profile: { ...this.profile },
203
+ attachError: this.lastAttachError,
204
+ attachInFlight: Boolean(this._attachPromise),
205
+ remoteKill: this.lastRemoteKill,
206
+ root: status && status.root === true,
207
+ debugPrepared: status && status.debugPrepared === true,
208
+ debugToolkit: (status && status.debugToolkit) || null,
209
+ identity: (status && status.identity) || null,
210
+ };
211
+ }
212
+
213
+ /** Ensure the SSH tunnel is running; returns its status. */
214
+ async _ensureTunnel() {
215
+ if (!this.tunnel || typeof this.tunnel.start !== 'function') {
216
+ throw new Error('remote instance has no SSH tunnel');
217
+ }
218
+ const current = this._tunnelStatus();
219
+ if (current && current.state === 'running') return current;
220
+ this._log('starting SSH tunnel');
221
+ const started = await this.tunnel.start();
222
+ if (started && started.ok === false) {
223
+ throw new Error(`SSH tunnel failed to start: ${started.error || started.lastError || 'unknown error'}`);
224
+ }
225
+ return this._tunnelStatus() || started || null;
226
+ }
227
+
228
+ _attachError(serial, lastError, attempts) {
229
+ const logPath = this.launchInfo && this.launchInfo.logPath
230
+ ? this.launchInfo.logPath
231
+ : (this.consolePort() ? `/tmp/apk-vm-emulator-${this.consolePort()}.log` : 'no remote emulator log (launch disabled)');
232
+ const detail = lastError ? errorText(lastError) : 'unknown error';
233
+ return new Error(
234
+ `remote adb attach failed for ${serial}: ${detail} (after ${attempts} attempt${attempts === 1 ? '' : 's'}); ` +
235
+ `emulator log: ${logPath}`,
236
+ );
237
+ }
238
+
239
+ /**
240
+ * Start the remote VM: tunnel → adb connect (retry within the deadline) →
241
+ * attach the device. `wait:false`/`attachInBackground:true` kicks off the
242
+ * (potentially long, boot-waiting) attach without blocking the caller.
243
+ */
244
+ async start(options = {}) {
245
+ this.touch();
246
+ if (this._attachPromise && options.wait !== false) {
247
+ // A previous background attach is still running; reuse it.
248
+ await this._attachPromise;
249
+ return this.status();
250
+ }
251
+ await this._ensureTunnel();
252
+ const serial = this.serial();
253
+ if (!serial) throw new Error('SSH tunnel is not exposing a loopback adb serial');
254
+
255
+ const deadline = this.now() + this.connectTimeoutMs;
256
+ let attempts = 0;
257
+ let lastError = null;
258
+ for (;;) {
259
+ attempts += 1;
260
+ try {
261
+ await this.vm.connect(serial);
262
+ lastError = null;
263
+ break;
264
+ } catch (error) {
265
+ lastError = error;
266
+ const message = errorText(error);
267
+ if (/unauthorized/i.test(message)) throw this._attachError(serial, error, attempts);
268
+ if (this.now() >= deadline) throw this._attachError(serial, lastError, attempts);
269
+ this._log(`adb connect ${serial} failed (attempt ${attempts}): ${message}`);
270
+ await this.sleep(this.connectRetryDelayMs);
271
+ }
272
+ }
273
+
274
+ const attach = async () => {
275
+ try {
276
+ await this.vm.attachDevice(serial);
277
+ this.lastAttachError = null;
278
+ } catch (error) {
279
+ this.lastAttachError = errorText(error);
280
+ throw error;
281
+ }
282
+ };
283
+ const background = options.attachInBackground === true || options.wait === false;
284
+ if (!background) {
285
+ await attach();
286
+ return this.status();
287
+ }
288
+ if (!this._attachPromise) {
289
+ this._attachPromise = attach()
290
+ .catch((error) => {
291
+ this._log(`background attach failed: ${errorText(error)}`);
292
+ })
293
+ .finally(() => {
294
+ this._attachPromise = null;
295
+ });
296
+ }
297
+ return this.status();
298
+ }
299
+
300
+ /** Await the in-flight background attach, if any (used by tests/routes). */
301
+ async waitForAttach() {
302
+ if (this._attachPromise) await this._attachPromise;
303
+ return this.lastAttachError;
304
+ }
305
+
306
+ consolePort() {
307
+ if (this.launchInfo && Number(this.launchInfo.consolePort) > 0) return Number(this.launchInfo.consolePort);
308
+ const remotePort = Number(this.profile.remotePort);
309
+ if (Number.isInteger(remotePort) && remotePort > 1) return remotePort - 1;
310
+ return null;
311
+ }
312
+
313
+ _remoteAdbPath() {
314
+ const sdkRoot = this.profile && typeof this.profile.sdkRoot === 'string' ? this.profile.sdkRoot.trim() : '';
315
+ if (!sdkRoot) return null;
316
+ return sdkRoot.replace(/\/+$/, '') + '/platform-tools/adb';
317
+ }
318
+
319
+ async _killRemote() {
320
+ const consolePort = this.consolePort();
321
+ if (!consolePort) {
322
+ this.lastRemoteKill = { ok: false, error: 'no remote emulator console port is known for this session' };
323
+ return this.lastRemoteKill;
324
+ }
325
+ let command;
326
+ try {
327
+ ({ command } = buildRemoteEmulatorStopCommand({ consolePort, adbPath: this._remoteAdbPath() }));
328
+ } catch (error) {
329
+ this.lastRemoteKill = { ok: false, error: errorText(error) };
330
+ return this.lastRemoteKill;
331
+ }
332
+ try {
333
+ const result = await this.runSsh(this.profile, command, {
334
+ timeoutMs: this.remoteStopTimeoutMs,
335
+ exec: this.exec || undefined,
336
+ });
337
+ this.lastRemoteKill = { ...(result || {}), command };
338
+ return this.lastRemoteKill;
339
+ } catch (error) {
340
+ this.lastRemoteKill = { ok: false, error: errorText(error), command };
341
+ return this.lastRemoteKill;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Stop the remote VM. Order is deliberate: optional remote `emu kill` first
347
+ * (so the adb port can be reused immediately), then detach the local device,
348
+ * then tear the SSH tunnel down.
349
+ */
350
+ async stop(options = {}) {
351
+ this.touch();
352
+ const killRemote = options && options.killRemote === true;
353
+ const remoteKill = killRemote ? await this._killRemote() : null;
354
+ let detach = null;
355
+ let detachError = null;
356
+ try {
357
+ detach = await this._stopVm();
358
+ } catch (error) {
359
+ detachError = errorText(error);
360
+ this._log(`stop: detach failed: ${detachError}`);
361
+ }
362
+ let tunnelStop = null;
363
+ let tunnelError = null;
364
+ try {
365
+ if (this.tunnel && typeof this.tunnel.stop === 'function') tunnelStop = await this.tunnel.stop();
366
+ } catch (error) {
367
+ tunnelError = errorText(error);
368
+ this._log(`stop: tunnel stop failed: ${tunnelError}`);
369
+ }
370
+ this.frame.buffer = null;
371
+ this.frame.at = 0;
372
+ return {
373
+ ok: true,
374
+ id: this.id,
375
+ kind: 'remote',
376
+ killRemote,
377
+ remoteKill,
378
+ detach,
379
+ detachError,
380
+ tunnel: tunnelStop || this._tunnelStatus(),
381
+ tunnelError,
382
+ };
383
+ }
384
+
385
+ async _stopVm() {
386
+ if (this._attachPromise) {
387
+ try {
388
+ await this._attachPromise;
389
+ } catch {
390
+ /* the attach error is recorded in status()/attachError */
391
+ }
392
+ }
393
+ return this.vm.stop();
394
+ }
395
+
396
+ async restart() {
397
+ this.touch();
398
+ await this.stop();
399
+ return this.start();
400
+ }
401
+
402
+ async saveSnapshot(name) {
403
+ this.touch();
404
+ return this.vm.saveSnapshot(name);
405
+ }
406
+
407
+ async screenshot() {
408
+ this.touch();
409
+ return this.vm.screenshot();
410
+ }
411
+
412
+ /** Cached PNG frame for the panel's instance view. */
413
+ async framePng() {
414
+ this.touch();
415
+ const now = Date.now();
416
+ if (this.frame.buffer && now - this.frame.at < 400) return this.frame.buffer;
417
+ if (!this.frame.inFlight) {
418
+ this.frame.inFlight = (async () => {
419
+ const png = await this.vm.screenshot();
420
+ this.frame.buffer = png;
421
+ this.frame.at = Date.now();
422
+ return png;
423
+ })().finally(() => {
424
+ this.frame.inFlight = null;
425
+ });
426
+ }
427
+ return this.frame.inFlight;
428
+ }
429
+
430
+ async installApk(apkPath) {
431
+ this.touch();
432
+ if (this.installInFlight) throw new Error('another APK install is already running on this instance');
433
+ this.installInFlight = (async () => {
434
+ const status = await this.vm.status();
435
+ if (status.state !== 'ready') throw new Error(`VM is not ready (state: ${status.state}); start it first`);
436
+ const meta = await this.vm.installApk(apkPath);
437
+ this.lastApk = {
438
+ path: apkPath,
439
+ packageName: meta.packageName || null,
440
+ label: meta.label || path.basename(apkPath),
441
+ launchActivity: meta.launchActivity || null,
442
+ launched: meta.launched !== false,
443
+ installedAt: Date.now(),
444
+ };
445
+ this.frame.buffer = null;
446
+ this.frame.at = 0;
447
+ void this.vm.saveSnapshot().catch(() => {});
448
+ return { ...this.lastApk };
449
+ })();
450
+ try {
451
+ return await this.installInFlight;
452
+ } finally {
453
+ this.installInFlight = null;
454
+ }
455
+ }
456
+
457
+ async input(payload) {
458
+ this.touch();
459
+ return this.vm.input(payload);
460
+ }
461
+
462
+ async sendTouch(message) {
463
+ this.touch();
464
+ if (!this.stream) throw new Error('H.264 stream is disabled for this instance');
465
+ await this.stream.ensure();
466
+ return this.stream.sendTouch(message);
467
+ }
468
+
469
+ async setClipboard(text, paste = false) {
470
+ this.touch();
471
+ if (!this.stream) throw new Error('H.264 stream is disabled for this instance');
472
+ return this.stream.setClipboard(text, paste);
473
+ }
474
+
475
+ async getClipboard() {
476
+ this.touch();
477
+ if (!this.stream) throw new Error('H.264 stream is disabled for this instance');
478
+ return this.stream.getClipboard();
479
+ }
480
+
481
+ /** Inject arbitrary UTF-8 text through the scrcpy control stream. */
482
+ async sendText(text) {
483
+ this.touch();
484
+ if (!this.stream) throw new Error('H.264 stream is disabled for this instance');
485
+ const messages = await this.stream.sendText(String(text));
486
+ return { ok: true, chars: String(text).length, messages };
487
+ }
488
+
489
+ handleVideoClient(client) {
490
+ this.touch();
491
+ if (!this.stream) {
492
+ client.sendText(JSON.stringify({ type: 'error', error: 'H.264 stream is disabled for this instance' }));
493
+ client.close(1001, 'stream disabled');
494
+ return;
495
+ }
496
+ try {
497
+ this.stream.handleClient(client);
498
+ } catch (error) {
499
+ this._log(`[video] handleClient failed: ${errorText(error)}`);
500
+ client.sendText(JSON.stringify({ type: 'error', error: errorText(error) }));
501
+ client.close(1011, 'stream handler failed');
502
+ }
503
+ }
504
+
505
+ videoStatus() {
506
+ return this.stream
507
+ ? this.stream.status()
508
+ : { enabled: false, active: false, clients: 0, fps: 0, maxFps: 0, error: 'scrcpyJarPath not configured' };
509
+ }
510
+
511
+ snapshotApk() {
512
+ return this.lastApk ? { ...this.lastApk } : null;
513
+ }
514
+
515
+ // Debug surface delegates (same as ExtraVmInstance; they also touch()).
516
+ shell(command, opts) {
517
+ this.touch();
518
+ return this.vm.shell(command, opts);
519
+ }
520
+ logcat(opts) {
521
+ this.touch();
522
+ return this.vm.logcat(opts);
523
+ }
524
+ getprop(name) {
525
+ this.touch();
526
+ return this.vm.getprop(name);
527
+ }
528
+ setprop(name, value) {
529
+ this.touch();
530
+ return this.vm.setprop(name, value);
531
+ }
532
+ listPackages(opts) {
533
+ this.touch();
534
+ return this.vm.listPackages(opts);
535
+ }
536
+ deviceInfo() {
537
+ this.touch();
538
+ return this.vm.deviceInfo();
539
+ }
540
+ ensureRoot() {
541
+ this.touch();
542
+ return this.vm.ensureRoot();
543
+ }
544
+ rotate(orientation) {
545
+ this.touch();
546
+ return this.vm.rotate(orientation);
547
+ }
548
+ uiDump() {
549
+ this.touch();
550
+ return this.vm.uiDump();
551
+ }
552
+ screenRecord(opts) {
553
+ this.touch();
554
+ return this.vm.screenRecord(opts);
555
+ }
556
+ perfSnapshot() {
557
+ this.touch();
558
+ return this.vm.perfSnapshot();
559
+ }
560
+ pushFile(local, remote) {
561
+ this.touch();
562
+ return this.vm.pushFile(local, remote);
563
+ }
564
+ pullFile(remote, local) {
565
+ this.touch();
566
+ return this.vm.pullFile(remote, local);
567
+ }
568
+ reboot(mode, options) {
569
+ this.touch();
570
+ return this.vm.reboot(mode, options);
571
+ }
572
+ forceStop(pkg) {
573
+ this.touch();
574
+ return this.vm.forceStop(pkg);
575
+ }
576
+ clearData(pkg) {
577
+ this.touch();
578
+ return this.vm.clearData(pkg);
579
+ }
580
+ uninstall(pkg) {
581
+ this.touch();
582
+ return this.vm.uninstall(pkg);
583
+ }
584
+ debugStatus() {
585
+ this.touch();
586
+ return this.vm.debugStatus();
587
+ }
588
+
589
+ async dispose() {
590
+ try {
591
+ if (this.stream) await this.stream.stop();
592
+ } catch {
593
+ /* best effort */
594
+ }
595
+ try {
596
+ await this.stop();
597
+ } catch {
598
+ /* best effort */
599
+ }
600
+ try {
601
+ await this.vm.dispose();
602
+ } catch {
603
+ /* best effort */
604
+ }
605
+ this.frame.buffer = null;
606
+ this.lastApk = null;
607
+ }
608
+ }