dsh-apk-vm 0.12.2 → 0.12.4

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
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
24
24
 
25
25
  import { AndroidVm } from './lib/android.js';
26
26
  import { InstanceManager } from './lib/instances.js';
27
+ import { defaultInstanceNamesPath } from './lib/instance-names.js';
27
28
  import { OWNER_SCOPE, normalizeScope } from './lib/vm-ownership.js';
28
29
  import { checkOwnerAccess, ownerFromHttp } from './lib/http-owner.js';
29
30
  import { ScrcpySession, annexbToAvcc, CONTROL_MESSAGE_TYPE } from './lib/scrcpy.js';
@@ -62,6 +63,28 @@ export const name = 'dsh-apk-vm';
62
63
  const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url));
63
64
  const SCRCPY_JAR = path.join(PLUGIN_DIR, 'lib', 'vendor', 'scrcpy-server-v5.0.1.jar');
64
65
 
66
+ /**
67
+ * Agent playbook shipped with the package (docs/AGENTS.md). Cached after the
68
+ * first read; `null` when a local build does not carry the file (the tool then
69
+ * reports that the guide is not bundled instead of failing).
70
+ */
71
+ const AGENT_GUIDE_PATH = path.join(PLUGIN_DIR, 'docs', 'AGENTS.md');
72
+ // Single source of truth for the tool action enum (schema + early validation).
73
+ const TOOL_ACTIONS = Object.freeze(["info", "shell", "logcat", "getprop", "setprop", "packages", "install", "push", "pull", "reboot", "root", "force_stop", "clear_data", "uninstall", "rotate", "ui_dump", "inspect_ui", "proxy", "install_ca", "network", "record", "perf", "screenshot", "tap", "swipe", "long_press", "key", "text", "apk_info", "find_ui", "assert_text", "tap_text", "clipboard_get", "clipboard_set", "devices", "attach_device", "detach_device", "start", "stop", "list_instances", "create_instance", "rename_instance", "destroy_instance", "owner_status", "claim_vm", "release_vm", "flow_start", "flow_stop", "flow_list", "flow_replay", "storage", "clean_storage", "skill_list", "skill_get", "skill_save", "skill_delete", "skill_start", "skill_stop", "skill_cancel", "skill_run", "skill_codebook", "control_ui", "control_features", "control_codebook", "control_tap", "control_input", "control_long_press", "control_swipe", "control_assert", "control_wait", "control_launch", "webview", "tap_css", "tap_selector", "type_text", "wait_for", "env_snapshot", "env_restore", "adb", "guide"]);
74
+
75
+
76
+ let agentGuideCache;
77
+ function readAgentGuide() {
78
+ if (agentGuideCache === undefined) {
79
+ try {
80
+ agentGuideCache = readFileSync(AGENT_GUIDE_PATH, 'utf8');
81
+ } catch {
82
+ agentGuideCache = null;
83
+ }
84
+ }
85
+ return agentGuideCache;
86
+ }
87
+
65
88
  /** Body limit for the JSON control endpoints. */
66
89
  const BODY_LIMIT_BYTES = 64 * 1024;
67
90
  /** Upload limit for browser APK uploads (500 MiB; Android emulator system apps are smaller). */
