dsh-apk-vm 0.12.4 → 0.13.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.
package/README.md CHANGED
@@ -45,7 +45,7 @@ same-origin, loopback-only debug HTTP API and an `apk_vm` Agent tool.
45
45
  > 当前 **Windows x64 与 Linux x86_64(headless)为端到端已验证平台**;macOS 仅做探测/CI
46
46
  > 覆盖,详见 `docs/LINUX-E2E.md`。
47
47
 
48
- **Status:** `0.12.4` · Apache-2.0 · no npm runtime dependencies · no build step.
48
+ **Status:** `0.12.5` · Apache-2.0 · no npm runtime dependencies · no build step.
49
49
 
50
50
  This is an open-source DSH plugin published on npm as **`dsh-apk-vm`**. Repository:
51
51
  [github.com/yuxiaole-bili/dsh-apk-vm](https://github.com/yuxiaole-bili/dsh-apk-vm).
@@ -96,7 +96,10 @@ and Agent-facing UI automation for development workflows.
96
96
  - Hardware virtualization: AEHD/WHPX on Windows, KVM on Linux, or HVF on macOS.
97
97
  - Node.js ≥ 20 only for the repository's headless checks; the plugin itself has no npm
98
98
  dependencies or build step.
99
- - Each running VM costs roughly 2.5 GB RAM; `maxInstances` defaults to 3 extra VMs.
99
+ - Each running VM costs roughly 2–3 GB of host RAM (`hw.ramSize` 1.5 GB default plus
100
+ emulator/GPU overhead); `maxInstances` defaults to 3 extra VMs. The `memoryGuard` (default on)
101
+ caps the effective count from total host RAM and the `vmPreset: lite` preset shrinks the guest
102
+ to 1 GB / 2 vCPU for 8–16 GB machines.
100
103
 
101
104
  **Permissions / risk**
102
105
 
@@ -197,6 +200,26 @@ key {"text":"HOME"} -> returned to launcher
197
200
  configured system image and the AVD, with live progress plus cancel/retry in the Environment
198
201
  card (`autoSetup` on `GET/POST /apk-vm/setup`). The normal `autoStart` flow then boots the VM;
199
202
  set `autoSetup: false` to keep setup manual.
203
+ - **Download resilience for the zero-config first run.** Every provisioning step retries
204
+ transient network failures with exponential backoff (`setupRetries: 3`, `retryDelayMs: 2000`)
205
+ and no-data stalls are detected by a 45 s no-progress watchdog, so a link that dies at 10 %
206
+ resumes instead of hanging. The JDK archive resumes from a `.partial` file with HTTP Range and
207
+ is re-verified against the SHA-256 checksum on each attempt; a configurable mirror
208
+ (`jdkMirror`) bypasses unreachable GitHub assets. The command-line-tools archive can point at
209
+ a mirror or proxy (`commandLineToolsUrl`, `commandLineToolsSha256`, `sdkManagerArgs`,
210
+ `sdkManagerEnv`, `networkProxy`), and the cumulative free-disk budget
211
+ (`minFreeDiskBytes`, default 6 GB) is checked before provisioning starts.
212
+ - **Memory guard, Lite mode and instance management.** A local emulator costs ~2–3 GB of host
213
+ RAM, so with `memoryGuard` on (default) the effective `maxInstances` is derived from total
214
+ host RAM (8 GB → 1; 16 GB → 3 with the default requested cap; clamped to 1–8), free host RAM
215
+ is checked at start, and a low-memory machine refuses to start another VM with a clear error
216
+ instead of swapping itself to death. On a 16 GB desktop that also runs an IDE and a browser,
217
+ keep `maxInstances` at 2 or switch to `vmPreset: lite`, which
218
+ shrinks the AVD to 1 GB RAM / 2 vCPU / SwiftShader with a 720p30 H.264 stream, and
219
+ `memoryPressureReap` (default on) stops the least-recently-used idle local VM when memory is
220
+ tight (extra VMs are stopped, never destroyed). The VM instances card shows host RAM, the
221
+ effective cap, the preset and the per-VM RAM/vCPU profile; `GET /apk-vm/state` and
222
+ `GET /apk-vm/emulators` expose the same `memory` object.
200
223
  - **Multi-agent isolation / multi-instance.** Several DSH Agents can drive separate VMs at the
201
224
  same time: each conversation owns a renewable lease on the VM it uses, so a second
202
225
  conversation never silently steals the first one's emulator. The first conversation gets the
@@ -445,38 +468,65 @@ instrumentation.
445
468
 
446
469
  Every running VM has a renewable **owner lease**, so two DSH conversations cannot silently drive
447
470
  the same emulator. A lease records the owner key, display label, scope (`shared`, `conversation`
448
- or `project`), session id, workspace, and `since` / `lastSeenAt` timestamps; leases expire after
449
- 30 minutes (`leaseTtlMs`) and are renewed by `apk_vm` calls that route to that VM.
471
+ or `project`), session id, workspace, `since` / `lastSeenAt` timestamps and, for dedicated VMs, a
472
+ `reservedUntil` deadline. Leases are persisted to `<profile>/.apk-vm/leases.json` and restored on
473
+ the next plugin start, so a dedicated VM stays reserved across DSH restarts. Shared leases expire
474
+ after 30 minutes (`leaseTtlMs`); dedicated (`conversation`/`project`) leases keep a reservation for
475
+ 24 hours (`leaseReservationTtlMs`) that is renewed by `apk_vm` calls that route to that VM.
476
+
477
+ The default VM is also **resident**: releasing its lease does not release or delete the VM. After
478
+ `sharedSuspendAfterMs` idle (5 minutes by default) it suspends into its quick-boot snapshot (state
479
+ `suspended`; the next start resumes in about 6 seconds), and after `sharedStopAfterMs` (1 hour)
480
+ suspended it is marked `stopped`. The AVD and snapshot are always kept, and any `apk_vm` call,
481
+ panel action or video client resets the idle timer and a later start resumes it on demand.
450
482
 
