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.
package/index.js CHANGED
@@ -18,6 +18,7 @@ import { createReadStream, existsSync, readFileSync, realpathSync } from 'node:f
18
18
  import { promises as fsp } from 'node:fs';
19
19
  import net from 'node:net';
20
20
  import os from 'node:os';
21
+ import { spawn } from 'node:child_process';
21
22
  import path from 'node:path';
22
23
  import { fileURLToPath } from 'node:url';
23
24
 
@@ -40,11 +41,13 @@ import { collectStorage, cleanTempFiles, cleanSnapshots, cleanOrphanAvds, format
40
41
  import { buildApksFromAab, aabInfo, detectBundletool } from './lib/aab.js';
41
42
  import { readHarFile, summarizeHar, filterHar, toCurl } from './lib/har.js';
42
43
  import { runAssertions, compareScreenshot, createTestReport, reportMarkdown } from './lib/ui-tests.js';
43
- import { SshAdbTunnel } from './lib/remote.js';
44
+ import { RemoteProfileBook, RemoteSessionManager, defaultRemoteProfilesPath, normalizeRemoteProfile, buildSshCommandArgs, quoteRemoteArg, runSshCommand } from './lib/remote.js';
44
45
  import { CdpBridge, previewJsValue } from './lib/cdp.js';
45
46
  import { losslessJson } from './lib/json-safe.js';
46
47
  import { ActivityLog } from './lib/activity-log.js';
47
48
  import { InstalledAppRegistry, defaultInstalledAppsPath, reinstallMissingApps, summarizeReinstallResult } from './lib/installed-apps.js';
49
+ import { normalizeCameraConfig, normalizeMicConfig, checkPosterFile, mediaLaunchOptions, cameraCapabilities, micCapabilities, micSourceName, remoteAudioPath, remoteMediaPaths, remotePosterPath } from './lib/media.js';
50
+ import { collectLocalInventory, collectRemoteInventory, buildEmulatorInventory } from './lib/emulator-inventory.js';
48
51
 
49
52
  const PLUGIN_VERSION = (() => {
50
53
  try {
@@ -67,6 +70,33 @@ const UPLOAD_LIMIT_BYTES = 500 * 1024 * 1024;
67
70
  const FRAME_TTL_MS = 200;
68
71
  /** Cache `wm size` for a while to keep the 2 s status poll cheap. */
69
72
  const SCREEN_TTL_MS = 15_000;
73
+ /** Media (virtual camera / mic) settings live next to the activity journal. */
74
+ const MEDIA_SETTINGS_VERSION = 1;
75
+ const DEFAULT_CAMERA_CONFIG = { back: 'emulated', front: 'none', posters: [] };
76
+ const DEFAULT_MIC_CONFIG = { mode: 'off' };
77
+
78
+ function mediaSettingsPath(dataRoot) {
79
+ return path.join(dataRoot, '.apk-vm', 'media.json');
80
+ }
81
+
82
+ // Media settings are read synchronously so the default AndroidVm can be built
83
+ // with its camera/mic launch arguments before the first boot. A corrupt or
84
+ // partially written file falls back to the built-in defaults.
85
+ function loadMediaSettings(dataRoot, cfg) {
86
+ let stored = null;
87
+ try {
88
+ stored = JSON.parse(readFileSync(mediaSettingsPath(dataRoot), 'utf8'));
89
+ } catch {
90
+ stored = null;
91
+ }
92
+ const cameraInput = { ...DEFAULT_CAMERA_CONFIG, ...(cfg.camera && typeof cfg.camera === 'object' ? cfg.camera : {}), ...(stored && stored.camera && typeof stored.camera === 'object' ? stored.camera : {}) };
93
+ const micInput = { ...DEFAULT_MIC_CONFIG, ...(cfg.mic && typeof cfg.mic === 'object' ? cfg.mic : {}), ...(stored && stored.mic && typeof stored.mic === 'object' ? stored.mic : {}) };
94
+ try {
95
+ return { camera: normalizeCameraConfig(cameraInput), mic: normalizeMicConfig(micInput) };
96
+ } catch {
97
+ return { camera: normalizeCameraConfig(DEFAULT_CAMERA_CONFIG), mic: normalizeMicConfig(DEFAULT_MIC_CONFIG) };
98
+ }
99
+ }
70
100
 
71
101
  function isReady(vm) {
72
102
  return vm && vm.state === 'ready';
@@ -271,6 +301,11 @@ function resolveApkPath(candidate, roots) {
271
301
  export function apply(ctx, config = {}) {
272
302
  const cfg = config && typeof config === 'object' ? config : {};
273
303
  ALLOW_REMOTE = cfg.allowRemote === true;
304
+ // Media settings must be known before the default AndroidVm is constructed:
305
+ // camera/mic flags are part of the emulator launch argv.
306
+ const dataRoot = resolveRoots(ctx, cfg.roots)[0] || process.cwd();
307
+ const mediaSettings = loadMediaSettings(dataRoot, cfg);
308
+ const initialMedia = mediaLaunchOptions(mediaSettings);
274
309
  const vm = new AndroidVm({
275
310
  sdkRoot: cfg.sdkRoot || process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || undefined,
276
311
  adbPath: cfg.adbPath || undefined,
@@ -279,6 +314,8 @@ export function apply(ctx, config = {}) {
279
314
  serial: cfg.serial || undefined,
280
315
  port: cfg.port || undefined,
281
316
  emulatorArgs: Array.isArray(cfg.emulatorArgs) ? cfg.emulatorArgs : undefined,
317
+ extraEmulatorArgs: initialMedia.extraEmulatorArgs,
318
+ enableAudio: initialMedia.enableAudio,
282
319
  spawnEmulator: cfg.spawnEmulator !== false,
283
320
  apkRoots: Array.isArray(cfg.roots) ? cfg.roots : undefined,
284
321
  bootTimeoutMs: cfg.bootTimeoutMs || undefined,
@@ -315,6 +352,8 @@ export function apply(ctx, config = {}) {
315
352
  dnsServers: Array.isArray(cfg.dnsServers) ? cfg.dnsServers.map(String) : undefined,
316
353
  networkMode: cfg.networkMode || undefined,
317
354
  tcpdumpPath: cfg.tcpdumpPath || undefined,
355
+ // Read at create() time so a media change applies to the next instance.
356
+ mediaOptionsProvider: () => mediaLaunchOptions(mediaSettings),
318
357
  log: (line) => vm._pushLog(line),
319
358
  });
320
359
 
@@ -347,7 +386,6 @@ export function apply(ctx, config = {}) {
347
386
  });
348
387
  }
349
388
  let installInFlight = null;
350
- let remoteTunnel = null;
351
389
  let startKick = null;
352
390
  let autoStartKicked = false;
353
391
  // Provisioning completion gets its own one-shot kick: a partially configured host can
@@ -869,6 +907,189 @@ export function apply(ctx, config = {}) {
869
907
  const appRegistry = new InstalledAppRegistry({
870
908
  file: defaultInstalledAppsPath(rootsFor()[0] || process.cwd()),
871
909
  });
910
+ // Saved remote VM hosts (SSH profiles) + live remote sessions. The session
911
+ // manager owns tunnel/instance lifecycle and registers remote instances into
912
+ // the same instance list as local extras (see lib/remote-instance.js).
913
+ const remoteProfileBook = new RemoteProfileBook({
914
+ file: defaultRemoteProfilesPath(dataRoot),
915
+ });
916
+ const remoteManager = new RemoteSessionManager({
917
+ dataDir: dataRoot,
918
+ profiles: remoteProfileBook,
919
+ instances: instanceManager,
920
+ sdkRoot: vm.sdkRoot,
921
+ adbPath: vm.adbPath,
922
+ scrcpyJarPath: SCRCPY_JAR,
923
+ scrcpyMaxSize: cfg.scrcpyMaxSize || 960,
924
+ scrcpyBitrate: cfg.scrcpyBitrate || 6000000,
925
+ scrcpyMaxFps: cfg.scrcpyMaxFps || 60,
926
+ maxSessions: cfg.remoteMaxSessions || 4,
927
+ log: (line) => vm._pushLog(line),
928
+ });
929
+ // Sessions that received a file-loop virtual microphone; disconnect stops it.
930
+ const remoteMicSessions = new Set();
931
+
932
+ async function remoteState() {
933
+ const [state, listed] = await Promise.all([
934
+ remoteManager.remoteState(),
935
+ vm.listDevices().catch(() => ({ ok: false, devices: [] })),
936
+ ]);
937
+ const sessions = Array.isArray(state.sessions) ? state.sessions : [];
938
+ const profiles = Array.isArray(state.profiles) ? state.profiles : [];
939
+ return {
940
+ ...state,
941
+ ok: true,
942
+ counts: state.counts || {
943
+ sessions: sessions.length,
944
+ connected: sessions.filter((item) => item.state === 'connected').length,
945
+ },
946
+ // Legacy single-session aliases kept for older panel builds.
947
+ tunnel: sessions.length && sessions[0].tunnel ? sessions[0].tunnel : null,
948
+ launch: sessions.length ? sessions[0] : null,
949
+ profile: profiles[0] || null,
950
+ profileError: state.profilesError || null,
951
+ vm: await vm.status(),
952
+ devices: Array.isArray(listed.devices) ? listed.devices : [],
953
+ };
954
+ }
955
+
956
+ // Persisted virtual camera / microphone settings for the local default VM.
957
+ async function persistMediaSettings() {
958
+ try {
959
+ const target = mediaSettingsPath(dataRoot);
960
+ await fsp.mkdir(path.dirname(target), { recursive: true });
961
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
962
+ const payload = {
963
+ version: MEDIA_SETTINGS_VERSION,
964
+ updatedAt: new Date().toISOString(),
965
+ camera: mediaSettings.camera,
966
+ mic: mediaSettings.mic,
967
+ };
968
+ await fsp.writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
969
+ await fsp.rename(tmp, target);
970
+ return { ok: true };
971
+ } catch (error) {
972
+ return { ok: false, error: error && error.message ? error.message : String(error) };
973
+ }
974
+ }
975
+
976
+ function mediaStateBody() {
977
+ return {
978
+ ok: true,
979
+ version: MEDIA_SETTINGS_VERSION,
980
+ camera: mediaSettings.camera,
981
+ mic: mediaSettings.mic,
982
+ launch: mediaLaunchOptions(mediaSettings),
983
+ settingsPath: mediaSettingsPath(dataRoot),
984
+ capabilities: { camera: cameraCapabilities(), mic: micCapabilities() },
985
+ };
986
+ }
987
+
988
+ // Arm the current settings on every VM; a restart is what makes emulator
989
+ // launch flags (camera/mic) take effect, and the panel decides when to do it.
990
+ function applyMediaSettingsToDefaultVm() {
991
+ const media = mediaLaunchOptions(mediaSettings);
992
+ try {
993
+ vm.extraEmulatorArgs = media.extraEmulatorArgs;
994
+ vm.enableAudio = media.enableAudio === true;
995
+ } catch {
996
+ /* best effort */
997
+ }
998
+ let applied = 0;
999
+ try {
1000
+ applied = instanceManager.applyMediaOptions(media).applied;
1001
+ } catch {
1002
+ /* best effort */
1003
+ }
1004
+ return { ok: true, applied, media: { extraEmulatorArgs: media.extraEmulatorArgs, enableAudio: media.enableAudio } };
1005
+ }
1006
+
1007
+ async function restartDefaultVmForMedia() {
1008
+ try {
1009
+ await vm.stop();
1010
+ } catch {
1011
+ /* already stopped */
1012
+ }
1013
+ await vm.start();
1014
+ return { ok: true, vm: await vm.status() };
1015
+ }
1016
+
1017
+ // Media args for a remote headless launch (camera posters are rewritten to
1018
+ // remote paths before they are passed to the emulator command).
1019
+ function remoteLaunchMedia(config) {
1020
+ const source = config || mediaSettings;
1021
+ const launch = mediaLaunchOptions(source);
1022
+ const warnings = [];
1023
+ if (source.mic && source.mic.mode === 'file' && process.platform === 'win32') {
1024
+ warnings.push('file-loop microphone input needs a PulseAudio host; use host mode on Windows');
1025
+ }
1026
+ return { extraEmulatorArgs: launch.extraEmulatorArgs, enableAudio: launch.enableAudio, warnings };
1027
+ }
1028
+
1029
+ // Stream a local file to the remote host through the session's SSH profile.
1030
+ async function uploadToRemote(profile, localPath, remotePath) {
1031
+ const args = buildSshCommandArgs(profile, `mkdir -p ${quoteRemoteArg(path.posix.dirname(remotePath))} && cat > ${quoteRemoteArg(remotePath)}`);
1032
+ const data = await fsp.readFile(localPath);
1033
+ await new Promise((resolve, reject) => {
1034
+ const child = spawn('ssh', args, { stdio: ['pipe', 'ignore', 'pipe'], windowsHide: true });
1035
+ let stderr = '';
1036
+ child.stderr.on('data', (chunk) => {
1037
+ stderr = `${stderr}${chunk.toString('utf8')}`.slice(-8192);
1038
+ });
1039
+ child.on('error', reject);
1040
+ child.on('close', (code) => {
1041
+ if (code === 0) resolve();
1042
+ else reject(new Error((stderr.trim() || `ssh exited with code ${code}`).slice(0, 400)));
1043
+ });
1044
+ child.stdin.on('error', () => {});
1045
+ child.stdin.end(data);
1046
+ });
1047
+ }
1048
+
1049
+ function remoteMicEnv() {
1050
+ const media = remoteMediaPaths(dataRoot);
1051
+ const source = micSourceName(dataRoot);
1052
+ return { media, sourceName: source, sinkName: `${source}_sink`, rate: 48000, channels: 1 };
1053
+ }
1054
+
1055
+ // PulseAudio virtual microphone without sudo: loop the audio file into a
1056
+ // null-sink and remap its monitor to a real source (module-pipe-source is not
1057
+ // available on the reference remote host).
1058
+ function buildRemoteMicStartCommand(audioPath) {
1059
+ const env = remoteMicEnv();
1060
+ const q = (value) => quoteRemoteArg(value);
1061
+ const sourceArg = q(`source_name=${env.sourceName}`);
1062
+ const sinkArg = q(`sink_name=${env.sinkName}`);
1063
+ return [
1064
+ 'set -u',
1065
+ `mkdir -p -- ${q(env.media.dir)} ${q(env.media.audioDir)}`,
1066
+ `if [ -f ${q(env.media.pidFile)} ]; then kill "$(cat ${q(env.media.pidFile)})" 2>/dev/null || true; rm -f ${q(env.media.pidFile)}; fi`,
1067
+ `_idx=$(pactl list short modules 2>/dev/null | grep -F ${sourceArg} | cut -f1 | head -n 1); [ -n "$_idx" ] && pactl unload-module "$_idx" >/dev/null 2>&1 || true`,
1068
+ `_sink=$(pactl list short modules 2>/dev/null | grep -F ${sinkArg} | cut -f1 | head -n 1); [ -n "$_sink" ] && pactl unload-module "$_sink" >/dev/null 2>&1 || true`,
1069
+ `pactl load-module module-null-sink ${sinkArg} rate=${env.rate} channels=${env.channels} >/dev/null 2>&1 || exit 1`,
1070
+ `pactl load-module module-remap-source master=${q(env.sinkName + '.monitor')} ${sourceArg} channels=${env.channels} >/dev/null 2>&1 || exit 1`,
1071
+ `ffmpeg -nostdin -hide_banner -loglevel error -re -stream_loop -1 -i ${q(audioPath)} -f s16le -ar ${env.rate} -ac ${env.channels} - 2> ${q(env.media.logFile)} | pacat --playback --raw --format=s16le --rate=${env.rate} --channels=${env.channels} --device=${q(env.sinkName)} >/dev/null 2>&1 &`,
1072
+ `echo $! > ${q(env.media.pidFile)}`,
1073
+ 'sleep 1',
1074
+ `pactl set-default-source ${sourceArg} >/dev/null 2>&1 || true`,
1075
+ `pactl list short sources 2>/dev/null | cut -f2 | grep -Fx ${q(env.sourceName)} || exit 1`,
1076
+ ].join('\n');
1077
+ }
1078
+
1079
+ function buildRemoteMicStopCommand() {
1080
+ const env = remoteMicEnv();
1081
+ const q = (value) => quoteRemoteArg(value);
1082
+ const sourceArg = q(`source_name=${env.sourceName}`);
1083
+ const sinkArg = q(`sink_name=${env.sinkName}`);
1084
+ return [
1085
+ 'set -u',
1086
+ `if [ -f ${q(env.media.pidFile)} ]; then kill "$(cat ${q(env.media.pidFile)})" 2>/dev/null || true; sleep 1; kill -9 "$(cat ${q(env.media.pidFile)})" 2>/dev/null || true; rm -f ${q(env.media.pidFile)}; fi`,
1087
+ `_idx=$(pactl list short modules 2>/dev/null | grep -F ${sourceArg} | cut -f1 | head -n 1); [ -n "$_idx" ] && pactl unload-module "$_idx" >/dev/null 2>&1 || true`,
1088
+ `_sink=$(pactl list short modules 2>/dev/null | grep -F ${sinkArg} | cut -f1 | head -n 1); [ -n "$_sink" ] && pactl unload-module "$_sink" >/dev/null 2>&1 || true`,
1089
+ 'pactl set-default-source auto_null.monitor >/dev/null 2>&1 || true',
1090
+ ].join('\n');
1091
+ }
1092
+
872
1093
  const snapshotApk = () => (lastApk ? { ...lastApk } : null);
873
1094
 
874
1095
  function rememberInstalledApp(apkPath, meta, instanceId = 'default') {
@@ -1376,6 +1597,8 @@ export function apply(ctx, config = {}) {
1376
1597
  '/apk-vm/avd',
1377
1598
  '/apk-vm/devices',
1378
1599
  '/apk-vm/device',
1600
+ '/apk-vm/camera',
1601
+ '/apk-vm/mic',
1379
1602
  '/apk-vm/remote',
1380
1603
  '/apk-vm/vm',
1381
1604
  '/apk-vm/install',
@@ -1478,6 +1701,14 @@ export function apply(ctx, config = {}) {
1478
1701
  } else if (key === '/vm') {
1479
1702
  action = 'vm';
1480
1703
  summary = `VM ${activityText(b.action, 30) || 'request'}`;
1704
+ } else if (key === '/camera') {
1705
+ action = 'camera';
1706
+ const config = b.config && typeof b.config === 'object' ? b.config : b;
1707
+ summary = `camera ${activityText(b.action, 20) || 'save'} (back=${activityText(config.back, 20) || '?'})`;
1708
+ } else if (key === '/mic') {
1709
+ action = 'mic';
1710
+ const config = b.config && typeof b.config === 'object' ? b.config : b;
1711
+ summary = `mic ${activityText(b.action, 20) || 'save'} (${activityText(config.mode, 20) || '?'})`;
1481
1712
  } else if (key === '/install') {
1482
1713
  action = 'install';
1483
1714
  summary = `install ${activityText(String(b.path || '').split(/[\\/]/).pop(), 100) || 'APK'}`;
@@ -3072,9 +3303,111 @@ export function apply(ctx, config = {}) {
3072
3303
  sendJson(res, 200, { ok: true, attached: serial, vm: await vm.status(), devices: await vm.listDevices() });
3073
3304
  });
3074
3305
 
3306
+ // ---------------------------------------------------------------------
3307
+ // Virtual camera + microphone settings for the local default VM.
3308
+ //
3309
+ // The emulator only accepts these flags on (re)launch, so `save` persists
3310
+ // the settings and `apply` arms them for the next boot; `restart:true`
3311
+ // reboots the default VM immediately.
3312
+ // ---------------------------------------------------------------------
3313
+ register('/apk-vm/camera', async (req, res) => {
3314
+ if (req.method === 'GET') {
3315
+ sendJson(res, 200, mediaStateBody());
3316
+ return;
3317
+ }
3318
+ if (req.method !== 'POST') {
3319
+ sendError(res, 405, 'GET or POST only');
3320
+ return;
3321
+ }
3322
+ try {
3323
+ const body = await readJsonBody(req);
3324
+ const action = String(body.action || 'save').toLowerCase();
3325
+ if (action !== 'save' && action !== 'apply') {
3326
+ sendError(res, 400, `unsupported action: ${action}`);
3327
+ return;
3328
+ }
3329
+ const cameraSource =
3330
+ body.config && typeof body.config === 'object'
3331
+ ? body.config
3332
+ : body.camera && typeof body.camera === 'object'
3333
+ ? body.camera
3334
+ : body;
3335
+ mediaSettings.camera = normalizeCameraConfig(cameraSource);
3336
+ // Fail fast on missing/unreadable posters: the emulator would otherwise only print a
3337
+ // cryptic -virtualscene-poster error on the next (re)launch. Checked here so both
3338
+ // `save` and `apply` report the offending poster path.
3339
+ for (const poster of mediaSettings.camera.posters) {
3340
+ const checked = await checkPosterFile(poster.path);
3341
+ if (!checked || checked.ok !== true) {
3342
+ throw new Error(`camera poster "${poster.name}" is unavailable: ${(checked && checked.reason) || 'unknown error'}`);
3343
+ }
3344
+ }
3345
+ const saved = await persistMediaSettings();
3346
+ if (!saved.ok) throw new Error(saved.error);
3347
+ const applied = action === 'apply';
3348
+ if (applied) applyMediaSettingsToDefaultVm();
3349
+ const restarted = applied && body.restart === true;
3350
+ if (restarted) await restartDefaultVmForMedia();
3351
+ sendJson(res, 200, { ...mediaStateBody(), saved: true, applied, restarted });
3352
+ } catch (error) {
3353
+ sendError(res, 400, error && error.message ? error.message : String(error));
3354
+ }
3355
+ });
3356
+
3357
+ register('/apk-vm/mic', async (req, res) => {
3358
+ if (req.method === 'GET') {
3359
+ sendJson(res, 200, mediaStateBody());
3360
+ return;
3361
+ }
3362
+ if (req.method !== 'POST') {
3363
+ sendError(res, 405, 'GET or POST only');
3364
+ return;
3365
+ }
3366
+ try {
3367
+ const body = await readJsonBody(req);
3368
+ const action = String(body.action || 'save').toLowerCase();
3369
+ if (action !== 'save' && action !== 'apply') {
3370
+ sendError(res, 400, `unsupported action: ${action}`);
3371
+ return;
3372
+ }
3373
+ const micSource =
3374
+ body.config && typeof body.config === 'object'
3375
+ ? body.config
3376
+ : body.mic && typeof body.mic === 'object'
3377
+ ? body.mic
3378
+ : body;
3379
+ mediaSettings.mic = normalizeMicConfig(micSource);
3380
+ const saved = await persistMediaSettings();
3381
+ if (!saved.ok) throw new Error(saved.error);
3382
+ const applied = action === 'apply';
3383
+ if (applied) applyMediaSettingsToDefaultVm();
3384
+ const restarted = applied && body.restart === true;
3385
+ if (restarted) await restartDefaultVmForMedia();
3386
+ const warnings = [];
3387
+ if (!applied && mediaSettings.mic.mode === 'file' && process.platform === 'win32') {
3388
+ warnings.push('file-loop microphone input is only available on Linux/remote PulseAudio hosts; use host passthrough or an OBS/VB-Audio device on Windows');
3389
+ }
3390
+ if (applied && mediaSettings.mic.mode === 'file' && process.platform === 'win32') {
3391
+ warnings.push('file-loop microphone input is only available on Linux/remote PulseAudio hosts; use host passthrough or an OBS/VB-Audio device on Windows');
3392
+ }
3393
+ sendJson(res, 200, { ...mediaStateBody(), saved: true, applied, restarted, warnings });
3394
+ } catch (error) {
3395
+ sendError(res, 400, error && error.message ? error.message : String(error));
3396
+ }
3397
+ });
3398
+
3399
+ // ---------------------------------------------------------------------
3400
+ // Remote VM hosts over SSH.
3401
+ //
3402
+ // Every session is one SSH tunnel to a remote emulator's adb port plus one
3403
+ // remote instance registered in the same list as local extras. With
3404
+ // `launch` the fixed headless emulator command starts over SSH first; the
3405
+ // virtual camera posters and the virtual microphone payload travel with it.
3406
+ // Profiles are stored in <profile>/.apk-vm/remote-profiles.json (no keys).
3407
+ // ---------------------------------------------------------------------
3075
3408
  register('/apk-vm/remote', async (req, res) => {
3076
3409
  if (req.method === 'GET') {
3077
- sendJson(res, 200, { ok: true, tunnel: remoteTunnel ? remoteTunnel.status() : null });
3410
+ sendJson(res, 200, await remoteState());
3078
3411
  return;
3079
3412
  }
3080
3413
  if (req.method !== 'POST') {
@@ -3084,50 +3417,185 @@ export function apply(ctx, config = {}) {
3084
3417
  const body = await readJsonBody(req);
3085
3418
  const action = String(body.action || 'connect').toLowerCase();
3086
3419
  try {
3087
- if (action === 'disconnect') {
3088
- if (remoteTunnel) {
3089
- await remoteTunnel.stop();
3090
- remoteTunnel = null;
3420
+ if (action === 'status') {
3421
+ sendJson(res, 200, await remoteState());
3422
+ return;
3423
+ }
3424
+ if (action === 'save-profile') {
3425
+ const saved = await remoteManager.saveProfile(
3426
+ body.profile && typeof body.profile === 'object' ? body.profile : body,
3427
+ { id: body.id, name: body.name },
3428
+ );
3429
+ sendJson(res, 200, { ...(await remoteState()), saved: true, profileFile: saved.file });
3430
+ return;
3431
+ }
3432
+ if (action === 'forget-profile') {
3433
+ let removed = [];
3434
+ if (body.id) {
3435
+ const out = await remoteManager.forgetProfile(String(body.id));
3436
+ removed = out.removed || [];
3437
+ } else {
3438
+ const listed = await remoteManager.listProfiles().catch(() => ({ profiles: [] }));
3439
+ const profiles = Array.isArray(listed && listed.profiles) ? listed.profiles : [];
3440
+ for (const profile of profiles) {
3441
+ const out = await remoteManager.forgetProfile(String(profile.id));
3442
+ removed = removed.concat(out.removed || []);
3443
+ }
3444
+ }
3445
+ sendJson(res, 200, { ...(await remoteState()), saved: false, removed });
3446
+ return;
3447
+ }
3448
+ if (action === 'disconnect' || action === 'remove-session') {
3449
+ const sessions = await remoteManager.list();
3450
+ const ids = body.id ? [String(body.id)] : (sessions || []).map((session) => session.id);
3451
+ const removed = [];
3452
+ for (const sessionId of ids) {
3453
+ removed.push(action === 'remove-session'
3454
+ ? await remoteManager.removeSession(sessionId, { killRemote: body.stopEmulator === true })
3455
+ : await remoteManager.disconnectSession(sessionId, { killRemote: body.stopEmulator === true, remove: body.remove === true }));
3456
+ if (remoteMicSessions.has(sessionId)) {
3457
+ remoteMicSessions.delete(sessionId);
3458
+ const session = remoteManager.getSession(sessionId);
3459
+ if (session && session.profile) {
3460
+ await runSshCommand(session.profile, buildRemoteMicStopCommand(), { timeoutMs: 15000 }).catch(() => {});
3461
+ }
3462
+ }
3091
3463
  }
3092
- await stopScrcpy();
3093
- await vm.detachDevice();
3464
+ if (body.detachDevice !== false) await vm.detachDevice().catch(() => {});
3094
3465
  frame.buffer = null;
3095
3466
  frame.at = 0;
3096
- sendJson(res, 200, { ok: true, detached: true, tunnel: null, vm: await vm.status() });
3467
+ sendJson(res, 200, { ...(await remoteState()), detached: true, removed });
3097
3468
  return;
3098
3469
  }
3099
3470
  if (action !== 'connect') throw new Error(`unsupported remote action: ${action}`);
3100
- if (remoteTunnel) {
3101
- await remoteTunnel.stop();
3102
- remoteTunnel = null;
3103
- }
3104
- const tunnel = new SshAdbTunnel({
3105
- host: body.host,
3106
- user: body.user,
3107
- port: body.sshPort,
3108
- keyPath: body.keyPath,
3109
- remotePort: body.remotePort,
3110
- localPort: body.localPort,
3111
- sshPath: body.sshPath,
3112
- });
3113
- const started = await tunnel.start().catch(async (error) => {
3114
- await tunnel.stop();
3115
- throw error;
3471
+
3472
+ const profileInput = body.profile && typeof body.profile === 'object'
3473
+ ? body.profile
3474
+ : (body.profileId ? String(body.profileId) : body);
3475
+ let launchConfig = mediaSettings;
3476
+ const mediaNotes = [];
3477
+ let micPrepared = false;
3478
+ let launchPlan = { extraEmulatorArgs: [], enableAudio: false, warnings: [] };
3479
+ const launchRequested = body.launch === true;
3480
+ if (launchRequested) {
3481
+ let profileForUpload = null;
3482
+ try {
3483
+ const wanted = profileInput && typeof profileInput === 'object' && profileInput.host
3484
+ ? profileInput
3485
+ : (typeof profileInput === 'string' ? { id: profileInput } : profileInput);
3486
+ if (wanted && typeof wanted === 'object' && wanted.host) {
3487
+ profileForUpload = normalizeRemoteProfile(wanted);
3488
+ } else {
3489
+ const wantedId = typeof profileInput === 'string' ? profileInput : (body.profileId || null);
3490
+ if (wantedId) {
3491
+ const found = await remoteManager.getProfile(String(wantedId));
3492
+ if (found && found.ok && found.profile) profileForUpload = normalizeRemoteProfile(found.profile);
3493
+ }
3494
+ }
3495
+ } catch (error) {
3496
+ throw new Error(`remote profile is not usable: ${error.message}`);
3497
+ }
3498
+ if (profileForUpload) {
3499
+ const posters = Array.isArray(mediaSettings.camera && mediaSettings.camera.posters)
3500
+ ? mediaSettings.camera.posters
3501
+ : [];
3502
+ const remotePosters = [];
3503
+ for (const poster of posters.slice(0, 8)) {
3504
+ if (!poster || !poster.path) continue;
3505
+ try {
3506
+ const name = poster.name || 'poster';
3507
+ const rawExtension = (path.extname(poster.path).slice(1) || 'png').toLowerCase();
3508
+ const extension = rawExtension === 'jpg' || rawExtension === 'jpeg' ? rawExtension : 'png';
3509
+ const remotePath = remotePosterPath(dataRoot, name, extension);
3510
+ await uploadToRemote(profileForUpload, poster.path, remotePath);
3511
+ remotePosters.push({ name, path: remotePath });
3512
+ mediaNotes.push(`uploaded camera poster ${name}`);
3513
+ } catch (error) {
3514
+ launchPlan.warnings.push(`camera poster upload failed: ${error.message}`);
3515
+ }
3516
+ }
3517
+ if (remotePosters.length) {
3518
+ launchConfig = { ...mediaSettings, camera: { ...mediaSettings.camera, posters: remotePosters } };
3519
+ }
3520
+ const mic = mediaSettings.mic || { mode: 'off' };
3521
+ if (mic.mode === 'file' && mic.filePath) {
3522
+ try {
3523
+ const remoteAudio = remoteAudioPath(dataRoot, path.basename(mic.filePath));
3524
+ await uploadToRemote(profileForUpload, mic.filePath, remoteAudio);
3525
+ const started = await runSshCommand(profileForUpload, buildRemoteMicStartCommand(remoteAudio), { timeoutMs: 30000 });
3526
+ if (!started.ok) throw new Error((started.stderr || started.error || 'ssh command failed').slice(0, 300));
3527
+ micPrepared = true;
3528
+ mediaNotes.push(`started virtual microphone ${micSourceName(dataRoot)}`);
3529
+ } catch (error) {
3530
+ launchPlan.warnings.push(`virtual microphone setup failed: ${error.message}`);
3531
+ }
3532
+ }
3533
+ }
3534
+ launchPlan = { ...remoteLaunchMedia(launchConfig), warnings: launchPlan.warnings.concat(remoteLaunchMedia(launchConfig).warnings) };
3535
+ }
3536
+ const created = await remoteManager.createSession({
3537
+ profile: profileInput,
3538
+ options: {
3539
+ launch: launchRequested,
3540
+ avdName: body.avdName || undefined,
3541
+ consolePort: body.consolePort || undefined,
3542
+ remotePort: body.remotePort || undefined,
3543
+ localPort: body.localPort || undefined,
3544
+ extraEmulatorArgs: launchPlan.extraEmulatorArgs,
3545
+ enableAudio: launchPlan.enableAudio,
3546
+ attachInBackground: body.attachInBackground !== false,
3547
+ connectTimeoutMs: body.connectTimeoutMs || undefined,
3548
+ },
3116
3549
  });
3117
- remoteTunnel = tunnel;
3118
- try {
3119
- await stopScrcpy();
3120
- await vm.attachDevice(started.serial);
3121
- } catch (error) {
3122
- await tunnel.stop();
3123
- remoteTunnel = null;
3124
- throw error;
3550
+ if (body.saveProfile !== false) {
3551
+ try {
3552
+ await remoteManager.saveProfile(profileInput);
3553
+ } catch (error) {
3554
+ launchPlan.warnings.push(`could not save the remote profile: ${error.message}`);
3555
+ }
3125
3556
  }
3557
+ if (micPrepared) remoteMicSessions.add(created.id);
3126
3558
  frame.buffer = null;
3127
3559
  frame.at = 0;
3128
- sendJson(res, 200, { ok: true, tunnel: tunnel.status(), vm: await vm.status() });
3560
+ sendJson(res, 202, { ...(await remoteState()), session: created, media: mediaNotes, warnings: launchPlan.warnings });
3561
+ return;
3129
3562
  } catch (error) {
3130
- sendError(res, 400, error.message);
3563
+ sendError(res, 400, error && error.message ? error.message : String(error));
3564
+ }
3565
+ });
3566
+
3567
+ // ---------------------------------------------------------------------
3568
+ // Emulator inventory: every AVD/device this plugin can drive — local
3569
+ // AVDs + android devices + saved remote hosts — merged into one list.
3570
+ // ---------------------------------------------------------------------
3571
+ register('/apk-vm/emulators', async (req, res) => {
3572
+ if (req.method !== 'GET') {
3573
+ sendError(res, 405, 'GET only');
3574
+ return;
3575
+ }
3576
+ try {
3577
+ const running = (instanceManager ? instanceManager.list() : []).map((instance) => ({
3578
+ id: instance.id,
3579
+ avdName: instance.avdName,
3580
+ serial: instance.serial,
3581
+ kind: instance.kind || 'extra',
3582
+ state: instance.state,
3583
+ }));
3584
+ const local = await collectLocalInventory({
3585
+ emulatorPath: vm.emulatorPath || cfg.emulatorPath || undefined,
3586
+ adbPath: vm.adbPath || undefined,
3587
+ sdkRoot: vm.sdkRoot || cfg.sdkRoot || undefined,
3588
+ runningInstances: running,
3589
+ });
3590
+ const listed = await remoteManager.listProfiles().catch(() => ({ profiles: [] }));
3591
+ const profiles = Array.isArray(listed && listed.profiles) ? listed.profiles : [];
3592
+ const remotes = [];
3593
+ for (const profile of profiles) {
3594
+ remotes.push(await collectRemoteInventory({ profile }));
3595
+ }
3596
+ sendJson(res, 200, buildEmulatorInventory({ local, remotes }));
3597
+ } catch (error) {
3598
+ sendError(res, 500, error && error.message ? error.message : String(error));
3131
3599
  }
3132
3600
  });
3133
3601
 
@@ -3903,6 +4371,7 @@ export function apply(ctx, config = {}) {
3903
4371
  for (const id of [...extraRouteDisposers.keys()]) disposeExtraRouteSet(id);
3904
4372
  for (const bridge of cdpBridges.values()) void bridge.close().catch(() => {});
3905
4373
  cdpBridges.clear();
4374
+ void remoteManager.dispose().catch(() => {});
3906
4375
  void instanceManager?.dispose?.();
3907
4376
  for (const dispose of disposers.reverse()) {
3908
4377
  try {
@@ -3919,14 +4388,6 @@ export function apply(ctx, config = {}) {
3919
4388
  host.effect(() => mountRoutes(host.webServer), 'dsh-apk-vm: http routes');
3920
4389
  });
3921
4390
 
3922
- ctx.effect(() => {
3923
- return () => {
3924
- const tunnel = remoteTunnel;
3925
- remoteTunnel = null;
3926
- if (tunnel) void tunnel.stop().catch(() => {});
3927
- };
3928
- }, 'dsh-apk-vm: ssh tunnel');
3929
-
3930
4391
  // Optional warm start: boot the VM right after the plugin activates so the
3931
4392
  // first panel/tab open lands on a running (or nearly booted) device. This is
3932
4393
  // what makes the visible "open the VM" step effectively instant; opt in with