@@ -340,6 +363,7 @@ export function apply(ctx, config = {}) {
340
363
  emulatorPath: vm.emulatorPath,
341
364
  systemImage: cfg.systemImage || DEFAULT_SYSTEM_IMAGE,
342
365
  baseAvdName: cfg.avdName || 'dsh_apk',
366
+ namesFile: defaultInstanceNamesPath(dataRoot),
343
367
  maxInstances: cfg.maxInstances || 3,
344
368
  gpuMode: cfg.gpuMode || 'host',
345
369
  snapshotName: cfg.snapshotName || 'default_boot',
@@ -929,6 +953,114 @@ export function apply(ctx, config = {}) {
929
953
  // Sessions that received a file-loop virtual microphone; disconnect stops it.
930
954
  const remoteMicSessions = new Set();
931
955
 
956
+ // One-time onboarding: the first apk_vm call in each conversation returns the
957
+ // playbook instead of touching a device. Persisted next to the other runtime
958
+ // state so a host restart does not re-teach the same conversation, but capped
959
+ // and pruned so the file cannot grow without bound.
960
+ const GUIDE_SEEN_VERSION = 1;
961
+ const GUIDE_SEEN_MAX_SESSIONS = 200;
962
+ const GUIDE_SEEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
963
+ const guideSeenFile = path.join(dataRoot, '.apk-vm', 'guide-seen.json');
964
+ const guideSeenSessions = new Map();
965
+ let guideSeenLoaded = false;
966
+ function loadGuideSeenSessions() {
967
+ if (guideSeenLoaded) return;
968
+ guideSeenLoaded = true;
969
+ try {
970
+ const parsed = JSON.parse(readFileSync(guideSeenFile, 'utf8'));
971
+ const sessions = parsed && typeof parsed.sessions === 'object' && parsed.sessions ? parsed.sessions : {};
972
+ const cutoff = Date.now() - GUIDE_SEEN_TTL_MS;
973
+ for (const [id, at] of Object.entries(sessions)) {
974
+ if (typeof at === 'number' && at >= cutoff) guideSeenSessions.set(String(id), at);
975
+ }
976
+ } catch {
977
+ /* missing/invalid file: every conversation starts un-onboarded */
978
+ }
979
+ }
980
+ function persistGuideSeenSessions() {
981
+ loadGuideSeenSessions();
982
+ const sessions = {};
983
+ for (const [id, at] of guideSeenSessions) sessions[id] = at;
984
+ const payload = { version: GUIDE_SEEN_VERSION, updatedAt: new Date().toISOString(), sessions };
985
+ void (async () => {
986
+ try {
987
+ await fsp.mkdir(path.dirname(guideSeenFile), { recursive: true });
988
+ const tmp = `${guideSeenFile}.${process.pid}.${Date.now()}.tmp`;
989
+ await fsp.writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
990
+ await fsp.rename(tmp, guideSeenFile);
991
+ } catch {
992
+ /* best effort: onboarding must never fail a tool call */
993
+ }
994
+ })();
995
+ }
996
+ function guideSessionSeen(sessionId) {
997
+ loadGuideSeenSessions();
998
+ const at = guideSeenSessions.get(String(sessionId));
999
+ if (at === undefined) return false;
1000
+ if (Date.now() - at > GUIDE_SEEN_TTL_MS) {
1001
+ guideSeenSessions.delete(String(sessionId));
1002
+ return false;
1003
+ }
1004
+ return true;
1005
+ }
1006
+ function markGuideSessionSeen(sessionId) {
1007
+ loadGuideSeenSessions();
1008
+ const id = String(sessionId);
1009
+ guideSeenSessions.delete(id);
1010
+ guideSeenSessions.set(id, Date.now());
1011
+ while (guideSeenSessions.size > GUIDE_SEEN_MAX_SESSIONS) {
1012
+ const oldest = guideSeenSessions.keys().next();
1013
+ if (oldest.done) break;
1014
+ guideSeenSessions.delete(oldest.value);
1015
+ }
1016
+ persistGuideSeenSessions();
1017
+ }
1018
+
1019
+ // A shared VM is a common device: when a different conversation starts using
1020
+ // the default instance again, reset the guest to its launcher so a new Agent
1021
+ // never inherits someone else's foreground app. Readiness is awaited in the
1022
+ // background so the tool response stays fast.
1023
+ async function waitForReadyApi(api, timeoutMs = 120000) {
1024
+ const deadline = Date.now() + Math.max(5000, Number(timeoutMs) || 0);
1025
+ let last = null;
1026
+ while (Date.now() < deadline) {
1027
+ try {
1028
+ last = await api.status();
1029
+ } catch {
1030
+ last = null;
1031
+ }
1032
+ if (last && last.state === 'ready' && last.serial) return last;
1033
+ if (last && last.state === 'error' && last.error) return last;
1034
+ await new Promise((resolve) => {
1035
+ const timer = setTimeout(resolve, 1000);
1036
+ if (timer && typeof timer.unref === 'function') timer.unref();
1037
+ });
1038
+ }
1039
+ return last;
1040
+ }
1041
+
1042
+ async function restoreSharedDesktop(api, owner, previousOwner) {
1043
+ try {
1044
+ if (!owner || owner.scope !== 'shared' || !owner.sessionId) return;
1045
+ if (previousOwner && previousOwner.sessionId === owner.sessionId) return;
1046
+ const status = await waitForReadyApi(api, 120000);
1047
+ if (!status || status.state !== 'ready' || !status.serial) return;
1048
+ await api.adb(['-s', status.serial, 'shell', 'input', 'keyevent', 'KEYCODE_HOME'], {
1049
+ timeoutMs: 15000,
1050
+ maxBytes: 16 * 1024,
1051
+ });
1052
+ await api.adb(['-s', status.serial, 'shell', 'wm', 'dismiss-keyguard'], {
1053
+ timeoutMs: 15000,
1054
+ maxBytes: 16 * 1024,
1055
+ }).catch(() => {});
1056
+ if (typeof vm._pushLog === 'function') {
1057
+ vm._pushLog(`[shared] restored the home screen for ${owner.label || owner.sessionId}`);
1058
+ }
1059
+ } catch {
1060
+ /* best effort: never block or fail the tool call */
1061
+ }
1062
+ }
1063
+
932
1064
  async function remoteState() {
933
1065
  const [state, listed] = await Promise.all([
934
1066
  remoteManager.remoteState(),
@@ -1439,6 +1571,7 @@ export function apply(ctx, config = {}) {
1439
1571
  id: 'default',
1440
1572
  kind: 'default',
1441
1573
  avdName: status.avd || vm.avdName || null,
1574
+ name: instanceManager ? instanceManager.nameFor('default', status.avd || vm.avdName) : status.avd || vm.avdName || null,
1442
1575
  port: vm.port || null,
1443
1576
  state: status.state,
1444
1577
  serial: status.serial || null,
@@ -2516,6 +2649,7 @@ export function apply(ctx, config = {}) {
2516
2649
  id: 'default',
2517
2650
  kind: 'default',
2518
2651
  avdName: defaultStatus.avd || vm.avdName || null,
2652
+ name: instanceManager ? instanceManager.nameFor('default', defaultStatus.avd || vm.avdName) : defaultStatus.avd || vm.avdName || null,
2519
2653
  port: vm.port || null,
2520
2654
  state: defaultStatus.state,
2521
2655
  serial: defaultStatus.serial || null,
@@ -2535,6 +2669,13 @@ export function apply(ctx, config = {}) {
2535
2669
  if (req.method === 'POST') {
2536
2670
  const body = await readJsonBody(req);
2537
2671
  try {
2672
+ if (body && (body.action === 'rename' || body.rename !== undefined)) {
2673
+ const target = String(body.rename !== undefined && body.rename !== true ? body.rename : body.instance || 'default');
2674
+ const renamed = await instanceManager.rename(target, body.name);
2675
+ if (!renamed.ok) throw new Error(renamed.error || 'rename failed');
2676
+ sendJson(res, 200, { ok: true, instance: renamed.id, name: renamed.name, previous: renamed.previous || null });
2677
+ return;
2678
+ }
2538
2679
  const instance = await instanceManager.create({ name: body.name });
2539
2680
  registerInstanceRoutes?.(instance.id);
2540
2681
  const owner = body.ownerKey || body.ownerScope
@@ -3599,6 +3740,30 @@ export function apply(ctx, config = {}) {
3599
3740
  }
3600
3741
  });
3601
3742
 
3743
+ // ---------------------------------------------------------------------
3744
+ // Agent playbook: the same docs/AGENTS.md the tool exposes through
3745
+ // action=guide, so scripts and panels can read it without the tool.
3746
+ // ---------------------------------------------------------------------
3747
+ register('/apk-vm/guide', async (req, res) => {
3748
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
3749
+ sendError(res, 405, 'GET only');
3750
+ return;
3751
+ }
3752
+ const markdown = readAgentGuide();
3753
+ if (markdown === null) {
3754
+ sendError(res, 404, 'agent guide is not bundled with this build (docs/AGENTS.md is missing)');
3755
+ return;
3756
+ }
3757
+ const body = Buffer.from(markdown, 'utf8');
3758
+ res.writeHead(200, {
3759
+ 'Content-Type': 'text/markdown; charset=utf-8',
3760
+ 'Content-Length': body.length,
3761
+ 'Cache-Control': 'no-store',
3762
+ });
3763
+ if (req.method === 'HEAD') res.end();
3764
+ else res.end(body);
3765
+ });
3766
+
3602
3767
  register('/apk-vm/vm', async (req, res) => {
3603
3768
  if (req.method !== 'POST') {
3604
3769
  sendError(res, 405, 'POST only');
@@ -4700,10 +4865,13 @@ export function apply(ctx, config = {}) {
4700
4865
  }
4701
4866
  const owner = toolOwnerContext(args, exec);
4702
4867
  const force = ownerTakeoverRequested(args);
4868
+ const previousDefaultOwner = instanceManager ? instanceManager.ownerInfo('default') : null;
4703
4869
  if (requested) {
4704
4870
  if (requested === 'default') {
4705
4871
  if (instanceManager) instanceManager.claimOwner('default', owner, { force });
4706
- return defaultToolApi();
4872
+ const api = defaultToolApi();
4873
+ if (exec && exec.agent) void restoreSharedDesktop(api, owner, previousDefaultOwner);
4874
+ return api;
4707
4875
  }
4708
4876
  if (!instanceManager) throw new Error('multi-instance support is disabled');
4709
4877
  const instance = instanceManager.get(requested);
@@ -4713,7 +4881,11 @@ export function apply(ctx, config = {}) {
4713
4881
  }
4714
4882
  if (instanceManager && exec && (exec.agent || owner.sessionId)) {
4715
4883
  const assigned = await instanceManager.forOwner(owner, { force });
4716
- if (assigned && assigned.default === true) return defaultToolApi();
4884
+ if (assigned && assigned.default === true) {
4885
+ const api = defaultToolApi();
4886
+ if (exec && exec.agent) void restoreSharedDesktop(api, owner, previousDefaultOwner);
4887
+ return api;
4888
+ }
4717
4889
  if (assigned && assigned.id) registerInstanceRoutes?.(assigned.id);
4718
4890
  return extraToolApi(assigned);
4719
4891
  }
@@ -4994,6 +5166,9 @@ export function apply(ctx, config = {}) {
4994
5166
  async function recordToolActivity(args, outcome, startedAt) {
4995
5167
  try {
4996
5168
  const action = String((args && args.action) || '').toLowerCase() || '(missing)';
5169
+ // Reading the playbook is not a VM operation and its summary is the whole
5170
+ // Markdown document; keep the activity journal focused on real actions.
5171
+ if (action === 'guide') return;
4997
5172
  const ok = !(outcome && outcome.ok === false);
4998
5173
  const failure = outcome && outcome.result && outcome.result.error;
4999
5174
  let shot = null;
@@ -5022,7 +5197,7 @@ export function apply(ctx, config = {}) {
5022
5197
  'The VM is usually already running (warm start); adbd runs as root once ready. ' +
5023
5198
  'Actions: info, shell, logcat, getprop, setprop, packages, install, push, pull, reboot, root, ' +
5024
5199
  'force_stop, clear_data, uninstall, rotate, ui_dump, inspect_ui, proxy, install_ca, network, record, perf, screenshot, tap, swipe, long_press, key, text, ' +
5025
- 'apk_info, find_ui, assert_text, tap_text, clipboard_get, clipboard_set, devices, attach_device, detach_device, start, stop, list_instances, create_instance, destroy_instance, owner_status, claim_vm, release_vm, flow_start, flow_stop, flow_list, flow_replay, storage, clean_storage, ' +
5200
+ 'apk_info, find_ui, assert_text, tap_text, clipboard_get, clipboard_set, devices, attach_device, detach_device, start, stop, list_instances, create_instance, rename_instance, destroy_instance, owner_status, claim_vm, release_vm, flow_start, flow_stop, flow_list, flow_replay, storage, clean_storage, ' +
5026
5201
  'skill_list, skill_get, skill_save, skill_delete, skill_start, skill_stop, skill_cancel, skill_run, skill_codebook, control_ui, control_features, control_codebook, control_tap, control_input, control_long_press, control_swipe, control_assert, control_wait, control_launch, ' +
5027
5202
  'webview, tap_css, tap_selector, type_text, wait_for, env_snapshot, env_restore, adb. ' +
5028
5203
  'WebView actions use Chrome DevTools Protocol (CDP): webview list|eval|click|wait_for|insert_text over the app WebView. ' +
@@ -5034,14 +5209,17 @@ export function apply(ctx, config = {}) {
5034
5209
  'Use shell for low-level Android commands, logcat for logs, ' +
5035
5210
  'setprop for system properties, packages to list apps, install to install+launch an APK by local path, ' +
5036
5211
  'push/pull to move files (under /data/local/tmp, /sdcard or /storage/emulated/0), reboot to restart the guest, ' +
5037
- 'rotate to lock orientation, ui_dump for the accessibility tree, record for a short MP4, perf for CPU/memory.',
5212
+ 'rotate to lock orientation, ui_dump for the accessibility tree, record for a short MP4, perf for CPU/memory. ' +
5213
+ 'Call action=guide to read the full agent playbook (docs/AGENTS.md) — it returns the Markdown itself: recommended workflow, coordinates/dpr, WebView and instance usage, and error handling. ' +
5214
+ 'The first apk_vm call in a new conversation returns this guide once (forced onboarding) and executes nothing: read it, then repeat your call. ' +
5215
+ 'The shared default VM is short-lived and shared by every conversation: for long-lived debugging claim a dedicated VM (ownerScope=conversation or project, or create_instance) instead of holding the shared one, and expect the guest to be reset to its home screen when another conversation enters it.',
5038
5216
  parameters: {
5039
5217
  type: 'object',
5040
5218
  additionalProperties: false,
5041
5219
  properties: {
5042
5220
  action: {
5043
5221
  type: 'string',
5044
- description: 'info|shell|logcat|getprop|setprop|packages|install|push|pull|reboot|root|force_stop|clear_data|uninstall|rotate|ui_dump|inspect_ui|proxy|install_ca|network|record|perf|screenshot|tap|swipe|long_press|key|text|apk_info|find_ui|assert_text|tap_text|clipboard_get|clipboard_set|devices|attach_device|detach_device|start|stop|list_instances|create_instance|destroy_instance|owner_status|claim_vm|release_vm|flow_start|flow_stop|flow_list|flow_replay|storage|clean_storage|skill_list|skill_get|skill_save|skill_delete|skill_start|skill_stop|skill_cancel|skill_run|skill_codebook|control_ui|control_features|control_codebook|control_tap|control_input|control_long_press|control_swipe|control_assert|control_wait|control_launch|webview|tap_css|tap_selector|type_text|wait_for|env_snapshot|env_restore|adb',
5222
+ description: TOOL_ACTIONS.join('|'),
5045
5223
  },
5046
5224
  instance: { type: 'string', description: 'Target VM instance id (default or an extra instance from list_instances). Omit for the calling Agent\'s assigned instance.' },
5047
5225
  ownerScope: { type: 'string', enum: ['shared', 'conversation', 'project'], description: 'VM ownership scope: shared (default), conversation (dedicated per DSH session), or project (dedicated per workspace).' },
@@ -5179,6 +5357,61 @@ export function apply(ctx, config = {}) {
5179
5357
  async executeInner(args, exec) {
5180
5358
  const action = String((args && args.action) || '').toLowerCase();
5181
5359
 
5360
+ // Reject unknown actions before any device/lease work: a typo must not
5361
+ // inherit a not-ready error or touch another session's VM.
5362
+ if (!TOOL_ACTIONS.includes(action)) {
5363
+ throw new Error(`unsupported apk_vm action: ${action}`);
5364
+ }
5365
+
5366
+ // The playbook is a pure read of a packaged Markdown file: no VM handle
5367
+ // is resolved, so agents can read it even before the environment exists.
5368
+ if (action === 'guide') {
5369
+ const markdown = readAgentGuide();
5370
+ if (markdown === null) {
5371
+ return {
5372
+ ok: false,
5373
+ summary: 'the agent guide is not bundled with this build (docs/AGENTS.md is missing)',
5374
+ result: { path: 'docs/AGENTS.md' },
5375
+ };
5376
+ }
5377
+ const guideOwner = toolOwnerContext(args, exec);
5378
+ if (guideOwner && guideOwner.sessionId) markGuideSessionSeen(guideOwner.sessionId);
5379
+ return {
5380
+ ok: true,
5381
+ // DSH renders the tool summary as the model-visible text, so the
5382
+ // playbook itself must be the summary; result stays small/JSON-safe.
5383
+ summary: markdown,
5384
+ result: { path: 'docs/AGENTS.md', chars: markdown.length, bytes: Buffer.byteLength(markdown, 'utf8') },
5385
+ };
5386
+ }
5387
+
5388
+ // Forced onboarding: the first apk_vm call in a fresh conversation
5389
+ // returns the playbook once and executes nothing (no VM handle, no
5390
+ // lease). Retrying the same action after reading it proceeds normally.
5391
+ if (cfg.guideOnNewSession !== false) {
5392
+ const ownerHint = toolOwnerContext(args, exec);
5393
+ const sessionId = ownerHint && ownerHint.sessionId;
5394
+ if (sessionId && !guideSessionSeen(sessionId)) {
5395
+ markGuideSessionSeen(sessionId);
5396
+ const markdown = readAgentGuide();
5397
+ if (markdown) {
5398
+ return {
5399
+ ok: true,
5400
+ summary:
5401
+ markdown +
5402
+ `\n\n---\n**One-time onboarding:** this guide was returned because this is the first apk_vm call in conversation \`${sessionId}\`; it is now marked as read. Your \`${action}\` call was not executed — repeat it to continue. The shared default VM is a short-lived shared device: for long-lived debugging claim a dedicated VM (ownerScope=conversation or create_instance).`,
5403
+ result: {
5404
+ guideRequired: true,
5405
+ guidePath: 'docs/AGENTS.md',
5406
+ requestedAction: action,
5407
+ sessionId,
5408
+ next: 'repeat the same apk_vm call after reading this guide',
5409
+ },
5410
+ };
5411
+ }
5412
+ }
5413
+ }
5414
+
5182
5415
  // Resolve the VM handle lazily: only actions that actually reach the
5183
5416
  // device should trigger owner assignment/leasing.
5184
5417
  let toolApiPromise = null;
@@ -5195,6 +5428,7 @@ export function apply(ctx, config = {}) {
5195
5428
  id: 'default',
5196
5429
  kind: 'default',
5197
5430
  avdName: defaultStatus.avd || vm.avdName || null,
5431
+ name: instanceManager ? instanceManager.nameFor('default', defaultStatus.avd || vm.avdName) : defaultStatus.avd || vm.avdName || null,
5198
5432
  port: vm.port || null,
5199
5433
  state: defaultStatus.state,
5200
5434
  serial: defaultStatus.serial || null,
@@ -5208,7 +5442,7 @@ export function apply(ctx, config = {}) {
5208
5442
  ];
5209
5443
  return {
5210
5444
  ok: true,
5211
- summary: instances.map((entry) => `${entry.id}:${entry.state}${entry.serial ? '@' + entry.serial : ''}${entry.ownerInfo ? ' owned:' + entry.ownerInfo.label : ''}`).join(', '),
5445
+ summary: instances.map((entry) => `${entry.name || entry.id}:${entry.state}${entry.serial ? '@' + entry.serial : ''}${entry.ownerInfo ? ' owned:' + entry.ownerInfo.label : ''}`).join(', '),
5212
5446
  result: { instances, maxInstances: instanceManager ? instanceManager.maxInstances : 1 },
5213
5447
  };
5214
5448
  }
@@ -5228,6 +5462,13 @@ export function apply(ctx, config = {}) {
5228
5462
  result: { id: instance.id, avdName: instance.avdName, port: instance.port, owner: ownerInfo },
5229
5463
  };
5230
5464
  }
5465
+ if (action === 'rename_instance') {
5466
+ if (!instanceManager) throw new Error('multi-instance support is disabled');
5467
+ const id = String(args.instance || args.name || 'default');
5468
+ const result = await instanceManager.rename(id, args.name || args.instanceName || args.newName || args.label);
5469
+ if (!result.ok) throw new Error(result.error || 'rename failed');
5470
+ return { ok: true, summary: `renamed ${result.id} to ${result.name}`, result };
5471
+ }
5231
5472
  if (action === 'destroy_instance') {
5232
5473
  if (!instanceManager) throw new Error('multi-instance support is disabled');
5233
5474
  const id = args.instance || args.name;
@@ -5606,6 +5847,13 @@ export function apply(ctx, config = {}) {
5606
5847
  const snapshot = await api.stop();
5607
5848
  return { ok: true, summary: `stopped ${api.id}`, result: snapshot || {} };
5608
5849
  }
5850
+ // Local push/pull paths are validated before the device readiness gate:
5851
+ // an outside-roots or missing local file must fail with an actionable
5852
+ // error even when the VM is stopped, booting or wedged.
5853
+ let prevalidatedLocalPath;
5854
+ if (action === 'push' || action === 'pull') {
5855
+ prevalidatedLocalPath = resolveDebugLocal(args.path, action === 'push');
5856
+ }
5609
5857
  const status = await ensureToolApiReady(api, action);
5610
5858
  switch (action) {
5611
5859
  case 'info': {
@@ -5797,12 +6045,12 @@ export function apply(ctx, config = {}) {
5797
6045
  return { ok: true, summary: `${api.id}: installed ${installed.packageName} (${installed.label})`, result: installed };
5798
6046
  }
5799
6047
  case 'push': {
5800
- const localPath = resolveDebugLocal(args.path, true);
6048
+ const localPath = prevalidatedLocalPath || resolveDebugLocal(args.path, true);
5801
6049
  const result = await api.pushFile(localPath, args.remotePath);
5802
6050
  return { ok: true, summary: `pushed ${localPath} -> ${result.remotePath}`, result };
5803
6051
  }
5804
6052
  case 'pull': {
5805
- const localPath = resolveDebugLocal(args.path, false);
6053
+ const localPath = prevalidatedLocalPath || resolveDebugLocal(args.path, false);
5806
6054
  const result = await api.pullFile(args.remotePath, localPath);
5807
6055
  return { ok: true, summary: `pulled ${args.remotePath} -> ${result.localPath}`, result };
5808
6056
  }
package/lib/android.js CHANGED
@@ -46,7 +46,7 @@
46
46
 
47
47
  import { spawn } from 'node:child_process';
48
48
  import { createHash } from 'node:crypto';
49
- import { existsSync, readdirSync, statSync } from 'node:fs';
49
+ import { existsSync, readdirSync, renameSync, statSync } from 'node:fs';
50
50
  import { promises as fsp } from 'node:fs';
51
51
  import os from 'node:os';
52
52
  import path from 'node:path';
@@ -902,9 +902,12 @@ export class AndroidVm {
902
902
  // Boot-speed bookkeeping (exposed by status()).
903
903
  this._bootKind = null; // 'cold' | 'snapshot' | 'attach'
904
904
  this._snapshotAvailable = null;
905
+ this._snapshotLoadFailed = false;
906
+ this._snapshotSuspicion = null;
907
+ this._snapshotRecovery = null;
908
+ this._snapshotRecoveryAttempted = false;
905
909
  this._accelAvailable = null;
906
910
  this._snapshotSave = null;
907
- this._snapshotLoadFailed = false;
908
911
  this._lastLaunchArgs = null;
909
912
 
910
913
  // Rooted / debuggable guest state (exposed by status()).
@@ -4233,6 +4236,7 @@ export class AndroidVm {
4233
4236
  this._sawNotBooted = false;
4234
4237
  this._bootProbe = { serial: null, at: 0, booted: false };
4235
4238
  if (this._error) this._error = null;
4239
+ this._snapshotRecoveryAttempted = false;
4236
4240
  this._pushLog(`[vm] start requested (adb=${this.adbPath})`);
4237
4241
 
4238
4242
  let devices = await this._listDevices();
@@ -4321,12 +4325,60 @@ export class AndroidVm {
4321
4325
  try {
4322
4326
  // A real emulator quick-boot snapshot has snapshot.pb; a leftover
4323
4327
  // `ram.img` from a crashed `-mem-path` run is NOT a restorable snapshot.
4324
- return existsSync(path.join(snap, 'snapshot.pb'));
4328
+ const pb = path.join(snap, 'snapshot.pb');
4329
+ if (!existsSync(pb)) return false;
4330
+ const pbStat = statSync(pb);
4331
+ if (!pbStat || pbStat.size <= 0) return false;
4332
+ // A crash while `snapshot save` was running can leave the control file
4333
+ // newer than the RAM image it points at; restoring such a set crashes
4334
+ // the emulator (Windows access violation 0xC0000005). Treat an obviously
4335
+ // inconsistent set as unusable so the cold-boot path rebuilds it.
4336
+ const ram = path.join(snap, 'ram.bin');
4337
+ if (existsSync(ram)) {
4338
+ const ramStat = statSync(ram);
4339
+ if (ramStat.size < 64 * 1024 * 1024) return false;
4340
+ if (pbStat.mtimeMs - ramStat.mtimeMs > 10 * 60 * 1000) {
4341
+ this._snapshotSuspicion = 'snapshot.pb is much newer than ram.bin (partial snapshot save)';
4342
+ return false;
4343
+ }
4344
+ }
4345
+ return true;
4325
4346
  } catch {
4326
4347
  return false;
4327
4348
  }
4328
4349
  }
4329
4350
 
4351
+ /**
4352
+ * Move a broken quick-boot snapshot aside so the next launch takes the cold
4353
+ * boot path without ever asking the emulator to restore corrupt state.
4354
+ * Returns the quarantine path, or null when there was nothing to move.
4355
+ */
4356
+ _quarantineSnapshot(reason) {
4357
+ try {
4358
+ const dir = this._avdDirectory();
4359
+ if (!dir) return null;
4360
+ const snap = path.join(dir, 'snapshots', this.snapshotName);
4361
+ if (!existsSync(snap)) return null;
4362
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
4363
+ const target = `${snap}.${reason}-${stamp}`;
4364
+ renameSync(snap, target);
4365
+ this._snapshotAvailable = false;
4366
+ this._snapshotLoadFailed = true;
4367
+ this._snapshotSuspicion = null;
4368
+ this._snapshotRecovery = {
4369
+ reason,
4370
+ at: Date.now(),
4371
+ avdName: this.avdName,
4372
+ snapshotName: this.snapshotName,
4373
+ quarantinedPath: target,
4374
+ };
4375
+ return target;
4376
+ } catch (error) {
4377
+ this._pushLog(`[vm] snapshot quarantine failed: ${error && error.message ? error.message : error}`);
4378
+ return null;
4379
+ }
4380
+ }
4381
+
4330
4382
  /**
4331
4383
  * Detect a usable CPU hypervisor (AEHD / WHPX / KVM / HAXM / HVF) through the
4332
4384
  * SDK's `emulator-check accel`. Returns false when only software TCG is
@@ -4556,6 +4608,36 @@ export class AndroidVm {
4556
4608
 
4557
4609
  await this.waitBooted(this.bootTimeoutMs);
4558
4610
  if (epoch !== this._waitEpoch) return; // stop() interrupted this run
4611
+ // Restoring a corrupt quick-boot snapshot can crash the emulator outright
4612
+ // (Windows status 0xC0000005) before adbd ever appears. Quarantine the
4613
+ // snapshot and retry once as a cold boot; the cold boot rebuilds it.
4614
+ if (
4615
+ this._state === 'error' &&
4616
+ this._bootKind === 'snapshot' &&
4617
+ this.quickBoot &&
4618
+ !this._snapshotRecoveryAttempted &&
4619
+ (this._snapshotLoadFailed || /emulator exited \(code [^)]*\)/.test(String(this._error || '')))
4620
+ ) {
4621
+ this._snapshotRecoveryAttempted = true;
4622
+ this._pushLog('[vm] quick-boot snapshot failed to restore; retrying with a cold boot');
4623
+ const quarantined = this._quarantineSnapshot('corrupt');
4624
+ this._pushLog(
4625
+ quarantined
4626
+ ? `[vm] quarantined broken snapshot -> ${quarantined}`
4627
+ : '[vm] no snapshot directory to quarantine',
4628
+ );
4629
+ this._bootKind = 'cold';
4630
+ this._setState('starting');
4631
+ if (this._child && this._child.exitCode === null) {
4632
+ try {
4633
+ this._child.kill();
4634
+ } catch {
4635
+ /* already gone */
4636
+ }
4637
+ }
4638
+ this._child = null;
4639
+ return this._spawnEmulatorAndWait(epoch);
4640
+ }
4559
4641
  if (this._state === 'ready') {
4560
4642
  if (this._bootKind === 'snapshot' && this._snapshotLoadFailed) {
4561
4643
  this._bootKind = 'cold';
@@ -4994,6 +5076,7 @@ export class AndroidVm {
4994
5076
  quickBoot: this.quickBoot,
4995
5077
  snapshotName: this.snapshotName,
4996
5078
  snapshotAvailable: this._snapshotAvailable === true || this._snapshotPresent(),
5079
+ snapshotRecovery: this._snapshotRecovery ? { ...this._snapshotRecovery } : null,
4997
5080
  gpuMode: this.gpuMode,
4998
5081
  accel: this._accelAvailable,
4999
5082
  root: this._root === true,
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Persistent, human-friendly display names for APK VM instances.
3
+ *
4
+ * Instance ids stay stable and URL-safe (`default`, `frontend`, `remote-…`);
5
+ * the display name is what the panel and agents show. Names live next to the
6
+ * other plugin state (`<dataDir>/.apk-vm/instance-names.json`) so they survive
7
+ * DSH restarts, plugin upgrades and AVD recreation.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { promises as fsp } from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ export const INSTANCE_NAMES_VERSION = 1;
14
+ export const MAX_INSTANCE_NAME_LENGTH = 48;
15
+ const DEFAULT_MAX_NAMES = 200;
16
+
17
+ /** Trim and flatten a user-supplied name; returns '' when nothing is usable. */
18
+ export function sanitizeDisplayName(value) {
19
+ return String(value === undefined || value === null ? '' : value)
20
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
21
+ .replace(/\s+/g, ' ')
22
+ .trim()
23
+ .slice(0, MAX_INSTANCE_NAME_LENGTH);
24
+ }
25
+
26
+ export function defaultInstanceNamesPath(dataDir) {
27
+ return path.join(String(dataDir || process.cwd()), '.apk-vm', 'instance-names.json');
28
+ }
29
+
30
+ /** In-memory view of the name map, persisted with atomic rename writes. */
31
+ export class InstanceNameBook {
32
+ constructor({ file = null, maxEntries = DEFAULT_MAX_NAMES } = {}) {
33
+ this.file = file ? String(file) : null;
34
+ this.maxEntries = Math.max(1, Number(maxEntries) || DEFAULT_MAX_NAMES);
35
+ this._names = new Map();
36
+ this._loaded = false;
37
+ }
38
+
39
+ _load() {
40
+ if (this._loaded) return;
41
+ this._loaded = true;
42
+ if (!this.file) return;
43
+ try {
44
+ const raw = readFileSync(this.file, 'utf8');
45
+ const parsed = JSON.parse(String(raw).replace(/^\uFEFF/, ''));
46
+ const entries = parsed && typeof parsed === 'object'
47
+ ? parsed.version === INSTANCE_NAMES_VERSION && parsed.names && typeof parsed.names === 'object'
48
+ ? parsed.names
49
+ : parsed.names && typeof parsed.names === 'object'
50
+ ? parsed.names
51
+ : parsed
52
+ : {};
53
+ for (const [id, value] of Object.entries(entries)) {
54
+ const name = sanitizeDisplayName(value);
55
+ const key = String(id || '').trim();
56
+ if (!key || !name) continue;
57
+ this._names.set(key, name);
58
+ if (this._names.size >= this.maxEntries) break;
59
+ }
60
+ } catch {
61
+ /* a missing or corrupt file simply starts empty */
62
+ }
63
+ }
64
+
65
+ /** Current display name for an id, or '' when none was set. */
66
+ get(id) {
67
+ this._load();
68
+ const key = String(id || '').trim();
69
+ return key ? this._names.get(key) || '' : '';
70
+ }
71
+
72
+ /** Id → display-name snapshot (for diagnostics/tests). */
73
+ list() {
74
+ this._load();
75
+ return Object.fromEntries(this._names);
76
+ }
77
+
78
+ _snapshot() {
79
+ this._load();
80
+ return Object.fromEntries(this._names);
81
+ }
82
+
83
+ async _persist() {
84
+ if (!this.file) return { ok: true };
85
+ const dir = path.dirname(this.file);
86
+ const text = JSON.stringify(
87
+ { version: INSTANCE_NAMES_VERSION, names: this._snapshot() },
88
+ null,
89
+ 2
90
+ ) + '\n';
91
+ try {
92
+ await fsp.mkdir(dir, { recursive: true });
93
+ const tmp = `${this.file}.tmp-${process.pid}-${Date.now()}`;
94
+ await fsp.writeFile(tmp, text, 'utf8');
95
+ await fsp.rename(tmp, this.file);
96
+ return { ok: true };
97
+ } catch (error) {
98
+ return { ok: false, error: `could not persist instance names: ${error && error.message ? error.message : error}` };
99
+ }
100
+ }
101
+
102
+ async set(id, name) {
103
+ const key = String(id || '').trim();
104
+ const clean = sanitizeDisplayName(name);
105
+ if (!key) return { ok: false, error: 'instance id is required' };
106
+ if (!clean) return { ok: false, error: 'name is required' };
107
+ this._load();
108
+ this._names.set(key, clean);
109
+ if (this._names.size > this.maxEntries) {
110
+ const oldest = this._names.keys().next().value;
111
+ if (oldest && oldest !== key) this._names.delete(oldest);
112
+ }
113
+ const saved = await this._persist();
114
+ if (!saved.ok) return saved;
115
+ return { ok: true, id: key, name: clean };
116
+ }
117
+
118
+ async delete(id) {
119
+ this._load();
120
+ const key = String(id || '').trim();
121
+ if (!key || !this._names.has(key)) return { ok: true, removed: false };
122
+ this._names.delete(key);
123
+ const saved = await this._persist();
124
+ if (!saved.ok) return saved;
125
+ return { ok: true, removed: true };
126
+ }
127
+ }