451
483
  - The first conversation that needs a VM claims the default instance. A different conversation
452
484
  gets a dedicated extra instance instead of taking the default one.
453
485
  - `ownerScope=conversation` gives the current DSH session a VM that follows it across turns;
454
486
  `ownerScope=project` does the same for the current workspace. `ownerScope=shared` keeps the
455
487
  first-come default behaviour.
456
- - If an `instance` is explicitly requested and owned by another conversation, the call fails with
457
- `vm-busy` and the owner details. `ownerForce=true` is an explicit takeover and should be used
458
- only after checking `owner_status`.
459
- - The VM instances card shows the current owner/scope. The **VM usage** card in the panel
460
- shows a readable owner label and provides **Claim**, **Release** and a `shared` /
461
- `conversation` / `project` scope control for the human user.
462
- - The Web panel is an administrator: it can operate a VM held by an Agent conversation and may
463
- force **Claim** / **Release**, while ordinary Agent calls still get `409 vm-busy`. The panel
464
- sends `x-apk-vm-role: admin`; the Host accepts that role only from loopback requests and
465
- downgrades non-local callers to `user`.
466
- - `owner_status` lists default/extra VM leases; `claim_vm` and `release_vm` manage them.
467
- HTTP: `GET|POST /apk-vm/ownership` (`status`, `claim`, `release`, `touch`), while
468
- `GET /apk-vm/state` and `GET /apk-vm/instances` include owner metadata.
488
+ - A reserved VM cannot be claimed by another owner without an explicit takeover. The response is
489
+ `409 vm-busy` with the owner short id and reservation deadline; pass `ownerForce=true` (alias
490
+ `force=true`) only after checking `owner_status`.
491
+ - The VM instances card shows the current owner/scope/reservation. The **VM usage** card in the
492
+ panel shows a readable owner label and provides **Claim**, **Release** and a `shared` /
493
+ `conversation` / `project` scope control for the human user. For a VM held by another owner the
494
+ panel keeps the controls read-only and offers **Take over**.
495
+ - The Web panel is an administrator, but admin mutations on a VM held by another owner are not
496
+ silent: they must be an explicit takeover, either by clicking **Take over** in the panel or by
497
+ sending `x-apk-vm-takeover: 1`. Otherwise the request fails with `409 vm-takeover-required`.
498
+ The panel sends `x-apk-vm-role: admin`; the Host accepts that role only from loopback requests
499
+ and downgrades non-local callers to `user`.
500
+ - `owner_status` lists default/extra VM leases; `claim_vm` and `release_vm` manage them and report
501
+ the previous owner when a takeover happens. HTTP: `GET|POST /apk-vm/ownership` (`status`,
502
+ `claim`, `release`, `touch`), while `GET /apk-vm/state` and `GET /apk-vm/instances` include owner
503
+ metadata.
469
504
  - When the panel makes a mutating HTTP request it sends
470
505
  `x-apk-vm-owner`, `x-apk-vm-scope`, `x-apk-vm-session`, `x-apk-vm-workspace` and
471
506
  `x-apk-vm-label`. Header values may be percent-encoded (UTF-8); the Host decodes them, so
