dsh-apk-vm 0.12.4 → 0.12.5

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/client.js CHANGED
@@ -30,7 +30,7 @@ window.__ModuleLoader__.load({
30
30
  var SWIPE_THRESHOLD_PX = 24;
31
31
  var FRAME_INTERVAL_MS = 500;
32
32
  var STATE_INTERVAL_MS = 2000;
33
- var CLIENT_VERSION = '0.12.4';
33
+ var CLIENT_VERSION = '0.12.5';
34
34
 
35
35
  /* ------------------------------------------------------------------ *
36
36
  * Optional dsh-better-sidebar integration.
@@ -400,7 +400,14 @@ window.__ModuleLoader__.load({
400
400
  'grid.close': 'Close grid',
401
401
  'instances.stop': 'Stop',
402
402
  'instances.stopped': 'Stopped instance {id}',
403
+ 'instances.start': 'Start',
404
+ 'instances.started': 'Started instance {id}',
403
405
  'instances.idle': 'idle {seconds}s',
406
+ 'instances.hostMemory': 'Host memory: {free} free of {total}',
407
+ 'instances.cap': 'instance cap {effective}/{requested}',
408
+ 'instances.lite': 'lite mode',
409
+ 'instances.profileInfo': '{ram} MB RAM · {cores} CPU',
410
+ 'setup.retrying': 'retry {attempt}/{max} in {seconds}s',
404
411
  'devices.title': 'Physical/remote adb device',
405
412
  'devices.select': 'Select device…',
406
413
  'devices.attach': 'Attach',
@@ -806,7 +813,14 @@ window.__ModuleLoader__.load({
806
813
  'grid.close': '关闭网格',
807
814
  'instances.stop': '停止',
808
815
  'instances.stopped': '已停止实例 {id}',
816
+ 'instances.start': '启动',
817
+ 'instances.started': '已启动实例 {id}',
809
818
  'instances.idle': '空闲 {seconds}s',
819
+ 'instances.hostMemory': '主机内存:可用 {free} / 共 {total}',
820
+ 'instances.cap': '实例上限 {effective}/{requested}',
821
+ 'instances.lite': '轻量模式',
822
+ 'instances.profileInfo': '{ram} MB 内存 · {cores} 核',
823
+ 'setup.retrying': '重试 {attempt}/{max},{seconds} 秒后',
810
824
  'devices.title': '物理/远程 adb 设备',
811
825
  'devices.select': '选择设备…',
812
826
  'devices.attach': '连接',
@@ -1193,6 +1207,8 @@ window.__ModuleLoader__.load({
1193
1207
  apk: apk,
1194
1208
  client: isObject(data.client) ? data.client : null,
1195
1209
  origin: typeof data.origin === 'string' && data.origin ? data.origin : '',
1210
+ memory: isObject(data.memory) ? data.memory : null,
1211
+ multiInstance: data.multiInstance === true,
1196
1212
  };
1197
1213
  }
1198
1214
 
@@ -2789,6 +2805,26 @@ window.__ModuleLoader__.load({
2789
2805
  var displayState = snapshot ? snapshot.vm.state : stateError ? 'error' : 'loading';
2790
2806
  var stateLabel = T('state.' + displayState);
2791
2807
  var ready = displayState === 'ready';
2808
+ // Host memory / lite-mode profile reported by GET /apk-vm/state.
2809
+ var memoryInfo = snapshot && isObject(snapshot.memory) ? snapshot.memory : null;
2810
+ var memoryHost = memoryInfo && isObject(memoryInfo.host) ? memoryInfo.host : null;
2811
+ var memoryProfile = memoryInfo && isObject(memoryInfo.profile) ? memoryInfo.profile : null;
2812
+ var memoryEffective = memoryInfo && Number.isFinite(Number(memoryInfo.effectiveMaxInstances)) ? Math.max(1, Math.round(Number(memoryInfo.effectiveMaxInstances))) : null;
2813
+ var memoryRequested = memoryInfo && Number.isFinite(Number(memoryInfo.requestedMaxInstances)) ? Math.max(1, Math.round(Number(memoryInfo.requestedMaxInstances))) : null;
2814
+ var memoryFreeMb = memoryHost && Number.isFinite(Number(memoryHost.freeMb)) ? Math.max(0, Math.round(Number(memoryHost.freeMb))) : null;
2815
+ var memoryTotalMb = memoryHost && Number.isFinite(Number(memoryHost.totalMb)) ? Math.max(0, Math.round(Number(memoryHost.totalMb))) : null;
2816
+ var memoryLimited = Boolean(memoryInfo && memoryInfo.limited === true);
2817
+ var memoryProfileName = memoryProfile && typeof memoryProfile.name === 'string' ? memoryProfile.name : '';
2818
+ var formatMemoryMb = function (mb) {
2819
+ if (mb === null) return 'n/a';
2820
+ return mb >= 1024 ? (mb / 1024).toFixed(1) + ' GB' : mb + ' MB';
2821
+ };
2822
+ var memoryLineText = memoryFreeMb !== null && memoryTotalMb !== null
2823
+ ? T('instances.hostMemory', { free: formatMemoryMb(memoryFreeMb), total: formatMemoryMb(memoryTotalMb) })
2824
+ : '';
2825
+ var memoryCapText = memoryEffective !== null
2826
+ ? T('instances.cap', { effective: memoryEffective, requested: memoryRequested || memoryEffective })
2827
+ : '';
2792
2828
  var targetFps =
2793
2829
  snapshot && isObject(snapshot.stream) && Number(snapshot.stream.fps) > 0
2794
2830
  ? Math.min(10, Math.max(1, Math.round(Number(snapshot.stream.fps))))
@@ -3552,6 +3588,25 @@ window.__ModuleLoader__.load({
3552
3588
  });
3553
3589
  }
3554
3590
 
3591
+ function startInstanceById(id) {
3592
+ if (!id || id === 'default' || instanceBusy) return;
3593
+ setInstanceBusy(true);
3594
+ requestJson('/apk-vm/instances/' + encodeURIComponent(id) + '/vm', {
3595
+ method: 'POST',
3596
+ body: JSON.stringify({ action: 'start' }),
3597
+ }, T).then(function (result) {
3598
+ if (!mountedRef.current) return;
3599
+ setInstanceBusy(false);
3600
+ if (!result.ok) {
3601
+ pushToast('error', (result.error || T('err.action')).slice(0, 400));
3602
+ return;
3603
+ }
3604
+ pushToast('success', T('instances.started', { id: id }));
3605
+ loadInstances();
3606
+ loadState();
3607
+ });
3608
+ }
3609
+
3555
3610
  function renameInstanceById(id) {
3556
3611
  if (!id || instanceBusy) return;
3557
3612
  var entry = null;
@@ -4414,6 +4469,12 @@ window.__ModuleLoader__.load({
4414
4469
  ? ''
4415
4470
  : autoPercent.toFixed(0) + '%' +
4416
4471
  (autoReceived !== null && autoTotal !== null ? ' · ' + autoMb(autoReceived) + ' / ' + autoMb(autoTotal) : '');
4472
+ var autoAttempt = autoDetail && Number.isFinite(Number(autoDetail.attempt)) ? Math.max(1, Math.round(Number(autoDetail.attempt))) : 1;
4473
+ var autoMaxAttempts = autoDetail && Number.isFinite(Number(autoDetail.maxAttempts)) ? Math.max(autoAttempt, Math.round(Number(autoDetail.maxAttempts))) : 0;
4474
+ var autoRetryDelayMs = autoDetail && Number.isFinite(Number(autoDetail.nextDelayMs)) ? Math.max(0, Math.round(Number(autoDetail.nextDelayMs))) : 0;
4475
+ var autoRetryText = autoAttempt > 1
4476
+ ? T('setup.retrying', { attempt: autoAttempt, max: autoMaxAttempts || autoAttempt, seconds: Math.max(1, Math.round(autoRetryDelayMs / 1000)) })
4477
+ : '';
4417
4478
  var autoRunning = autoSetupStateName === 'running';
4418
4479
  var autoReadyKey = autoSetup && autoSetup.finishedAt ? 'ready:' + String(autoSetup.finishedAt) : 'ready';
4419
4480
 
@@ -5564,7 +5625,7 @@ window.__ModuleLoader__.load({
5564
5625
  className: 'apkvm-dim',
5565
5626
  style: { flex: '1 1 auto', minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
5566
5627
  },
5567
- autoProgressText + (autoMessage ? ' · ' + autoMessage : '') + (autoProgressSuffix ? ' · ' + autoProgressSuffix : '')
5628
+ autoProgressText + (autoMessage ? ' · ' + autoMessage : '') + (autoProgressSuffix ? ' · ' + autoProgressSuffix : '') + (autoRetryText ? ' · ' + autoRetryText : '')
5568
5629
  ),
5569
5630
  actionBtn(T('setup.autoCancel'), {
5570
5631
  key: 'auto-setup-cancel',
@@ -5945,12 +6006,23 @@ window.__ModuleLoader__.load({
5945
6006
  'summary',
5946
6007
  { className: 'apkvm-debug-summary' },
5947
6008
  h('span', { className: 'apkvm-card-title' }, T('instances.manage')),
5948
- h('span', { className: 'apkvm-dim', style: { marginLeft: 'auto' } }, String(instancesList.length)),
6009
+ h(
6010
+ 'span',
6011
+ { className: 'apkvm-dim', style: { marginLeft: 'auto' }, title: [memoryLineText, memoryCapText, memoryProfileName === 'lite' ? T('instances.lite') : ''].filter(Boolean).join(' · ') },
6012
+ String(instancesList.length) + (memoryCapText ? ' · ' + memoryCapText : '')
6013
+ ),
5949
6014
  h('span', { className: 'apkvm-chevron', 'aria-hidden': 'true' }, '▸')
5950
6015
  ),
5951
6016
  h(
5952
6017
  'div',
5953
6018
  { className: 'apkvm-instlist' },
6019
+ memoryLineText || memoryCapText || memoryProfileName === 'lite'
6020
+ ? h(
6021
+ 'div',
6022
+ { className: 'apkvm-dim', style: { padding: '0 2px 2px', whiteSpace: 'normal', overflow: 'visible' } },
6023
+ [memoryLineText, memoryCapText, memoryProfileName === 'lite' ? T('instances.lite') : '', memoryLimited ? '⚠' : ''].filter(Boolean).join(' · ')
6024
+ )
6025
+ : null,
5954
6026
  instancesList.map(function (entry) {
5955
6027
  var isDefault = entry.id === 'default';
5956
6028
  var ownerInfo = entry.ownerInfo && isObject(entry.ownerInfo) ? entry.ownerInfo : null;
@@ -5973,7 +6045,14 @@ window.__ModuleLoader__.load({
5973
6045
  h(
5974
6046
  'div',
5975
6047
  { className: 'apkvm-instmeta' },
5976
- idle !== null && !isDefault ? T('instances.idle', { seconds: idle }) : ''
6048
+ [
6049
+ Number(entry.ramSizeMb) > 0 || Number(entry.cores) > 0
6050
+ ? T('instances.profileInfo', { ram: Number(entry.ramSizeMb) || '?', cores: Number(entry.cores) || '?' })
6051
+ : isDefault && memoryProfile && (Number(memoryProfile.ramSizeMb) > 0 || Number(memoryProfile.cores) > 0)
6052
+ ? T('instances.profileInfo', { ram: Number(memoryProfile.ramSizeMb) || '?', cores: Number(memoryProfile.cores) || '?' })
6053
+ : '',
6054
+ idle !== null && !isDefault ? T('instances.idle', { seconds: idle }) : '',
6055
+ ].filter(Boolean).join(' · ')
5977
6056
  ),
5978
6057
  h(
5979
6058
  'div',
@@ -5993,19 +6072,33 @@ window.__ModuleLoader__.load({
5993
6072
  ),
5994
6073
  isDefault
5995
6074
  ? null
5996
- : h(
5997
- 'button',
5998
- {
5999
- type: 'button',
6000
- className: 'apkvm-mini',
6001
- title: T('instances.stop'),
6002
- onClick: function (event) {
6003
- event.preventDefault();
6004
- stopInstanceById(entry.id);
6075
+ : entry.state === 'ready' || entry.state === 'booting' || entry.state === 'starting'
6076
+ ? h(
6077
+ 'button',
6078
+ {
6079
+ type: 'button',
6080
+ className: 'apkvm-mini',
6081
+ title: T('instances.stop'),
6082
+ onClick: function (event) {
6083
+ event.preventDefault();
6084
+ stopInstanceById(entry.id);
6085
+ },
6005
6086
  },
6006
- },
6007
- T('instances.stop')
6008
- ),
6087
+ T('instances.stop')
6088
+ )
6089
+ : h(
6090
+ 'button',
6091
+ {
6092
+ type: 'button',
6093
+ className: 'apkvm-mini',
6094
+ title: T('instances.start'),
6095
+ onClick: function (event) {
6096
+ event.preventDefault();
6097
+ startInstanceById(entry.id);
6098
+ },
6099
+ },
6100
+ T('instances.start')
6101
+ ),
6009
6102
  isDefault
6010
6103
  ? null
6011
6104
  : h(
package/cordis.patch.yml CHANGED
@@ -45,6 +45,21 @@
45
45
  # quick reuse. start()/the next Agent action boots it again.
46
46
  instanceIdleMs: 900000
47
47
  instanceReapIntervalMs: 60000
48
+ # Host memory guard: refuse to start another local VM when the machine is
49
+ # low on memory, and cap the effective instance count from total RAM.
50
+ # A local emulator costs ~2-3 GB (AVD 1.5 GB + qemu/GPU overhead), so
51
+ # with 4 GB reserved for the host this allows 2 VMs on 16 GB and 1 on
52
+ # 8 GB (clamped to 1..8). Remote sessions do not count.
53
+ memoryGuard: true
54
+ # hostReserveMb: 4096
55
+ # estimatedVmMb: 3072
56
+ # Lite mode: smaller AVD hardware profile for memory-constrained hosts
57
+ # (1 GB guest RAM, 2 vCPU, SwiftShader GPU, 1 fps PNG / 720p30 H.264).
58
+ # Applies to the default AVD and to extra instances. standard | lite.
59
+ vmPreset: standard
60
+ # When memory is tight, stop the least recently used idle local VM
61
+ # before creating another one (extra VMs are stopped, never destroyed).
62
+ memoryPressureReap: true
48
63
  # H.264 stream: up to 60 fps via the vendored scrcpy server; 960 keeps
49
64
  # 540x960 video (plenty for the panel) so software WebCodecs decode can
50
65
  # sustain ~60 fps.
@@ -77,6 +92,29 @@
77
92
  # Manual (user-triggered only) system-image download from the
78
93
  # Environment card; autoSetup does not need this flag.
79
94
  allowSetupDownloads: false
95
+ # Download reliability for the zero-config first run: every provisioning
96
+ # step retries transient network failures with exponential backoff
97
+ # (setupRetries, retryDelayMs), no-data stalls are detected by a 45 s
98
+ # no-progress watchdog on the JDK/command-line-tools downloads, and the
99
+ # cumulative free-disk budget is checked before provisioning starts.
100
+ setupRetries: 3
101
+ retryDelayMs: 2000
102
+ # minFreeDiskBytes: 6442450944
103
+ # Optional mirrors/proxies for the Android SDK command-line tools and
104
+ # sdkmanager (the JDK already has jdkMirror). sdkManagerArgs are passed
105
+ # verbatim to sdkmanager; networkProxy becomes --proxy_* flags and is
106
+ # used only by sdkmanager, never by the plugin itself. commandLineToolsUrl
107
+ # overrides the Google command-line-tools archive.
108
+ # commandLineToolsUrl: 'https://example.com/commandlinetools-win-latest.zip'
109
+ # commandLineToolsSha256: '...'
110
+ # sdkManagerArgs: ['--no_https']
111
+ # sdkManagerEnv:
112
+ # SDK_TEST_BASE_URL: 'https://mirror.example.com/android/repository/'
113
+ # networkProxy:
114
+ # host: 127.0.0.1
115
+ # port: 7890
116
+ # user: ''
117
+ # password: ''
80
118
  # The VM routes accept root shell/debug actions, so they reject
81
119
  # non-loopback clients by default even if the DSH web UI is exposed to
82
120
  # the LAN. Set true only behind your own authenticated reverse proxy.
package/docs/AGENTS.md CHANGED
@@ -142,6 +142,26 @@ by another conversation returns `vm-busy` unless you force a takeover (`ownerFor
142
142
  - Each instance has its own WebSocket (`/apk-vm/instances/<id>/ws`), unless the panel falls back
143
143
  to PNG frames.
144
144
 
145
+ ## Host memory, Lite mode and instance caps
146
+
147
+ A local emulator costs roughly 2–3 GB of host RAM. With `memoryGuard` on (the default) the
148
+ effective `maxInstances` is derived from total host RAM (`hostReserveMb` 4 GB reserve,
149
+ `estimatedVmMb` 3 GB per VM): **8 GB → 1 VM, 16 GB → 3 with the default requested cap,
150
+ 32 GB+ → 3**. A 16 GB desktop that also runs an IDE and a browser is happier with
151
+ `maxInstances: 2`, or with `vmPreset: lite` (1 GB guest RAM / 2 vCPU / SwiftShader / 720p30),
152
+ which can fit a third VM.
153
+
154
+ - `create_instance` / local starts can fail with a `host memory guard` error: stop an idle
155
+ instance, lower `maxInstances`, or pass `memoryOverride: true` when you knowingly
156
+ over-commit.
157
+ - `memoryPressureReap` (on by default) stops the least-recently-used idle local VM when free
158
+ host memory is low; extra VMs are only stopped, never destroyed.
159
+ - `list_instances`, `GET /apk-vm/state` and `/apk-vm/emulators` expose the same `memory`
160
+ object: `effectiveMaxInstances`, `requestedMaxInstances`, `limited`, `host.freeMb/totalMb`,
161
+ the active `profile` and `pressureReap`.
162
+ - The guard estimates from host totals: an emulator started outside the plugin, and remote
163
+ sessions, are not counted. Use Lite mode on 8–16 GB hosts when running several agents.
164
+
145
165
  ## VM names and per-conversation selection
146
166
 
147
167
  - Every VM can have a human-friendly display name; ids stay stable (`default`, `frontend`,
package/docs/PRIVACY.md CHANGED
@@ -50,7 +50,11 @@ reporting, advertising or a remote backend.
50
50
  base. Every archive is verified against Adoptium's published SHA-256 checksum; the plugin sends
51
51
  no identifying headers, cookies or user data. It then runs the user's own `sdkmanager` for the
52
52
  Android SDK command-line tools, build-tools, platform and system image from the official Google
53
- Android SDK repository. The plugin does not proxy or collect those downloads. Those downloads
53
+ Android SDK repository. The plugin does not proxy or collect those downloads. Optional
54
+ overrides (`jdkMirror`, `commandLineToolsUrl`/`commandLineToolsSha256`, `sdkManagerArgs`,
55
+ `sdkManagerEnv`, `networkProxy`) only redirect the plugin's own downloader and the
56
+ `sdkmanager` child process to a user-chosen mirror or proxy; proxy credentials passed this way
57
+ are used only for that child process and are never logged. Those downloads
54
58
  are size- and time-bounded and HTTPS-only, and can be disabled with `autoSetup: false` (the
55
59
  Environment card then offers the manual actions as before). No analytics, telemetry,
56
60
  advertising or remote backend is involved, and no third-party endpoint other than the ones
package/docs/RELEASING.md CHANGED
@@ -8,12 +8,13 @@ Repository: <https://github.com/yuxiaole-bili/dsh-apk-vm>.
8
8
  ## Publish to npm
9
9
 
10
10
  The package is intentionally public and has no build step; publishing the repository directory is
11
- enough:
11
+ enough. **The default registry on the reference host is a mirror (`registry.npmmirror.com`);
12
+ publishing must target npm explicitly**, otherwise `npm publish` fails with `E404`:
12
13
 
13
14
  ```bash
14
- npm login # once per machine, as the npm account that owns dsh-apk-vm
15
- npm publish --access public # prepublish uses the packed file list
16
- npm view dsh-apk-vm version # verify the published version
15
+ npm whoami --registry=https://registry.npmjs.org # once per machine/account
16
+ npm publish --access public --registry=https://registry.npmjs.org
17
+ npm view dsh-apk-vm version --registry=https://registry.npmjs.org # verify
17
18
  ```
18
19
 
19
20
  The GitHub release tarball and the npm tarball are produced from the same `npm pack` output.
@@ -78,7 +79,10 @@ The in-app Plugin Manager title/description comes from `locale/en.json` and `loc
78
79
 
79
80
  ## Versioning
80
81
 
81
- - `package.json` and `CHANGELOG.md` move together.
82
+ - `package.json`, `CHANGELOG.md` and `CHANGELOG.zh-CN.md` move together (the Chinese file mirrors
83
+ the 0.12.x entries; the pre-0.12 history stays English-only in `CHANGELOG.md`).
84
+ - `client.js` `CLIENT_VERSION` must match `package.json`; `npm run check` runs
85
+ `scripts/check-version.mjs` and fails the release if they disagree.
82
86
  - Use `0.x.y` while the plugin API/route surface may still change.
83
87
  - Keep `SECURITY.md` supported-version table in sync.
84
88
  - Tag the release (`git tag -a v0.3.12 -m ...`) and attach the tarball produced by
@@ -94,6 +98,8 @@ The in-app Plugin Manager title/description comes from `locale/en.json` and `loc
94
98
  - [ ] Demo media (if any) recorded on a real host and listed in `docs/README.md`
95
99
  - [ ] README install instructions use `<path-to-repo>` / user-chosen paths
96
100
  - [ ] Release notes call out known limitations (Windows E2E only, no audio, etc.)
101
+ - [ ] `CHANGELOG.zh-CN.md` updated for the release (0.12.5+ promise; keep it in sync with
102
+ `CHANGELOG.md`)
97
103
 
98
104
  ## Known limitations to state in the release
99
105
 
package/index.js CHANGED
@@ -121,6 +121,28 @@ function loadMediaSettings(dataRoot, cfg) {
121
121
  }
122
122
  }
123
123
 
124
+ /**
125
+ * Optional AVD hardware profile ("lite" mode) for memory-constrained hosts.
126
+ * A null result means "standard": the existing defaults are kept untouched.
127
+ * InstanceManager normalizes the same setting for extra instances.
128
+ */
129
+ const VM_PRESET_LITE = Object.freeze({
130
+ name: 'lite',
131
+ ramSizeMb: 1024,
132
+ cores: 2,
133
+ gpuMode: 'swiftshader_indirect',
134
+ frameFps: 1,
135
+ scrcpyMaxSize: 720,
136
+ scrcpyMaxFps: 30,
137
+ });
138
+
139
+ function normalizeVmPreset(value) {
140
+ if (!value || value === 'standard') return null;
141
+ if (value === 'lite') return VM_PRESET_LITE;
142
+ if (typeof value === 'object' && !Array.isArray(value)) return { name: 'custom', ...value };
143
+ return null;
144
+ }
145
+
124
146
  function isReady(vm) {
125
147
  return vm && vm.state === 'ready';
126
148
  }
@@ -329,6 +351,12 @@ export function apply(ctx, config = {}) {
329
351
  const dataRoot = resolveRoots(ctx, cfg.roots)[0] || process.cwd();
330
352
  const mediaSettings = loadMediaSettings(dataRoot, cfg);
331
353
  const initialMedia = mediaLaunchOptions(mediaSettings);
354
+ // Lite mode is applied to the default VM as well: GPU + frame rate are part
355
+ // of the AndroidVm options (the AVD RAM/CPU profile is patched separately),
356
+ // while extra instances get the same profile from InstanceManager.
357
+ const vmPreset = normalizeVmPreset(cfg.vmPreset);
358
+ const presetGpuMode = vmPreset && typeof vmPreset.gpuMode === 'string' ? vmPreset.gpuMode : null;
359
+ const presetFrameFps = vmPreset && Number.isFinite(Number(vmPreset.frameFps)) ? Number(vmPreset.frameFps) : null;
332
360
  const vm = new AndroidVm({
333
361
  sdkRoot: cfg.sdkRoot || process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || undefined,
334
362
  adbPath: cfg.adbPath || undefined,
@@ -343,7 +371,7 @@ export function apply(ctx, config = {}) {
343
371
  apkRoots: Array.isArray(cfg.roots) ? cfg.roots : undefined,
344
372
  bootTimeoutMs: cfg.bootTimeoutMs || undefined,
345
373
  // Fast-boot strategy: host GPU + hypervisor detection + quick-boot snapshots.
346
- gpuMode: cfg.gpuMode || undefined,
374
+ gpuMode: presetGpuMode || cfg.gpuMode || undefined,
347
375
  accel: cfg.accel || undefined,
348
376
  requireAccel: cfg.requireAccel !== false,
349
377
  quickBoot: cfg.quickBoot !== false,
@@ -365,6 +393,12 @@ export function apply(ctx, config = {}) {
365
393
  baseAvdName: cfg.avdName || 'dsh_apk',
366
394
  namesFile: defaultInstanceNamesPath(dataRoot),
367
395
  maxInstances: cfg.maxInstances || 3,
396
+ // Memory guard + optional lite hardware profile (see lib/memory.js).
397
+ vmPreset: cfg.vmPreset || 'standard',
398
+ memoryGuard: cfg.memoryGuard !== false,
399
+ hostReserveMb: cfg.hostReserveMb,
400
+ estimatedVmMb: cfg.estimatedVmMb,
401
+ memoryPressureReap: cfg.memoryPressureReap !== false,
368
402
  gpuMode: cfg.gpuMode || 'host',
369
403
  snapshotName: cfg.snapshotName || 'default_boot',
370
404
  scrcpyJarPath: SCRCPY_JAR,
@@ -388,6 +422,9 @@ export function apply(ctx, config = {}) {
388
422
  let disposeInstanceRoutes = null;
389
423
  const flowRecorder = new FlowRecorder();
390
424
  const cdpBridges = new Map();
425
+ // Lite mode: keep the default AVD small on memory-constrained hosts. Fire and
426
+ // forget — a missing AVD is normal before auto-setup runs.
427
+ void applyVmPresetToDefaultAvd();
391
428
  if (instanceManager) {
392
429
  instanceManager.onCreated = (id) => {
393
430
  registerInstanceRoutes?.(id);
@@ -418,7 +455,7 @@ export function apply(ctx, config = {}) {
418
455
  const frame = { buffer: null, at: 0, inFlight: null, receivedAt: [] };
419
456
  const screen = { value: null, at: 0 };
420
457
  const preferAutoStart = cfg.autoStart !== false;
421
- let streamFps = Number.isFinite(Number(cfg.frameFps)) ? Math.min(10, Math.max(1, Math.round(Number(cfg.frameFps)))) : 2;
458
+ let streamFps = Number.isFinite(Number(presetFrameFps || cfg.frameFps)) ? Math.min(10, Math.max(1, Math.round(Number(presetFrameFps || cfg.frameFps)))) : 2;
422
459
 
423
460
  function measuredFrameFps() {
424
461
  const now = Date.now();
@@ -571,6 +608,52 @@ export function apply(ctx, config = {}) {
571
608
  }
572
609
  }
573
610
 
611
+ /**
612
+ * SDK download/install knobs shared by auto-setup and the manual panel steps.
613
+ * These map straight onto lib/setup.js options; unknown/empty values are left
614
+ * untouched so the defaults keep working.
615
+ */
616
+ function provisionNetworkOptions() {
617
+ const options = {};
618
+ if (Array.isArray(cfg.sdkManagerArgs) && cfg.sdkManagerArgs.length) options.sdkManagerArgs = cfg.sdkManagerArgs.map(String);
619
+ if (cfg.sdkManagerEnv && typeof cfg.sdkManagerEnv === 'object' && !Array.isArray(cfg.sdkManagerEnv)) options.sdkManagerEnv = cfg.sdkManagerEnv;
620
+ if (cfg.networkProxy && typeof cfg.networkProxy === 'object' && !Array.isArray(cfg.networkProxy)) options.networkProxy = cfg.networkProxy;
621
+ if (typeof cfg.commandLineToolsUrl === 'string' && cfg.commandLineToolsUrl) options.commandLineToolsUrl = cfg.commandLineToolsUrl;
622
+ if (typeof cfg.commandLineToolsSha256 === 'string' && cfg.commandLineToolsSha256) options.commandLineToolsSha256 = cfg.commandLineToolsSha256;
623
+ return options;
624
+ }
625
+
626
+ /**
627
+ * Lite mode patches the default AVD too (extra instances get the profile from
628
+ * InstanceManager). config.ini is plain text and is read at the next boot, so
629
+ * this is best-effort: a missing AVD just means setup has not created it yet.
630
+ */
631
+ async function applyVmPresetToDefaultAvd() {
632
+ try {
633
+ if (!vmPreset) return;
634
+ const ramSizeMb = Number(vmPreset.ramSizeMb);
635
+ const cores = Number(vmPreset.cores);
636
+ if (!Number.isFinite(ramSizeMb) && !Number.isFinite(cores)) return;
637
+ const avdHome = process.env.ANDROID_AVD_HOME || path.join(os.homedir(), '.android', 'avd');
638
+ const avd = String(cfg.avdName || 'dsh_apk');
639
+ const configPath = path.join(avdHome, `${avd}.avd`, 'config.ini');
640
+ if (!existsSync(configPath)) return;
641
+ let text = readFileSync(configPath, 'utf8');
642
+ if (!text.endsWith('\n')) text += '\n';
643
+ const setKey = (key, value) => {
644
+ const line = `${key}=${value}`;
645
+ const pattern = new RegExp(`^${key}=.*$`, 'm');
646
+ text = pattern.test(text) ? text.replace(pattern, line) : `${text}${line}\n`;
647
+ };
648
+ if (Number.isFinite(ramSizeMb) && ramSizeMb > 0) setKey('hw.ramSize', String(Math.round(ramSizeMb)));
649
+ if (Number.isFinite(cores) && cores > 0) setKey('hw.cpu.ncore', String(Math.round(cores)));
650
+ await fsp.writeFile(configPath, text, 'utf8');
651
+ vm._pushLog(`applied the ${vmPreset.name || 'custom'} VM preset to the default AVD ${avd}`);
652
+ } catch (error) {
653
+ vm._pushLog(`applying the VM preset to the default AVD failed: ${error && error.message ? error.message : error}`);
654
+ }
655
+ }
656
+
574
657
  function buildAutoSetup(enabled) {
575
658
  return createAutoSetup({
576
659
  enabled,
@@ -583,6 +666,12 @@ export function apply(ctx, config = {}) {
583
666
  jdkRoot: configuredJdkRoot,
584
667
  jdkMirror: cfg.jdkMirror,
585
668
  jdkVersion: cfg.jdkVersion,
669
+ // Download reliability knobs (lib/autosetup.js): retries with backoff,
670
+ // cumulative disk budget, and SDK-manager/network overrides.
671
+ stepRetries: cfg.setupRetries,
672
+ retryDelayMs: cfg.retryDelayMs,
673
+ minFreeDiskBytes: cfg.minFreeDiskBytes,
674
+ ...provisionNetworkOptions(),
586
675
  log: autoSetupLog,
587
676
  onUpdate: (snapshot) => {
588
677
  if (snapshot.state === lastAutoSetupState) return;
@@ -1564,6 +1653,9 @@ export function apply(ctx, config = {}) {
1564
1653
  stream: { fps: streamFps, hostFps: measuredFrameFps(), h264: scrcpyStatus() },
1565
1654
  origin: serverOrigin,
1566
1655
  multiInstance: Boolean(instanceManager),
1656
+ // Host memory + effective instance cap + lite profile (lib/memory.js).
1657
+ // Guarded so an older lib/instances.js never breaks the state route.
1658
+ memory: instanceManager && typeof instanceManager.memory === 'function' ? instanceManager.memory() : null,
1567
1659
  client: lastClientReport,
1568
1660
  owner: instanceManager ? instanceManager.ownerInfo('default') : null,
1569
1661
  instances: [
@@ -2522,6 +2614,7 @@ export function apply(ctx, config = {}) {
2522
2614
  jdkRoot: configuredJdkRoot,
2523
2615
  systemImage: cfg.systemImage || DEFAULT_SYSTEM_IMAGE,
2524
2616
  acceptLicenses: true,
2617
+ ...provisionNetworkOptions(),
2525
2618
  });
2526
2619
  setupCache = null;
2527
2620
  sendJson(res, 200, { ok: result.ok === true, action, result });
@@ -2542,6 +2635,7 @@ export function apply(ctx, config = {}) {
2542
2635
  jdkRoot: configuredJdkRoot,
2543
2636
  packages,
2544
2637
  acceptLicenses: true,
2638
+ ...provisionNetworkOptions(),
2545
2639
  });
2546
2640
  setupCache = null;
2547
2641
  sendJson(res, 200, { ok: result.ok === true, action, result });
@@ -2557,6 +2651,7 @@ export function apply(ctx, config = {}) {
2557
2651
  jdkRoot: configuredJdkRoot,
2558
2652
  packages: Array.isArray(body.packages) ? body.packages : undefined,
2559
2653
  acceptLicenses: true,
2654
+ ...provisionNetworkOptions(),
2560
2655
  });
2561
2656
  setupCache = null;
2562
2657
  sendJson(res, 200, { ok: result.ok === true, action, result });
@@ -3734,7 +3829,15 @@ export function apply(ctx, config = {}) {
3734
3829
  for (const profile of profiles) {
3735
3830
  remotes.push(await collectRemoteInventory({ profile }));
3736
3831
  }
3737
- sendJson(res, 200, buildEmulatorInventory({ local, remotes }));
3832
+ const inventory = buildEmulatorInventory({ local, remotes });
3833
+ if (instanceManager && typeof instanceManager.memory === 'function') {
3834
+ try {
3835
+ inventory.memory = instanceManager.memory();
3836
+ } catch {
3837
+ inventory.memory = null;
3838
+ }
3839
+ }
3840
+ sendJson(res, 200, inventory);
3738
3841
  } catch (error) {
3739
3842
  sendError(res, 500, error && error.message ? error.message : String(error));
3740
3843
  }