-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathandroid.mjs
More file actions
955 lines (913 loc) · 25.2 KB
/
Copy pathandroid.mjs
File metadata and controls
955 lines (913 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
#!/usr/bin/env node
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { connect } from "simdeck/test";
const root = fileURLToPath(new URL("../..", import.meta.url));
const simdeck = resolveSimDeckCli();
const verbose = process.env.SIMDECK_INTEGRATION_VERBOSE === "1";
const keepAndroid = process.env.SIMDECK_INTEGRATION_KEEP_ANDROID === "1";
const bootAndroid = process.env.SIMDECK_INTEGRATION_BOOT_ANDROID === "1";
const requireRunningAndroid =
process.env.SIMDECK_INTEGRATION_REQUIRE_RUNNING_ANDROID === "1" ||
process.env.CI === "true";
const requestedAvd = process.env.SIMDECK_INTEGRATION_ANDROID_AVD;
const requestedAndroidLaunchTarget =
process.env.SIMDECK_INTEGRATION_ANDROID_LAUNCH_TARGET;
const defaultStepTimeoutMs = Number(
process.env.SIMDECK_INTEGRATION_STEP_TIMEOUT_MS ?? "180000",
);
let session = null;
let androidUDID = "";
let androidLaunchTarget = null;
let shutdownAndroidAfterRun = false;
const stepTimings = [];
process.on("SIGINT", () => {
cleanupSync();
process.exit(130);
});
process.on("SIGTERM", () => {
cleanupSync();
process.exit(143);
});
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error?.stack ?? error);
process.exit(1);
});
async function main() {
try {
if (!fs.existsSync(simdeck)) {
throw new Error(`Missing ${simdeck}. Run npm run build:cli first.`);
}
if (
!fs.existsSync(
path.join(root, "packages", "simdeck-test", "dist", "index.js"),
)
) {
throw new Error(
"Missing simdeck/test dist. Run npm run build:simdeck-test first.",
);
}
session = await measuredStep("simdeck/test isolated connect", () =>
connect({
cliPath: simdeck,
projectRoot: root,
isolated: true,
videoCodec: "software",
}),
);
console.log(`service ${session.endpoint}`);
const target = await measuredStep("resolve Android AVD", () =>
resolveAndroidDevice(),
);
if (!target) {
console.log(
"No Android AVDs discovered; skipping Android integration suite.",
);
return;
}
androidUDID = target.udid;
console.log(
`android target ${androidUDID} (${target.name})${
target.isBooted ? " already booted" : ""
}`,
);
if (!target.isBooted && !bootAndroid) {
const message = `${androidUDID} is not running. Start the emulator first or set SIMDECK_INTEGRATION_BOOT_ANDROID=1 to let SimDeck boot it.`;
if (requireRunningAndroid) {
throw new Error(message);
}
console.log(`${message} Skipping Android integration suite.`);
return;
}
shutdownAndroidAfterRun = !target.isBooted && bootAndroid && !keepAndroid;
await measuredStep(
target.isBooted
? "JS boot Android idempotent"
: "JS boot Android emulator",
async () => {
await session.boot(androidUDID);
await waitForBooted(androidUDID);
},
{ timeoutMs: target.isBooted ? 120_000 : 300_000 },
);
androidLaunchTarget = await measuredStep(
"resolve Android launch target",
() => resolveAndroidLaunchTarget(),
{ timeoutMs: 60_000 },
);
await runCliSurface();
await runJsSurface();
console.log("SimDeck Android integration suite passed");
} finally {
await cleanupAndroid();
cleanupSync();
printTimingSummary();
}
}
async function runCliSurface() {
await measuredStep("CLI list includes Android", () => {
assertAndroidListed(simdeckJson(["list"]), androidUDID);
});
await measuredStep(
"CLI boot Android idempotent",
() => assertJson(simdeckJson(["boot", androidUDID]), "boot"),
{ timeoutMs: 180_000 },
);
await measuredStep("CLI chrome-profile", () => {
const profile = simdeckJson(["chrome-profile", androidUDID]);
assertJson(profile, "chrome-profile");
assert.ok(Number(profile.screenWidth) > 0, "missing Android screenWidth");
assert.ok(Number(profile.screenHeight) > 0, "missing Android screenHeight");
});
const tree = await measuredStep("CLI describe Android tree", async () => {
const payload = await retryAsync(
() =>
simdeckJson([
"describe",
androidUDID,
"--source",
"android-uiautomator",
"--format",
"compact-json",
"--max-depth",
"2",
]),
"CLI describe Android tree",
{ attempts: 8, delayMs: 2_000 },
);
assertRoots(payload, "CLI describe");
return payload;
});
await measuredStep("CLI describe Android point", async () => {
const point = centerOfFirstRoot(tree);
if (!point) {
throw new Error("Unable to derive point from Android tree root.");
}
assertRoots(
await retryAsync(
() =>
simdeckJson([
"describe",
androidUDID,
"--source",
"android-uiautomator",
"--format",
"compact-json",
"--point",
`${point.x},${point.y}`,
"--max-depth",
"1",
]),
"CLI describe Android point",
{ attempts: 4, delayMs: 1_000 },
),
"CLI point describe",
);
});
await measuredStep("CLI screenshot stdout", () => {
assertPngBuffer(
runBuffer(
simdeck,
[
"--server-url",
session.endpoint,
"screenshot",
androidUDID,
"--stdout",
],
{ timeoutMs: 120_000, maxBuffer: 64 * 1024 * 1024 },
),
);
});
await measuredStep("CLI pasteboard behavior", () => {
const setResult = runCommand(
simdeck,
[
"--server-url",
session.endpoint,
"pasteboard",
"set",
androidUDID,
"simdeck android cli",
],
{ timeoutMs: 60_000 },
);
if (setResult.status !== 0) {
assertClipboardUnsupported(setResult);
return;
}
try {
const payload = simdeckJson(["pasteboard", "get", androidUDID]);
assert.equal(payload.text, "simdeck android cli");
} catch (error) {
assertClipboardUnsupported(error);
}
});
await measuredStep("CLI app launch and URL", () => {
if (androidLaunchTarget) {
try {
simdeckJson(["launch", androidUDID, androidLaunchTarget], {
timeoutMs: 60_000,
});
} catch (error) {
if (
requestedAndroidLaunchTarget ||
!isAndroidIntentUnavailable(error)
) {
throw error;
}
console.log(
`Android image rejected discovered launch target ${androidLaunchTarget}; continuing with URL/home coverage.`,
);
}
} else {
console.log("Android image did not expose a launchable activity.");
}
try {
simdeckJson(["open-url", androidUDID, "https://example.com"], {
timeoutMs: 60_000,
});
} catch (error) {
if (!isAndroidIntentUnavailable(error)) {
throw error;
}
console.log("Android image did not expose an https URL handler.");
}
simdeckJson(["home", androidUDID]);
});
await measuredStep("CLI pointer gestures", () => {
simdeckJson([
"tap",
androidUDID,
"0.5",
"0.5",
"--normalized",
"--duration-ms",
"20",
]);
simdeckJson([
"touch",
androidUDID,
"0.5",
"0.5",
"--phase",
"began",
"--normalized",
]);
simdeckJson([
"touch",
androidUDID,
"0.5",
"0.5",
"--phase",
"ended",
"--normalized",
]);
simdeckJson([
"swipe",
androidUDID,
"0.5",
"0.75",
"0.5",
"0.25",
"--normalized",
"--duration-ms",
"120",
"--steps",
"4",
]);
simdeckJson([
"gesture",
androidUDID,
"scroll-down",
"--duration-ms",
"120",
"--delta",
"0.2",
]);
});
await measuredStep("CLI keyboard and system controls", () => {
simdeckJson(["key", androidUDID, "enter"]);
simdeckJson([
"key-sequence",
androidUDID,
"--keycodes",
"h,e,l,l,o",
"--delay-ms",
"5",
]);
simdeckJson([
"key-combo",
androidUDID,
"--modifiers",
"shift",
"--key",
"h",
]);
simdeckJson(["type", androidUDID, "simdeck"]);
simdeckJson(["dismiss-keyboard", androidUDID]);
simdeckJson(["button", androidUDID, "back"]);
simdeckJson(["app-switcher", androidUDID]);
simdeckJson(["home", androidUDID]);
});
await measuredStep("CLI rotation and appearance restore", () => {
simdeckJson(["rotate-left", androidUDID], { timeoutMs: 60_000 });
simdeckJson(["rotate-right", androidUDID], { timeoutMs: 60_000 });
simdeckJson(["toggle-appearance", androidUDID], { timeoutMs: 60_000 });
simdeckJson(["toggle-appearance", androidUDID], { timeoutMs: 60_000 });
});
await measuredStep("CLI logs", () => {
const payload = simdeckJson([
"logs",
androidUDID,
"--seconds",
"1",
"--limit",
"5",
]);
assert.ok(
Array.isArray(payload.entries),
"CLI logs did not return entries",
);
});
}
async function runJsSurface() {
await measuredStep("JS list includes Android", async () => {
assertAndroidListed(await session.list(), androidUDID);
});
await measuredStep("JS chromeProfile", async () => {
const profile = await session.chromeProfile(androidUDID);
assertJson(profile, "chromeProfile");
});
await measuredStep("JS Android tree", async () => {
assertRoots(
await retryAsync(
() =>
session.tree(androidUDID, {
source: "android-uiautomator",
maxDepth: 2,
}),
"JS Android tree",
{ attempts: 6, delayMs: 2_000 },
),
"JS tree",
);
});
await measuredStep("JS screenshot", async () => {
assertPngBuffer(await session.screenshot(androidUDID));
});
await measuredStep("JS pasteboard behavior", async () => {
try {
await session.pasteboardSet(androidUDID, "simdeck android js");
assert.equal(
await session.pasteboardGet(androidUDID),
"simdeck android js",
);
} catch (error) {
assertClipboardUnsupported(error);
}
});
await measuredStep("JS app launch and URL", async () => {
if (androidLaunchTarget) {
try {
await session.launch(androidUDID, androidLaunchTarget);
} catch (error) {
if (
requestedAndroidLaunchTarget ||
!isAndroidIntentUnavailable(error)
) {
throw error;
}
console.log(
`Android image rejected discovered launch target ${androidLaunchTarget}; continuing with URL/home coverage.`,
);
}
}
try {
await session.openUrl(androidUDID, "https://example.com");
} catch (error) {
if (!isAndroidIntentUnavailable(error)) {
throw error;
}
console.log("Android image did not expose an https URL handler.");
}
await session.home(androidUDID);
});
await measuredStep("JS pointer gestures", async () => {
await session.tap(androidUDID, 0.5, 0.5);
await session.touch(androidUDID, 0.5, 0.5, "began");
await session.touch(androidUDID, 0.5, 0.5, "ended");
await session.swipe(androidUDID, 0.5, 0.75, 0.5, 0.25, {
durationMs: 120,
steps: 4,
});
await session.gesture(androidUDID, "scroll-down", {
durationMs: 120,
delta: 0.2,
});
});
await measuredStep("JS keyboard and system controls", async () => {
await session.key(androidUDID, 40);
await session.keySequence(androidUDID, [11, 8, 15, 15, 18], {
delayMs: 5,
});
await session.typeText(androidUDID, "simdeck");
await session.dismissKeyboard(androidUDID);
await session.button(androidUDID, "back");
await session.appSwitcher(androidUDID);
await session.home(androidUDID);
});
await measuredStep("JS rotation and appearance restore", async () => {
await session.rotateLeft(androidUDID);
await session.rotateRight(androidUDID);
await session.toggleAppearance(androidUDID);
await session.toggleAppearance(androidUDID);
});
await measuredStep("JS logs", async () => {
assert.ok(
Array.isArray(await session.logs(androidUDID, { limit: 5, seconds: 1 })),
"JS logs did not return entries",
);
});
await measuredStep("JS batch Android controls", async () => {
const payload = await session.batch(androidUDID, [
{
action: "touchSequence",
events: [
{ x: 0.5, y: 0.5, phase: "began", delayMsAfter: 20 },
{ x: 0.5, y: 0.5, phase: "ended" },
],
},
{
action: "swipe",
startX: 0.5,
startY: 0.75,
endX: 0.5,
endY: 0.25,
durationMs: 100,
steps: 4,
},
{ action: "key", keyCode: 40 },
{ action: "home" },
{ action: "describe", source: "android-uiautomator", maxDepth: 1 },
]);
assertJson(payload, "JS batch");
});
}
function resolveAndroidDevice() {
const emulator = androidSdkTool("emulator/emulator");
if (!emulator) {
if (requestedAvd) {
throw new Error("Android SDK emulator binary was not found.");
}
return null;
}
const avds = runText(emulator, ["-list-avds"], { timeoutMs: 30_000 })
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (requestedAvd) {
const avdName = requestedAvd.replace(/^android:/, "");
const running = runningAndroidAvds(avdName);
if (!avds.includes(avdName)) {
throw new Error(
`SIMDECK_INTEGRATION_ANDROID_AVD=${requestedAvd} was not found. Available Android AVDs: ${avds.join(", ")}`,
);
}
return {
udid: `android:${avdName}`,
name: avdName,
isBooted: running.has(avdName),
};
}
const running = runningAndroidAvds();
const avdName = avds[0];
return avdName
? {
udid: `android:${avdName}`,
name: avdName,
isBooted: running.has(avdName),
}
: null;
}
function resolveAndroidLaunchTarget() {
if (requestedAndroidLaunchTarget) {
return requestedAndroidLaunchTarget;
}
const adb = androidSdkTool("platform-tools/adb");
if (!adb) {
return null;
}
const serial = onlineAndroidSerials(adb)[0];
if (!serial) {
return null;
}
const queries = [
[
"cmd",
"package",
"query-activities",
"--brief",
"--components",
"-a",
"android.intent.action.MAIN",
"-c",
"android.intent.category.LAUNCHER",
],
[
"cmd",
"package",
"query-activities",
"--brief",
"--components",
"-a",
"android.intent.action.MAIN",
],
[
"cmd",
"package",
"resolve-activity",
"--brief",
"--components",
"-a",
"android.intent.action.MAIN",
"-c",
"android.intent.category.LAUNCHER",
],
[
"cmd",
"package",
"resolve-activity",
"--brief",
"--components",
"-a",
"android.intent.action.MAIN",
],
];
for (const query of queries) {
try {
const output = runText(adb, ["-s", serial, "shell", ...query], {
timeoutMs: 30_000,
});
const target = chooseAndroidLaunchComponent(
parseAndroidActivityComponents(output),
);
if (target) {
if (verbose) {
console.log(`Android launch target ${target}`);
}
return target;
}
} catch (error) {
if (verbose) {
console.log(
`Android launch target query failed: ${error.message.split("\n")[0]}`,
);
}
}
}
return null;
}
function parseAndroidActivityComponents(output) {
const components = [];
for (const line of output.split(/\r?\n/)) {
for (const token of line.trim().split(/\s+/)) {
if (
/^[A-Za-z0-9_.]+\/(?:[A-Za-z0-9_.$]+|\.[A-Za-z0-9_.$]+)$/.test(token)
) {
components.push(token);
}
}
}
return [...new Set(components)];
}
function chooseAndroidLaunchComponent(components) {
const preferredPackages = [
"com.android.settings/",
"com.google.android.apps.nexuslauncher/",
"com.android.launcher3/",
];
for (const packagePrefix of preferredPackages) {
const component = components.find((value) =>
value.startsWith(packagePrefix),
);
if (component) {
return component;
}
}
return (
components.find(
(value) =>
!value.startsWith("com.android.systemui/") &&
!value.startsWith("android/"),
) ?? null
);
}
function runningAndroidAvds(fallbackAvdName = "") {
const adb = androidSdkTool("platform-tools/adb");
if (!adb) {
return new Set();
}
const devices = onlineAndroidSerials(adb);
const avds = new Set();
for (const serial of devices) {
const name = androidAvdNameForSerial(adb, serial);
if (name) {
avds.add(name);
}
}
if (fallbackAvdName && avds.size === 0 && devices.length === 1) {
avds.add(fallbackAvdName);
}
return avds;
}
function onlineAndroidSerials(adb) {
return runText(adb, ["devices"], { timeoutMs: 30_000 })
.split(/\r?\n/)
.map((line) => line.trim().split(/\s+/))
.filter(
([serial, state]) =>
serial?.startsWith("emulator-") && state === "device",
)
.map(([serial]) => serial);
}
function androidAvdNameForSerial(adb, serial) {
for (const property of ["ro.boot.qemu.avd_name", "ro.kernel.qemu.avd_name"]) {
try {
const name = runText(adb, ["-s", serial, "shell", "getprop", property], {
timeoutMs: 10_000,
}).trim();
if (name) {
return name;
}
} catch {
// Fall through to the next lookup. ADB can briefly expose devices
// before every shell service is ready.
}
}
try {
return runText(adb, ["-s", serial, "emu", "avd", "name"], {
timeoutMs: 10_000,
})
.split(/\r?\n/)
.map((line) => line.trim())
.find((line) => line && line !== "OK");
} catch {
return null;
}
}
function androidSdkTool(relativePath) {
const roots = [
process.env.ANDROID_HOME,
process.env.ANDROID_SDK_ROOT,
process.platform === "win32"
? path.join(os.homedir(), "AppData", "Local", "Android", "Sdk")
: null,
path.join(os.homedir(), "Library", "Android", "sdk"),
path.join(os.homedir(), "Android", "Sdk"),
].filter(Boolean);
for (const root of roots) {
const candidate = androidSdkToolCandidate(root, relativePath);
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
function resolveSimDeckCli() {
const candidates =
process.platform === "win32"
? ["simdeck-bin.exe", "simdeck-bin-win32-x64.exe", "simdeck"]
: ["simdeck", "simdeck-bin"];
for (const candidate of candidates) {
const absolute = path.join(root, "build", candidate);
if (fs.existsSync(absolute)) {
return absolute;
}
}
return path.join(
root,
"build",
process.platform === "win32" ? "simdeck-bin.exe" : "simdeck",
);
}
function androidSdkToolCandidate(root, relativePath) {
const candidate = path.join(root, relativePath);
if (process.platform !== "win32" || path.extname(candidate)) {
return candidate;
}
return `${candidate}.exe`;
}
function simulatorList(payload) {
return Array.isArray(payload?.simulators) ? payload.simulators : [];
}
async function waitForBooted(udid) {
const avdName = udid.replace(/^android:/, "");
const deadline = Date.now() + 180_000;
while (Date.now() < deadline) {
if (runningAndroidAvds().has(avdName)) {
return;
}
await sleep(1_000);
}
throw new Error(`Timed out waiting for ${udid} to boot.`);
}
async function cleanupAndroid() {
if (!session || !androidUDID || !shutdownAndroidAfterRun) {
return;
}
try {
await measuredStep("shutdown Android emulator", () =>
session.shutdown(androidUDID),
);
} catch (error) {
console.error(`Failed to shutdown ${androidUDID}: ${error.message}`);
}
}
function cleanupSync() {
if (session) {
session.close();
session = null;
}
}
async function measuredStep(label, run, options = {}) {
const started = process.hrtime.bigint();
let timeoutId = null;
if (verbose) {
console.log(`> ${label}`);
}
try {
const timeoutMs = options.timeoutMs ?? defaultStepTimeoutMs;
const result = await Promise.race([
Promise.resolve().then(run),
new Promise((_, reject) => {
timeoutId = setTimeout(
() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
timeoutMs,
);
}),
]);
const elapsedMs = Number(process.hrtime.bigint() - started) / 1_000_000;
stepTimings.push({ label, elapsedMs });
if (verbose) {
console.log(`ok ${label} ${elapsedMs.toFixed(1)}ms`);
}
if (options.timeoutMs && elapsedMs > options.timeoutMs) {
throw new Error(
`${label} exceeded ${options.timeoutMs}ms budget (${elapsedMs.toFixed(
1,
)}ms)`,
);
}
return result;
} catch (error) {
const elapsedMs = Number(process.hrtime.bigint() - started) / 1_000_000;
console.error(`fail ${label} ${elapsedMs.toFixed(1)}ms`);
throw error;
} finally {
if (timeoutId) {
clearTimeout(timeoutId);
}
}
}
async function retryAsync(run, label, options = {}) {
const attempts = options.attempts ?? 3;
const delayMs = options.delayMs ?? 1_000;
let lastError = null;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await run();
} catch (error) {
lastError = error;
if (attempt < attempts) {
if (verbose) {
console.log(
`${label} attempt ${attempt}/${attempts} failed: ${error.message}`,
);
}
await sleep(delayMs);
}
}
}
throw lastError;
}
function printTimingSummary() {
if (!verbose || stepTimings.length === 0) {
return;
}
console.log("\nTiming summary:");
for (const entry of stepTimings) {
console.log(` ${entry.label.padEnd(36)} ${entry.elapsedMs.toFixed(1)}ms`);
}
}
function simdeckJson(args, options = {}) {
return JSON.parse(
runText(simdeck, ["--server-url", session.endpoint, ...args], options),
);
}
function runText(command, args, options = {}) {
return runBuffer(command, args, options).toString("utf8").trim();
}
function runBuffer(command, args, options = {}) {
const result = runCommand(command, args, options);
if (result.status !== 0) {
throw new Error(
`${[command, ...args].join(" ")} failed with ${result.status}\n${result.stderr}`,
);
}
return result.stdoutBuffer ?? Buffer.alloc(0);
}
function runCommand(command, args, options = {}) {
if (verbose) {
console.log(`$ ${[command, ...args].join(" ")}`);
}
const result = spawnSync(command, args, {
cwd: root,
encoding: null,
timeout: options.timeoutMs ?? 120_000,
maxBuffer: options.maxBuffer ?? 4 * 1024 * 1024,
});
return {
status: result.status ?? 1,
stdout: (result.stdout ?? Buffer.alloc(0)).toString("utf8"),
stderr: (result.stderr ?? Buffer.alloc(0)).toString("utf8"),
stdoutBuffer: result.stdout ?? Buffer.alloc(0),
};
}
function assertClipboardUnsupported(errorOrResult) {
const message =
errorOrResult instanceof Error
? errorOrResult.message
: `${errorOrResult.stdout}\n${errorOrResult.stderr}`;
assert.match(
message,
/clipboard shell service is not implemented|No shell command implementation/i,
);
}
function isAndroidIntentUnavailable(error) {
const message = error instanceof Error ? error.message : String(error);
return /unable to resolve Intent|No Activity found|Activity class .* does not exist/i.test(
message,
);
}
function assertAndroidListed(payload, udid) {
assert.ok(
simulatorList(payload).some(
(simulator) => simulator.udid === udid || simulator.id === udid,
),
`${udid} was not present in simulator list`,
);
}
function assertJson(payload, label) {
assert.ok(payload && typeof payload === "object", `${label} was not JSON`);
}
function assertRoots(payload, label) {
assertJson(payload, label);
assert.ok(Array.isArray(payload.roots), `${label} missing roots array`);
assert.ok(payload.roots.length > 0, `${label} returned no roots`);
}
function centerOfFirstRoot(payload) {
const frame = payload?.roots?.[0]?.frame;
if (!frame || typeof frame !== "object") {
return null;
}
const x = Number(
Array.isArray(frame) ? frame[0] : (frame.x ?? frame.minX ?? 0),
);
const y = Number(
Array.isArray(frame) ? frame[1] : (frame.y ?? frame.minY ?? 0),
);
const width = Number(Array.isArray(frame) ? frame[2] : (frame.width ?? 0));
const height = Number(Array.isArray(frame) ? frame[3] : (frame.height ?? 0));
if (
!Number.isFinite(width) ||
!Number.isFinite(height) ||
width <= 0 ||
height <= 0
) {
return null;
}
return {
x: Math.round(x + width / 2),
y: Math.round(y + height / 2),
};
}
function assertPngBuffer(buffer) {
const signature = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
]);
assert.ok(
buffer.length > signature.length &&
buffer.subarray(0, signature.length).equals(signature),
"screenshot did not return a PNG buffer",
);
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}