472
- non-ASCII labels and workspace paths remain valid for browser `fetch`. A request that
473
- supplies an owner header auto-claims a free VM; on a leased VM
474
- it must match the current owner key. `POST /apk-vm/*` control routes return `409 vm-busy` with
475
- the current owner when the header is missing or does not match. Read-only `GET` routes are
476
- never blocked.
507
+ non-ASCII labels and workspace paths remain valid for browser `fetch`. A request that supplies
508
+ an owner header auto-claims a free VM; on a leased VM it must match the current owner key.
509
+ `POST /apk-vm/*` control routes return `409 vm-busy` (or `409 vm-takeover-required` for an
510
+ admin takeover) with the current owner when the header is missing or does not match. Read-only
511
+ `GET` routes are never blocked.
477
512
  - Closing a DSH conversation (the `session/disposed` event) automatically releases its leases,
478
- with the 30-minute TTL as a fallback if that event is unavailable.
479
-
513
+ with the TTL as a fallback if that event is unavailable. Claim, release and takeover changes are
514
+ recorded in the activity journal together with the previous and incoming owner.
515
+
516
+
517
+ VM operation locks go further than ownership: `lock_vm` / `unlock_vm` (or `POST /apk-vm/ownership`
518
+ actions `lock`/`unlock`) make the current owner's lease a hard lock. While locked, every mutating
519
+ request from another agent or the panel is rejected with `409 vm-locked`; `ownerForce`/takeover
520
+ cannot break it, and only the lock owner can control the VM (a local admin can force-unlock from
521
+ the panel). Locks are persisted in `<profile>/.apk-vm/leases.json` and the owner card shows
522
+ Lock/Unlock.
523
+
524
+ The lock policy is configurable. `lockEnforcement` is `all` (default: the lock blocks every
525
+ other mutating client, including a panel takeover), `agents` (only other agents are blocked;
526
+ the local panel is the human operator and can still operate a locked VM) or `off` (locks are
527
+ advisory markers and never block). `lockControl` is `all` (default: an agent or the panel may
528
+ lock/unlock) or `user` (only the panel/user may lock or unlock; the `lock_vm`/`unlock_vm`
529
+ actions return an error).
480
530
  ## Multiple instances, physical devices and snapshots
481
531
 
482
532
  - **Isolated extra instances.** `POST /apk-vm/instances {"name":"agent-a","start":true}` creates a
@@ -548,6 +598,8 @@ card uses the same endpoint.
548
598
  { "action": "temp" }
549
599
  { "action": "snapshots", "avdName": "dsh_apk", "confirm": true }
550
600
  { "action": "orphan-avds", "confirm": true }
601
+ { "action": "corrupt-snapshots", "confirm": true }
602
+ { "action": "crash-dumps", "confirm": true }
551
603
  ```
552
604
 
553
605
  - `temp` removes only screenshots, MP4 recordings, uploaded APKs and flow JSON created by this
@@ -556,6 +608,13 @@ card uses the same endpoint.
556
608
  boot is a cold boot.
557
609
  - `orphan-avds` removes only `dsh_apk_*` AVDs that are not registered to any instance and are
558
610
  not active.
611
+ - `corrupt-snapshots` deletes quarantined `*.corrupt-*` snapshot backups; `crash-dumps` deletes
612
+ emulator crash reports under the temp directory. `totals.reclaimableBytes` sums orphan AVDs,
613
+ corrupt backups, crash dumps and temp files, so it is the upper bound for one cleanup pass.
614
+ - Every destructive action (`snapshots`, `orphan-avds`, `corrupt-snapshots`, `crash-dumps`,
615
+ `destroy_instance`) requires `confirm: true`; the panel asks for a second click.
616
+ - An action that has to boot a VM fails after about 120 s (explicit `start`: 180 s, override
617
+ with `timeoutMs`) instead of blocking for the full boot timeout; the VM keeps booting.
559
618
  - `apk_vm` tool actions: `storage`, `clean_storage` (`storageAction`, `avdName`, `confirm`).
560
619
 
561
620
  ## Network controls
@@ -732,14 +791,36 @@ config:
732
791
  maxInstances: 3 # extra VMs (default VM is always available)
733
792
  instanceIdleMs: 900000 # stop idle extra VMs after 15 min (AVD kept)
734
793
  instanceReapIntervalMs: 60000
794
+ # Resident shared default VM: lease can be released, VM/AVD are never deleted.
795
+ # Idle -> suspend into the quick-boot snapshot; longer idle -> state "stopped"
796
+ # (snapshot kept). Activity resets the timer and resumes it on demand.
797
+ sharedResident: true
798
+ sharedSuspendAfterMs: 300000 # suspend the default VM after 5 min idle
799
+ sharedStopAfterMs: 3600000 # mark it "stopped" after 1 h suspended
800
+ memoryGuard: true # cap instances from host RAM; refuse low-memory starts
801
+ # hostReserveMb: 4096 # RAM kept for the host/other apps
802
+ # estimatedVmMb: 3072 # estimated cost of one local emulator
803
+ vmPreset: standard # standard | lite (1 GB / 2 vCPU / SwiftShader / 720p30)
804
+ memoryPressureReap: true # stop LRU idle VMs before creating another one
735
805
  leaseTtlMs: 1800000 # VM owner lease lifetime; renewed by apk_vm calls
806
+ leaseReservationTtlMs: 86400000 # dedicated (conversation/project) lease reservation; 24h
807
+ lockEnforcement: all # all | agents | off (operation-lock policy)
808
+ lockControl: all # all | user (who may lock/unlock a VM)
736
809
  allowRemote: false # reject non-loopback VM API clients
737
810
  autoSetup: true # zero-config first run: auto-provision JDK 17 + SDK + image + AVD
811
+ setupRetries: 3 # retries per provisioning step (exponential backoff)
812
+ retryDelayMs: 2000
813
+ # minFreeDiskBytes: 6442450944 # cumulative free-disk budget before provisioning
738
814
  # jdkRoot: 'C:/tools/dsh-jdk' # where the auto-downloaded JDK 17 lives
739
815
  # jdkVersion: 17 # Temurin major version to provision (known-good table covers 17.0.21+9)
740
816
  # jdkMirror: 'https://mirrors.tuna.tsinghua.edu.cn/Adoptium' # override the JDK mirror fallback
741
817
  # activityDir: 'C:/tools/apk-vm-activity' # journal + screenshot storage (default <profile>/.apk-vm/activity)
742
818
  allowSetupDownloads: false # gate the optional manual system-image download action
819
+ # commandLineToolsUrl: 'https://example.com/commandlinetools-win-latest.zip' # mirror for the tools archive
820
+ # commandLineToolsSha256: '...' # checksum for the custom archive
821
+ # sdkManagerArgs: ['--no_https'] # passed verbatim to sdkmanager (mirrors / flags)
822
+ # sdkManagerEnv: { SDK_TEST_BASE_URL: 'https://mirror.example.com/android/repository/' }
823
+ # networkProxy: { host: 127.0.0.1, port: 7890 } # --proxy_* flags for sdkmanager only
743
824
  scrcpy: true
744
825
  scrcpyMaxSize: 960
745
826
  scrcpyMaxFps: 60
@@ -804,15 +885,34 @@ All keys are optional; defaults are shown in the **Default** column.
804
885
  | `mic` | `{ mode: "off" }` | Guest microphone: `off` / `host` (host input passthrough) / `file` (loop an audio file into a virtual source; Linux and remote hosts). Optional `backend`, `filePath`. |
805
886
  | `multiInstance` | `true` | Allow isolated extra VMs for concurrent Agents. |
806
887
  | `maxInstances` | `3` | Maximum number of extra instances (in addition to the default VM). Each running instance costs guest RAM/CPU. |
888
+ | `memoryGuard` | `true` | Cap the effective instance count from host RAM and refuse to start a local VM when free memory is below the reserve. Remote sessions are not counted. |
889
+ | `hostReserveMb` | `4096` | Host RAM kept free when computing the effective cap / deciding whether a new VM fits. |
890
+ | `estimatedVmMb` | `3072` | Estimated host RAM used by one local emulator (AVD RAM + qemu/GPU overhead) for the guard and the panel estimate. |
891
+ | `vmPreset` | `standard` | `standard` or `lite` (1 GB guest RAM, 2 vCPU, SwiftShader GPU, 1 fps PNG / 720p30 H.264). Applies to the default AVD (rewritten on activation) and to extra instances. |
892
+ | `memoryPressureReap` | `true` | When memory is tight, stop the least-recently-used idle local VM before creating another one. Extra VMs are stopped, never destroyed. |
807
893
  | `instanceIdleMs` | `900000` | Stop an extra instance after this long without panel frames, a video client, or an Agent command (AVD is kept). |
808
894
  | `instanceReapIntervalMs` | `60000` | How often the idle reaper checks extra instances. |
895
+ | `sharedResident` | `true` | Keep the default VM resident: leases can be released, but the VM and its AVD are never released/deleted. After `sharedSuspendAfterMs` idle it suspends into its quick-boot snapshot (state `suspended`, ~6 s resume); after `sharedStopAfterMs` it is marked `stopped` (snapshot/AVD kept). Any tool/panel/stream activity resets the idle timer. |
896
+ | `sharedSuspendAfterMs` | `300000` | Idle time (ms) before the resident default VM suspends into its quick-boot snapshot. |
897
+ | `sharedStopAfterMs` | `3600000` | How long the resident default VM may stay suspended before it is marked `stopped` (snapshot is kept). |
809
898
  | `leaseTtlMs` | `1800000` | Lifetime of a VM owner lease. Every `apk_vm` call that routes to the VM renews it; set `0` to disable expiry. |
899
+ | `leaseReservationTtlMs` | `86400000` | How long a `conversation`/`project` lease stays reserved for its owner across restarts. The VM cannot be claimed by another owner until it expires (explicit takeover still allowed). |
900
+ | `lockEnforcement` | `all` | Operation-lock policy: `all` (hard lock for every other mutating client, including a panel takeover), `agents` (only other agents are blocked; the local panel may still operate a locked VM), `off` (locks are advisory and never block). |
901
+ | `lockControl` | `all` | Who may lock/unlock: `all` (agents or the panel) or `user` (panel/user only; `lock_vm`/`unlock_vm` return an error). |
810
902
  | `allowRemote` | `false` | Allow non-loopback clients to reach `/apk-vm/*` and `/apk-vm/ws` (only behind your own authenticated proxy). |
811
903
  | `allowSetupDownloads` | `false` | Allow the Environment card's `install-image` action to run `sdkmanager --install` (large download). |
812
904
  | `autoSetup` | `true` | Provision a missing JDK 17 / SDK packages / system image / AVD automatically on first use (roughly 2.5 GB on a cold machine). Set `false` to keep setup manual. |
813
905
  | `jdkRoot` | `~/.dsh/apk-vm/jdk` | Where the auto-downloaded Temurin JDK 17 is installed. A system JDK / `JAVA_HOME` is preferred when present. |
814
906
  | `jdkVersion` | `17` | Temurin major version to provision when `autoSetup` needs a JDK. |
815
907
  | `jdkMirror` | built-in Tsinghua mirror | Mirror base URL (or array of bases) used for the Temurin JDK archive when the GitHub-hosted Adoptium download is unreachable, verified with the same SHA-256 checksum. Env: `DSH_APK_VM_JDK_MIRROR`; an empty value disables the fallback. |
908
+ | `setupRetries` | `3` | Automatic retries per provisioning step after a transient network/command failure (exponential backoff). |
909
+ | `retryDelayMs` | `2000` | Base delay between provisioning retries; doubled each attempt. |
910
+ | `minFreeDiskBytes` | `6442450944` (6 GB) | Cumulative free-disk budget checked before provisioning starts (JDK + tools + image + AVD). |
911
+ | `commandLineToolsUrl` | Google archive | Optional mirror URL for the command-line-tools archive (checksum option below). |
912
+ | `commandLineToolsSha256` | — | Optional SHA-256 for `commandLineToolsUrl`; the download is verified like the JDK. |
913
+ | `sdkManagerArgs` | `[]` | Extra arguments passed verbatim to `sdkmanager` (for example `["--no_https"]` for a mirror). |
914
+ | `sdkManagerEnv` | `{}` | Extra environment variables for `sdkmanager` (for example `SDK_TEST_BASE_URL` for an SDK mirror). |
915
+ | `networkProxy` | — | `{host, port, user, password}` translated into `--proxy_*` flags for `sdkmanager` only; the plugin itself never proxies its own requests. |
816
916
  | `activityDir` | `<profile>/.apk-vm/activity` | Where the Agent activity journal (`activity.jsonl`) and its screenshots are stored. |
817
917
  | `frameFps` | `2` | PNG fallback target frame rate, 1–10 (the H.264 path is not affected). |
818
918
  | `scrcpy` | `true` | Enable the H.264/WebCodecs transport. |
@@ -831,6 +931,15 @@ per-action availability. It also carries the auto-setup state: `autoSetupEnabled
831
931
  finishedAt }`; `POST /apk-vm/setup` with `{ action: "auto-setup" }` starts/retries provisioning
832
932
  and `{ action: "cancel-auto-setup" }` cancels it.
833
933
 
934
+ `GET /apk-vm/state`, `GET /apk-vm/emulators`, `GET /apk-vm/instances` and the
935
+ `apk_vm` `list_instances` action also expose a `memory` object:
936
+ `{ available, totalMb, freeMb, reserveMb, estimatedVmMb, guard, pressureReap,
937
+ requestedMaxInstances, effectiveMaxInstances, preset: { name, ramSizeMb, cores, ... },
938
+ limited, reason }`. It is the same object the panel uses for the host-memory line and the
939
+ instance cap. `POST /apk-vm/instances` (create) and `create_instance` honour it: when a local VM
940
+ does not fit, the request fails with an actionable error, or `memoryPressureReap` stops an idle
941
+ VM first.
942
+
834
943
  ---
835
944
 
836
945
  ## Architecture
@@ -865,6 +974,7 @@ and `{ action: "cancel-auto-setup" }` cancels it.
865
974
  | Setup | [lib/setup.js](lib/setup.js), [lib/jdk.js](lib/jdk.js), [lib/autosetup.js](lib/autosetup.js) | Dependency-free SDK / adb / emulator / AVD / acceleration detection plus one-click `create-avd` and optional `install-image`; `lib/jdk.js` provisions a managed Temurin JDK 17 and `lib/autosetup.js` runs the first-use auto-provisioning chain. |
866
975
  | Journal | [lib/activity-log.js](lib/activity-log.js) | Records every `apk_vm` tool call and every mutating panel/HTTP request (`source: tool|http|system`; action, argument preview, result/error, duration, instance, screenshot for mutating actions) as local JSONL + PNGs; backs the panel timeline and the `/apk-vm/activity` routes. |
867
976
  | Installed apps | [lib/installed-apps.js](lib/installed-apps.js) | Persists APKs installed through the plugin (`<profile>/.apk-vm/installed-apps.json`, archived copies under `<profile>/.apk-vm/apks`) and re-installs missing packages on the next boot (`autoReinstall`). |
977
+ | Memory | [lib/memory.js](lib/memory.js) | Host RAM snapshot, effective instance cap derived from RAM, `standard` / `lite` preset resolution and the low-memory start checks used by `lib/instances.js`; exposed as `memory` on `GET /apk-vm/state`, `/apk-vm/emulators` and `/apk-vm/instances`. |
868
978
  | Streaming | scrcpy 5.0.1 server (`lib/vendor/scrcpy-server-v5.0.1.jar`, pushed to `/data/local/tmp/scrcpy-server.jar`) + [lib/scrcpy.js](lib/scrcpy.js) | H.264 screen capture and the scrcpy control protocol, without the desktop scrcpy client. |
869
979
  | Device bridge | `adb` from Android SDK platform-tools | install / launch / screencap / input / logcat / file push-pull. |
870
980
  | Plugin runtime | DSH plugin APIs (`slots`, `locale`, `webServer`, `tools`, `dsh.client`) | Sidebar entry, main panel, same-origin HTTP/WebSocket control plane, agent tool. |
@@ -941,7 +1051,7 @@ JSON bodies are bounded to 64 KiB; the raw APK upload is bounded to 500 MiB.
941
1051
  | POST | `/apk-vm/stream` | `{"fps":1–10}` — set the PNG fallback target frame rate. |
942
1052
  | POST | `/apk-vm/stream/quality` | `{"preset":"low\|balanced\|high"}` — change H.264 resolution/bitrate/fps; the scrcpy session reconnects. |
943
1053
  | GET (upgrade) | `/apk-vm/ws` | WebSocket H.264 stream (see above). |
944
- | GET/POST | `/apk-vm/ownership` | `GET` lists VM leases; `POST {"action":"claim\|release\|touch","instanceId":"default","ownerScope":"shared\|conversation\|project","sessionId"?,"workspace"?,"force"?}` manages the owner lease. |
1054
+ | GET/POST | `/apk-vm/ownership` | `GET` lists VM leases; `POST {"action":"claim\|release\|touch","instanceId":"default","ownerScope":"shared\|conversation\|project","sessionId"?,"workspace"?,"force"?}` manages the owner lease. `force:true` is only for an explicit takeover; an admin call on a foreign reservation must send `x-apk-vm-takeover: 1`. |
945
1055
  | GET | `/apk-vm/instances` | List default + extra VM instances, including `name`, `owner`, `ownerInfo` (`key`, `label`, `scope`, `sessionId`, `workspace`, `since`, `lastSeenAt`), `lastUsedAt`, `idleMs`, `idleTimeoutMs`, `videoClients`. |
946
1056
  | POST | `/apk-vm/instances` | `{"name":"agent-a","start":true}` — create an isolated AVD/VM; every extra instance has its own H.264 stream. `{"action":"rename","instance":"default","name":"QA phone"}` sets a display name. |
947
1057
  | DELETE | `/apk-vm/instances/:id` | Stop/dispose an extra instance (the default cannot be destroyed). |
@@ -1028,10 +1138,12 @@ its home screen.
1028
1138
  For concurrent Agents, pass `instance` to target a specific VM; when omitted, the tool resolves
1029
1139
  the calling Agent's lease and assigned instance (first conversation → default VM, later
1030
1140
  conversations → isolated instances created on demand until `maxInstances`). Set
1031
- `ownerScope=conversation` or `ownerScope=project` to request a dedicated VM for the current DSH
1032
- session/workspace. `owner_status` lists leases, `claim_vm` / `release_vm` manage them, and
1033
- `ownerForce=true` is required for an explicit takeover. Each extra instance has its own H.264
1034
- WebSocket (`/apk-vm/instances/<id>/ws`) and falls back to PNG if WebCodecs is unavailable.
1141
+ `ownerScope=conversation` or `ownerScope=project` to reserve a dedicated VM for the current DSH
1142
+ session/workspace; the reservation survives plugin restarts (24 h by default,
1143
+ `leaseReservationTtlMs`). `owner_status` lists leases, `claim_vm` / `release_vm` manage them, and
1144
+ `ownerForce=true` (alias `force=true`) is required for an explicit takeover. Each extra instance
1145
+ has its own H.264 WebSocket (`/apk-vm/instances/<id>/ws`) and falls back to PNG if WebCodecs is
1146
+ unavailable.
1035
1147
 
1036
1148
  UI automation is live-verified against a multi-instance VM: `find_ui {"text":"Phone"}` returned
1037
1149
  `Phone @ 102,1121`, `assert_text {"text":"Phone"}` found one node, `tap_text {"text":"Phone"}`
@@ -1095,6 +1207,13 @@ screen legitimately shows a low FPS. The 60 Hz animation test sustains ~59 fps o
1095
1207
  The `Target FPS` selector applies only to the PNG fallback; the H.264 path is capped by
1096
1208
  `scrcpyMaxFps`.
1097
1209
 
1210
+ Host memory is the other cost driver: each local emulator costs roughly 2–3 GB (1.5 GB AVD RAM
1211
+ plus qemu/GPU overhead). With `memoryGuard: true` the effective instance cap is derived from
1212
+ total RAM minus `hostReserveMb` (4 GB) divided by `estimatedVmMb` (3 GB), then clamped by
1213
+ `maxInstances`: 8 GB → 1 VM, 16 GB → 3 (the default requested cap), 32 GB+ → 3. A 16 GB desktop
1214
+ that also runs an IDE and a browser is happier with `maxInstances: 2`; `vmPreset: lite` lowers
1215
+ the guest to 1 GB / 2 vCPU / SwiftShader and a 720p30 stream when you need a third.
1216
+
1098
1217
  ---
1099
1218
 
1100
1219
  ## Verification
@@ -1188,16 +1307,33 @@ card starts provisioning automatically; while it runs you see the current step p
1188
1307
 
1189
1308
  ### Auto-setup fails or is stuck
1190
1309
 
1191
- The card shows the last step and the error (`autoSetup.error` in `GET /apk-vm/setup`). Common
1192
- causes: no network access to `api.adoptium.net` / `dl.google.com` (or to `github.com`, where
1193
- Adoptium hosts the JDK archive — the built-in Tsinghua mirror is tried automatically), a proxy or
1194
- firewall, an antivirus locking freshly extracted files, or less than ~3 GB free disk space. Press
1195
- **Retry**: the JDK archive is reused when its SHA-256 checksum matches, so retries do not
1196
- re-download it; a mirror can be pinned with `jdkMirror` (or `DSH_APK_VM_JDK_MIRROR`).
1197
- You can also set `autoSetup: false` and provision manually (see
1310
+ The card shows the last step and the error (`autoSetup.error` in `GET /apk-vm/setup`). Each
1311
+ provisioning step is retried automatically (`setupRetries`, default 3, exponential backoff) and
1312
+ downloads that stop transferring data are aborted by a 45 s no-progress watchdog, so a link that
1313
+ dies mid-download recovers instead of hanging. Common causes: no network access to
1314
+ `api.adoptium.net` / `dl.google.com` (or to `github.com`, where Adoptium hosts the JDK archive —
1315
+ the built-in Tsinghua mirror is tried automatically), a proxy or firewall, an antivirus locking
1316
+ freshly extracted files, or less than the required free disk space (`minFreeDiskBytes`, default
1317
+ 6 GB, is checked before provisioning). Press **Retry**: the JDK archive is reused when its
1318
+ SHA-256 checksum matches and resumes from a `.partial` file with HTTP Range otherwise; a mirror
1319
+ can be pinned with `jdkMirror` (or `DSH_APK_VM_JDK_MIRROR`). For proxies and mirrors behind the
1320
+ SDK downloads set `networkProxy` (translated to `sdkmanager --proxy_*` flags), `sdkManagerArgs`,
1321
+ `sdkManagerEnv`, or point `commandLineToolsUrl` / `commandLineToolsSha256` at your own tools
1322
+ archive. You can also set `autoSetup: false` and provision manually (see
1198
1323
  [step 3](#3-provide-an-android-sdk-system-image-and-avd-automatic-by-default)); parts that already
1199
1324
  succeeded are skipped on the next attempt.
1200
1325
 
1326
+ ### The VM refuses to start because the host is low on memory
1327
+
1328
+ With `memoryGuard: true` (default) a local emulator is only started when the host has room for
1329
+ it: total RAM minus `hostReserveMb` (4 GB) divided by `estimatedVmMb` (~3 GB) gives the
1330
+ effective instance cap (`GET /apk-vm/state` → `memory.effectiveMaxInstances`; the panel shows it
1331
+ on the VM instances card). Close other emulators/apps, raise `hostReserveMb`/`estimatedVmMb` only
1332
+ after measuring, set `vmPreset: lite` to shrink new guests to 1 GB / 2 vCPU, enable
1333
+ `memoryPressureReap` (default) so idle VMs are stopped first, or move work to a remote VM
1334
+ (`/apk-vm/remote`, see [Remote VM host over SSH](#remote-vm-host-over-ssh)). `memoryGuard: false`
1335
+ disables the check.
1336
+
1201
1337
  ### "No usable CPU hypervisor (AEHD/WHPX) was found"
1202
1338
 
1203
1339
  The plugin fails fast (`requireAccel: true` by default) because an x86_64 system image cannot
@@ -1423,6 +1559,11 @@ before pointing the DSH Web UI at an untrusted network.
1423
1559
  services; network activity is limited to `autoSetup` provisioning (Temurin JDK from
1424
1560
  `api.adoptium.net` or its mirror, then the SDK packages/image through the user's own
1425
1561
  `sdkmanager`, which contacts Google's SDK repository) and the same-origin DSH Web server.
1562
+ - **Provisioning proxy/mirror settings stay with the child process.** `networkProxy` is translated
1563
+ into `sdkmanager --proxy_*` flags only, and `sdkManagerArgs` / `sdkManagerEnv` are passed to the
1564
+ child `sdkmanager` invocation only. The plugin never proxies its own requests, and none of these
1565
+ values (including a proxy password) is written to the activity journal or exposed on HTTP
1566
+ routes.
1426
1567
  - **The Agent activity log is local-only.** Tool-call journal entries and screenshots are written
1427
1568
  under `<profile>/.apk-vm/activity` on this host and are never sent anywhere. They can contain
1428
1569
  screen content and command arguments, so clear the journal before sharing a recording of the
@@ -1464,6 +1605,17 @@ customization remain research notes in [DESIGN.md](DESIGN.md) §8.
1464
1605
  - **The virtual microphone `file` mode needs a Linux/PulseAudio host.** On Windows only `host`
1465
1606
  passthrough is available, and camera/mic changes apply to a running default VM only after it is
1466
1607
  restarted.
1608
+ - **The memory guard is an estimate, not a hard limit.** It reads host totals (`os` APIs), assumes
1609
+ `estimatedVmMb` per local VM and refuses/clamps new local VMs, but it cannot stop an externally
1610
+ started emulator and it counts remote sessions as zero host RAM. Set `memoryGuard: false` if the
1611
+ estimate is too conservative for your machine.
1612
+ - **`vmPreset: lite` resizes hardware profiles, not a running guest.** The default AVD's
1613
+ `hw.ramSize`/`hw.cpu.ncore` are rewritten on activation and extra instances get them at create
1614
+ time; an already running VM must be restarted to pick them up.
1615
+ - **Download resume is partial.** The JDK archive resumes from `.partial` with HTTP Range and is
1616
+ checksum-verified on every retry; the command-line-tools archive, SDK packages and system image
1617
+ are retried per step (whole-file), and `sdkmanager` owns its own retry/proxy behaviour. The 45 s
1618
+ no-progress watchdog applies to the JDK and command-line-tools downloads.
1467
1619
 
1468
1620
  - **Windows x64 and Linux x86_64 are the end-to-end verified platforms.** macOS SDK/adb/
1469
1621
  emulator/AVD discovery is implemented and `arm64` hosts automatically select the