Repository navigation
Expand file tree
/
Copy pathdevice.ts
More file actions
1000 lines (899 loc) · 40.4 KB
/
Copy pathdevice.ts
File metadata and controls
1000 lines (899 loc) · 40.4 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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from 'node:crypto';
import { AppError } from './errors.ts';
import type { DeviceIdentity } from './device-identity.ts';
import type { EnvMap } from './source-value.ts';
export {
deviceIdentity,
deviceIdentityKey,
deviceShape,
sameDeviceIdentity,
sameDeviceShape,
type DeviceIdentity,
} from './device-identity.ts';
// Legacy Apple leaf platforms. Retained ONLY as accepted `--platform` / read-path
// input aliases (approach b back-compat) and as the PUBLIC leaf strings the daemon
// still emits; the internal `Platform` no longer carries them — every Apple OS
// collapses to the single `apple` platform (ADR-0009 / issue #979).
export type ApplePlatform = 'ios' | 'macos';
// Explicit, stored Apple operating system. All six literals are reserved so the
// type is stable as platform support grows, but discovery only ever populates
// the four currently supported ones ('ios' | 'ipados' | 'tvos' | 'macos').
const APPLE_OS_VALUES = ['ios', 'ipados', 'tvos', 'watchos', 'visionos', 'macos'] as const;
export type AppleOS = (typeof APPLE_OS_VALUES)[number];
// Internal device platforms. Apple OSes collapse to a single `apple` platform; the
// `appleOs` field on DeviceInfo is the sole OS discriminant.
export const PLATFORMS = ['apple', 'android', 'harmonyos', 'vega', 'linux', 'web'] as const;
export type Platform = (typeof PLATFORMS)[number];
// The PUBLIC leaf platform strings the daemon emits and clients parse (approach b:
// output never changes). Equals the pre-collapse `Platform` set.
export const PUBLIC_PLATFORMS = [
'ios',
'macos',
'android',
'harmonyos',
'vega',
'linux',
'web',
] as const;
export type PublicPlatform = (typeof PUBLIC_PLATFORMS)[number];
// Accepted `--platform` selectors: the internal platforms plus the legacy Apple leaf
// aliases `ios`/`macos`, which still resolve to `apple` devices (read-path back-compat).
export const PLATFORM_SELECTORS = [...PLATFORMS, 'ios', 'macos'] as const;
export type PlatformSelector = (typeof PLATFORM_SELECTORS)[number];
export const DEVICE_KINDS = ['simulator', 'emulator', 'device'] as const;
export type DeviceKind = (typeof DEVICE_KINDS)[number];
export const DEVICE_TARGETS = ['mobile', 'tv', 'desktop'] as const;
export type DeviceTarget = (typeof DEVICE_TARGETS)[number];
export type DeviceInfo = {
platform: Platform;
id: string;
name: string;
kind: DeviceKind;
target?: DeviceTarget;
// Explicit Apple OS discriminant populated at discovery for Apple devices.
// Optional so legacy records (and non-Apple platforms) remain valid.
appleOs?: AppleOS;
// Presentation-only hardware model and OS version reported by discovery when the
// platform tooling exposes them; never part of device identity or selection.
model?: string;
osVersion?: string;
booted?: boolean;
simulatorSetPath?: string;
// Internal physical-iOS execution backend selected during discovery.
// Public device projections strip this field.
iosPhysicalDeviceBackend?: 'coredevice' | 'xctest';
/**
* Set when this device is one app of a host device rather than the host itself (ADR 0035). Its
* id is {@link hostAppDeviceId} of the two, so every per-device lock, claim, and session check
* treats the app as a device of its own; only {@link devicesOverlap} relates it to its host.
*/
hostApp?: { hostDeviceId: string; bundleId: string };
};
const HOST_APP_DEVICE_ID_INFIX = ':app:';
const WEB_SESSION_DEVICE_ID_INFIX = ':session:';
const HOST_SCOPED_DEVICE_ID_INFIXES = [HOST_APP_DEVICE_ID_INFIX, WEB_SESSION_DEVICE_ID_INFIX];
const MACOS_BUNDLE_ID_PATTERN = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;
/** A macOS bundle id in reverse-DNS form such as com.apple.TextEdit; any segment may be mixed-case. */
export function isMacOsBundleId(value: string): boolean {
return MACOS_BUNDLE_ID_PATTERN.test(value);
}
/** Bundle ids match without regard to case, as LaunchServices matches them. */
export function hostAppDeviceId(hostDeviceId: string, bundleId: string): string {
return `${hostDeviceIdPrefix(hostDeviceId)}${bundleId.toLowerCase()}`;
}
/** The host of an app or web session device id, or the id itself for any other device. */
export function hostDeviceIdOf(deviceId: string): string {
const infixes = HOST_SCOPED_DEVICE_ID_INFIXES.map((infix) => deviceId.indexOf(infix)).filter(
(index) => index >= 0,
);
return infixes.length === 0 ? deviceId : deviceId.slice(0, Math.min(...infixes));
}
/** A device id as devices carry it: the bundle part of an app device id is lowercase. */
export function canonicalDeviceId(deviceId: string): string {
const hostDeviceId = hostDeviceIdOf(deviceId);
const prefix = hostDeviceIdPrefix(hostDeviceId);
return deviceId.startsWith(prefix)
? hostAppDeviceId(hostDeviceId, deviceId.slice(prefix.length))
: deviceId;
}
/** The id prefix every app device of `hostDeviceId` shares. */
export function hostDeviceIdPrefix(hostDeviceId: string): string {
return `${hostDeviceId}${HOST_APP_DEVICE_ID_INFIX}`;
}
/** One app of `host`, held as a device of its own. */
export function hostAppDevice(host: DeviceInfo, bundleId: string): DeviceInfo {
return {
...host,
id: hostAppDeviceId(host.id, bundleId),
hostApp: { hostDeviceId: host.id, bundleId },
};
}
const WEB_BACKEND_KEY_PREFIX = 'p_';
const WEB_TENANT_KEY_HASH_LENGTH = 12;
const WEB_SESSION_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
// agent-browser binds its control socket at `<tmpdir>/adw/<12 hex>/<key>.sock` and refuses a path
// over 103 bytes. The macOS per-user tmpdir is 48 bytes, the longest of the supported hosts.
const SOCKET_PATH_MAX_BYTES = 103;
const SOCKET_DIR_BYTES = 48 + '/adw/'.length + 12;
const SOCKET_FILE_OVERHEAD_BYTES = '/'.length + '.sock'.length;
/** The most characters a web backend session key can hold. */
const WEB_BACKEND_KEY_MAX_LENGTH =
SOCKET_PATH_MAX_BYTES - SOCKET_DIR_BYTES - SOCKET_FILE_OVERHEAD_BYTES;
/**
* A web session as the caller names it. `name` is the tenant-relative public name, never the
* tenant-prefixed key the session store holds it under; `tenantId` is set under tenant isolation.
*/
export type WebSessionIdentity = Readonly<{ name: string; tenantId?: string }>;
function webBackendKeyPrefix(tenantId: string | undefined): string {
if (tenantId === undefined) return WEB_BACKEND_KEY_PREFIX;
const hash = crypto.createHash('sha256').update(tenantId).digest('hex');
return `t_${hash.slice(0, WEB_TENANT_KEY_HASH_LENGTH)}_`;
}
/**
* The name of a web session in lower case, so names that differ only by case are one session on a
* case-insensitive filesystem. It is refused with `web_session_name_invalid`, never trimmed, unless
* it is non-empty, holds only letters, digits, `_` and `-` (the characters the backend accepts in
* a session name, so surrounding whitespace is refused and the stored session address equals the
* validated name), and leaves room for `keyPrefixLength` characters of the backend key within the
* socket path limit. That also keeps `:` out of the name, which would parse as the `:session:` or
* `:app:` infix of another device id.
*/
function requireWebSessionName(sessionName: string, keyPrefixLength: number): string {
const name = sessionName.toLowerCase();
const maxLength = WEB_BACKEND_KEY_MAX_LENGTH - keyPrefixLength;
if (!WEB_SESSION_NAME_PATTERN.test(sessionName) || name.length > maxLength) {
throw new AppError(
'INVALID_ARGS',
`A web session name must be 1 to ${maxLength} characters of letters, digits, "_" and "-".`,
{
reason: 'web_session_name_invalid',
sessionName,
maxLength,
hint: 'Pass --session with a name such as "checkout-1".',
},
);
}
return name;
}
/**
* The key agent-browser isolates a browser on, derived once from the session: `p_<name>`, or
* `t_<hash12 of the tenant>_<name>` under tenant isolation so two tenants never share a browser.
*/
export function webSessionBackendKey(session: WebSessionIdentity): string {
const prefix = webBackendKeyPrefix(session.tenantId);
return `${prefix}${requireWebSessionName(session.name, prefix.length)}`;
}
/**
* One web session of `host`, held as a device of its own. Its id carries the backend key, so two
* names that drive one browser are one device and every reader takes the same key from it.
*/
export function webSessionDevice(host: DeviceInfo, session: WebSessionIdentity): DeviceInfo {
const id = `${host.id}${WEB_SESSION_DEVICE_ID_INFIX}${webSessionBackendKey(session)}`;
return { ...host, id };
}
/** The backend key a web session device id carries, or `undefined` for any other device id. */
export function webBackendKeyOf(deviceId: string): string | undefined {
const rest = deviceId.slice(hostDeviceIdOf(deviceId).length);
return rest.startsWith(WEB_SESSION_DEVICE_ID_INFIX)
? rest.slice(WEB_SESSION_DEVICE_ID_INFIX.length)
: undefined;
}
/** The host of an app device, then the device itself; any other device alone. */
export function hostAndDeviceIds(device: DeviceInfo): string[] {
return device.hostApp ? [device.hostApp.hostDeviceId, device.id] : [device.id];
}
/** The macOS host holds apps, and the web host holds web sessions, as devices of their own. */
export function canHostScopedDevices(device: Pick<DeviceInfo, 'platform' | 'appleOs'>): boolean {
return isMacOs(device) || device.platform === 'web';
}
/** Whether `deviceId` is an app device or a web session device of `hostDeviceId`. */
export function isHostScopedDeviceOf(hostDeviceId: string, deviceId: string): boolean {
return HOST_SCOPED_DEVICE_ID_INFIXES.some((infix) =>
deviceId.startsWith(`${hostDeviceId}${infix}`),
);
}
/**
* Whether two devices cannot be held by two sessions at once: the same device, or a host and one
* of its app or web session devices. Two such devices of one host do not overlap.
*/
export function devicesOverlap(leftId: string, rightId: string): boolean {
return (
leftId === rightId ||
isHostScopedDeviceOf(rightId, leftId) ||
isHostScopedDeviceOf(leftId, rightId)
);
}
export type DeviceSelector = {
platform?: PlatformSelector;
target?: DeviceTarget;
deviceName?: string;
udid?: string;
serial?: string;
};
/** Device identity is narrower than platform/target filtering for precedence decisions. */
export function hasExplicitDeviceIdentitySelector(
selector: Pick<DeviceSelector, 'deviceName' | 'udid' | 'serial'>,
): boolean {
return [selector.deviceName, selector.udid, selector.serial].some(
(value) => typeof value === 'string' && value.trim().length > 0,
);
}
type DeviceSelectionContext = {
simulatorSetPath?: string;
};
export function isApplePlatform(
platform: Platform | PlatformSelector | undefined,
): platform is ApplePlatform | 'apple' {
return platform === 'apple' || platform === 'ios' || platform === 'macos';
}
/**
* The macOS Apple-OS leaf: the AppKit desktop host. The post-collapse replacement for
* the former `platform === 'macos'` leaf compare — discovery always stamps
* `appleOs: 'macos'` on the host device (buildHostMacDevice), so the OS discriminant
* is authoritative.
*/
export function isMacOs(device: Pick<DeviceInfo, 'platform' | 'appleOs'>): boolean {
// The `appleOs` discriminant is authoritative for discovered devices; the legacy
// leaf `platform: 'macos'` (persisted pre-collapse records, or synthetic
// leaf-string devices) is still honored via the cast for back-compat.
return device.appleOs === 'macos' || (device.platform as string) === 'macos';
}
/**
* The touch iOS family: every Apple OS except the macOS desktop host
* (iOS / iPadOS / tvOS / visionOS). This is the EXACT post-collapse equivalent of the
* pre-collapse `platform === 'ios'` leaf compare — that leaf covered all four of these
* OSes — so `isIosFamily(device)` swaps in for `device.platform === 'ios'`
* behavior-for-behavior (false for macOS and every non-Apple platform).
*/
export function isIosFamily(device: Pick<DeviceInfo, 'platform' | 'appleOs'>): boolean {
return isApplePlatform(device.platform) && !isMacOs(device);
}
/**
* The iPhone/iPad simulator leaf: a simulator of an Apple handheld OS. `simctl` surfaces that a
* phone or tablet simulator exposes and a television or headset one does not — content size is one
* — are confined to this leaf, which is strictly narrower than {@link isIosFamily} (that also covers
* tvOS and visionOS simulators) and excludes both the macOS host and every physical device.
*/
export function isHandheldAppleSimulator(
device: Pick<DeviceInfo, 'platform' | 'target' | 'appleOs' | 'kind'>,
): boolean {
if (device.kind !== 'simulator') return false;
const appleOs = resolveDeviceAppleOs(device);
return appleOs === 'ios' || appleOs === 'ipados';
}
/**
* The iPhone/iPad leaf on a simulator or hardware, including legacy records that predate the
* stored `appleOs` discriminant. Excludes tvOS, visionOS, the macOS host, and non-Apple platforms.
*/
export function isHandheldAppleDevice(
device: Pick<DeviceInfo, 'platform' | 'target' | 'appleOs'>,
): boolean {
if (!isIosFamily(device)) return false;
const appleOs = resolveDeviceAppleOs(device);
return appleOs === 'ios' || appleOs === 'ipados';
}
export function isMobilePlatform(device: Pick<DeviceInfo, 'platform' | 'appleOs'>): boolean {
// Phone/tablet device family: Android plus every Apple OS except the macOS desktop
// host. Preserves the pre-collapse `platform === 'ios' || platform === 'android'`
// set exactly (the old `ios` platform covered iOS/iPadOS/tvOS/visionOS).
return (
device.platform === 'android' ||
device.platform === 'harmonyos' ||
(isApplePlatform(device.platform) && !isMacOs(device))
);
}
/**
* The PUBLIC leaf platform string emitted to machine consumers (approach b: output
* keeps emitting `ios`/`macos`, never the internal `apple`). Apple devices project to
* their leaf via `appleOs`; non-Apple platforms pass through unchanged.
*/
export function publicPlatformString(
device: Pick<DeviceInfo, 'platform' | 'appleOs'>,
): PublicPlatform {
if (!isApplePlatform(device.platform)) return device.platform;
return isMacOs(device) ? 'macos' : 'ios';
}
/**
* The inverse of {@link publicPlatformString}: reconstruct the internal `platform` (+
* `appleOs` where the leaf is unambiguous) from a PUBLIC leaf string. Used where the
* client rebuilds an internal DeviceInfo from a parsed daemon response. The `ios` leaf
* leaves `appleOs` unset so the target-based inference still distinguishes tvOS.
*/
export function deviceFieldsFromPublicPlatform(platform: PublicPlatform): {
platform: Platform;
appleOs?: AppleOS;
} {
if (platform === 'macos') return { platform: 'apple', appleOs: 'macos' };
if (platform === 'ios') return { platform: 'apple' };
return { platform };
}
/**
* The tvOS Apple-OS leaf predicate. tvOS is modeled as the `ios` platform with a
* `tv` form-factor target (ADR-0009 defers the `Platform` collapse; discovery also
* stores `appleOs: 'tvos'`). Naming the leaf keeps its focus-only interaction
* contract — XCUIRemote focus navigation, and NO coordinate tap/gesture — gated by
* one explicit predicate instead of a `target === 'tv'` string compare smeared
* across the Apple interaction paths.
*
* Apple-only by design: Android TV also uses `target: 'tv'` but is a DISTINCT leaf,
* so the `isApplePlatform` gate is load-bearing (do not widen it to any TV target).
*/
export function isTvOsDevice(device: Pick<DeviceInfo, 'platform' | 'target'>): boolean {
return isApplePlatform(device.platform) && device.target === 'tv';
}
/**
* The Apple leaves whose runner synthesizes tap input (`RunnerTests+SynthesizedInteraction.swift`
* gates two-finger HID synthesis behind `#if os(iOS)`, which covers iOS and iPadOS only): every
* `isIosFamily` leaf except tvOS (no touchscreen) and visionOS (the runner's `#else` branch, no
* synthesis path). Every producer of `synthesized: true` gates on this predicate so none of them
* pays for a synthesis attempt the runner cannot perform.
*/
export function runnerSynthesizesTap(
device: Pick<DeviceInfo, 'platform' | 'appleOs' | 'target'>,
): boolean {
return isIosFamily(device) && !isTvOsDevice(device) && device.appleOs !== 'visionos';
}
/** Resolve the stored Apple OS, preserving legacy target/leaf inference for old device records. */
export function resolveDeviceAppleOs(
device: Pick<DeviceInfo, 'platform' | 'target' | 'appleOs'>,
): AppleOS {
if (device.appleOs) return device.appleOs;
if ((device.platform as string) === 'macos') return 'macos';
if (isTvOsDevice(device)) return 'tvos';
return 'ios';
}
/**
* @internal Type guard exposed for unit tests.
*/
export function isPlatform(value: unknown): value is Platform {
// Internal device-platform membership derived from the canonical PLATFORMS tuple.
return (PLATFORMS as readonly unknown[]).includes(value);
}
export function isPublicPlatform(value: unknown): value is PublicPlatform {
// The PUBLIC leaf strings a daemon response carries (approach b). Used by the client
// normalizers, which parse leaf platforms (`ios`/`macos`), not the internal `apple`.
return (PUBLIC_PLATFORMS as readonly unknown[]).includes(value);
}
export function isDeviceTarget(value: unknown): value is DeviceTarget {
return (DEVICE_TARGETS as readonly unknown[]).includes(value);
}
export function isAppleOs(value: unknown): value is AppleOS {
// The stored Apple-OS discriminant carried additively on the PUBLIC device output
// (iPhone/iPad/tvOS/visionOS/macOS). Used by the client normalizers to validate the
// optional `appleOs` field parsed from a daemon response. Its values never include the
// internal `apple` platform token, so surfacing it does not affect the apple-leak guard.
return (APPLE_OS_VALUES as readonly unknown[]).includes(value);
}
export function decodeDeviceIdentity(value: unknown): DeviceIdentity | null {
if (!isObject(value)) return null;
const id = readDeviceIdentityId(value.id);
const family = readDeviceIdentityFamily(value.family);
const kind = readDeviceIdentityKind(value.kind);
const target = readDeviceIdentityTarget(value.target);
if (!id || !family || !kind || target === null) return null;
if (!hasCoherentAppleIdentity(value, family, kind)) return null;
return buildDeviceIdentity(value, id, family, kind, target);
}
function buildDeviceIdentity(
value: Record<string, unknown> & {
appleOs?: AppleOS;
iosPhysicalDeviceBackend?: DeviceInfo['iosPhysicalDeviceBackend'];
},
id: string,
family: Platform,
kind: DeviceKind,
target: DeviceTarget | undefined,
): DeviceIdentity {
return Object.freeze({
id,
family,
...(value.appleOs === undefined ? {} : { appleOs: value.appleOs }),
kind,
...(target === undefined ? {} : { target }),
...(value.iosPhysicalDeviceBackend === undefined
? {}
: { iosPhysicalDeviceBackend: value.iosPhysicalDeviceBackend }),
});
}
function readDeviceIdentityId(value: unknown): string | null {
return isNonEmptyString(value) ? value : null;
}
function readDeviceIdentityFamily(value: unknown): Platform | null {
return isPlatform(value) ? value : null;
}
function readDeviceIdentityKind(value: unknown): DeviceKind | null {
return isDeviceKind(value) ? value : null;
}
function readDeviceIdentityTarget(value: unknown): DeviceTarget | undefined | null {
if (value === undefined) return undefined;
return isDeviceTarget(value) ? value : null;
}
function hasCoherentAppleIdentity(
value: Record<string, unknown>,
family: Platform,
kind: DeviceKind,
): value is Record<string, unknown> & {
appleOs?: AppleOS;
iosPhysicalDeviceBackend?: DeviceInfo['iosPhysicalDeviceBackend'];
} {
if (family === 'apple') {
if (!isAppleOs(value.appleOs)) return false;
} else if (value.appleOs !== undefined || value.iosPhysicalDeviceBackend !== undefined) {
return false;
}
return hasValidPhysicalAppleBackend(value.iosPhysicalDeviceBackend, kind);
}
function hasValidPhysicalAppleBackend(value: unknown, kind: DeviceKind): boolean {
if (value === undefined) return true;
if (kind !== 'device') return false;
return value === 'coredevice' || value === 'xctest';
}
function isDeviceKind(value: unknown): value is DeviceKind {
return (DEVICE_KINDS as readonly unknown[]).includes(value);
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function matchesPlatformSelector(
device: Pick<DeviceInfo, 'platform' | 'appleOs'>,
selector: PlatformSelector | undefined,
): boolean {
if (!selector) return true;
if (selector === 'apple') return isApplePlatform(device.platform);
// Legacy leaf selectors resolve within the collapsed `apple` platform via `appleOs`,
// preserving the pre-collapse `--platform ios|macos` device sets exactly.
if (selector === 'ios') return isApplePlatform(device.platform) && !isMacOs(device);
if (selector === 'macos') return isApplePlatform(device.platform) && isMacOs(device);
return device.platform === selector;
}
/**
* Whether two `--platform` selections can name the SAME device.
*
* Selectors name a platform on one of two axes: the collapsed `apple` family, or an Apple leaf
* (`ios`/`macos`) — plus the non-Apple platforms, which have one axis each. Equality of the two
* strings is therefore not the question: `apple` and `ios` name overlapping devices while `ios` and
* `macos` do not. The `apple` selector is only equivalent to a leaf, never to a non-Apple platform.
*
* Comparing selectors by string instead was the shape behind #2962, where a remote connection bound
* to the public `ios` was compared with an `apple`-axis value and every iOS install was refused.
* Any caller that decides "this request targets a different platform than the one already bound"
* has to answer it on both axes, which is why this lives beside the selectors rather than in one
* caller.
*/
export function platformSelectorsConflict(
requested: PlatformSelector | undefined,
bound: PlatformSelector | undefined,
): boolean {
if (!requested || !bound) return false;
if (requested === bound) return false;
if (requested === 'apple') return !isApplePlatform(bound);
if (bound === 'apple') return !isApplePlatform(requested);
return true;
}
export function resolveApplePlatformName(
platformOrTarget: ApplePlatform | DeviceTarget | undefined,
appleOs?: AppleOS,
): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' {
// Prefer the explicit, stored Apple OS when present; legacy records without
// it keep resolving through the existing target-based inference below.
if (appleOs) return resolveRunnerPlatformNameForAppleOs(appleOs);
if (platformOrTarget === 'macos' || platformOrTarget === 'desktop') return 'macOS';
if (platformOrTarget === 'tv') return 'tvOS';
return 'iOS';
}
function resolveRunnerPlatformNameForAppleOs(
appleOs: AppleOS,
): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' {
switch (appleOs) {
case 'tvos':
return 'tvOS';
case 'macos':
return 'macOS';
case 'visionos':
return 'visionOS';
// iOS and iPadOS share the single iOS runner profile/SDK. watchOS remains
// reserved in the type but is never produced by discovery; defaulting it to
// iOS keeps any future record on a valid runner profile without introducing
// watchOS support.
default:
return 'iOS';
}
}
const DAEMON_IOS_SIMULATOR_DEVICE_SET_ENV = 'AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET';
/**
* The simulator set a daemon request's device inventory reaches. macOS and desktop selectors
* never reach a simulator set. For selectors that can reach simulators,
* `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` in the daemon's environment is the operator's set: it
* applies when the request names no set, and a request naming another set is refused.
*/
export function resolveRequestAppleSimulatorSetPath(params: {
requestedSetPath?: string;
platform?: PlatformSelector;
target?: DeviceTarget;
env: EnvMap;
}): string | undefined {
const { platform, target, env } = params;
if (platform === 'macos' || target === 'desktop') return undefined;
const requested = params.requestedSetPath?.trim() || undefined;
if (!supportsAppleSimulatorSelection(platform)) return requested;
const operatorSet = env[DAEMON_IOS_SIMULATOR_DEVICE_SET_ENV]?.trim() || undefined;
if (!operatorSet) return requested;
if (requested && requested !== operatorSet) {
throw new AppError(
'INVALID_ARGS',
`This daemon only reaches iOS simulators in the set "${operatorSet}" (${DAEMON_IOS_SIMULATOR_DEVICE_SET_ENV}), but the request named --ios-simulator-device-set "${requested}".`,
{
reason: 'ios_simulator_device_set_outside_daemon_set',
hint: `Omit --ios-simulator-device-set, or pass exactly "${operatorSet}".`,
},
);
}
return operatorSet;
}
export function sortAppleDevicesForSelection<TDevice extends DeviceInfo>(
devices: TDevice[],
): TDevice[] {
return devices
.map((device, index) => ({ device, index }))
.sort((left, right) => compareAppleDevicesForSelection(left, right))
.map(({ device }) => device);
}
function supportsAppleSimulatorSelection(platform: PlatformSelector | undefined): boolean {
return !platform || platform === 'apple' || platform === 'ios';
}
export async function resolveDevice(
devices: DeviceInfo[],
selector: DeviceSelector,
context: DeviceSelectionContext = {},
): Promise<DeviceInfo> {
let candidates = devices.filter((device) => matchesDeviceSelector(device, selector));
const explicitlySelected = resolveExplicitDevice(candidates, selector);
if (explicitlySelected) return explicitlySelected;
const namedDevice = resolveDeviceByName(candidates, selector.deviceName);
if (namedDevice) return namedDevice;
if (isAppleDeviceCandidateSet(candidates)) {
candidates = sortAppleDevicesForSelection(candidates);
}
return selectDefaultDevice(candidates, selector, context);
}
function resolveExplicitDevice(
candidates: DeviceInfo[],
selector: DeviceSelector,
): DeviceInfo | undefined {
assertSelectorFlagMatchesPlatform(selector);
if (selector.udid) return resolveAppleDeviceByUdid(candidates, selector.udid);
if (selector.serial) return resolveDeviceBySerial(candidates, selector);
return undefined;
}
/**
* `--udid` addresses Apple devices and `--serial` addresses serial-addressable ones (Android,
* HarmonyOS). Passing the wrong pair used to reach resolution and fail as "No Apple device with
* UDID emulator-5580" on an explicitly `--platform android` request — an answer about the wrong
* platform, which reads as a missing device rather than a mistyped flag.
*/
function assertSelectorFlagMatchesPlatform(selector: DeviceSelector): void {
const platform = selector.platform;
if (!platform) return;
if (selector.udid && isSerialAddressablePlatform(platform)) {
throw new AppError(
'INVALID_ARGS',
`--udid selects Apple devices, but this request selected --platform ${platform}.`,
{ hint: `Use --serial ${selector.udid} for ${platform} devices.` },
);
}
if (selector.serial && isApplePlatform(platform)) {
throw new AppError(
'INVALID_ARGS',
`--serial selects Android and HarmonyOS devices, but this request selected --platform ${platform}.`,
{ hint: `Use --udid ${selector.serial} for Apple devices.` },
);
}
}
function resolveAppleDeviceByUdid(candidates: DeviceInfo[], udid: string): DeviceInfo {
const match = candidates.find((device) => device.id === udid && isApplePlatform(device.platform));
if (!match) {
throw new AppError('DEVICE_NOT_FOUND', `No Apple device with UDID ${udid}`, {
dispatched: 'no',
});
}
return match;
}
function resolveDeviceBySerial(candidates: DeviceInfo[], selector: DeviceSelector): DeviceInfo {
const match = candidates.find(
(device) => device.id === selector.serial && isSerialAddressablePlatform(device.platform),
);
if (!match) {
throw new AppError('DEVICE_NOT_FOUND', serialDeviceNotFoundMessage(selector), {
dispatched: 'no',
});
}
return match;
}
function resolveDeviceByName(
candidates: DeviceInfo[],
deviceName: string | undefined,
): DeviceInfo | undefined {
if (!deviceName) return undefined;
const match = candidates.find((device) => matchesDeviceNameSelector(device, deviceName));
if (!match) {
const hint = deviceIdentityMistakenForNameHint(candidates, deviceName);
throw new AppError(
'DEVICE_NOT_FOUND',
`No device named ${deviceName}`,
hint === undefined ? { dispatched: 'no' } : { hint, dispatched: 'no' },
);
}
return match;
}
/**
* `--device` takes a device NAME, and `--udid`/`--serial` take a device IDENTITY. Passing an
* identity to `--device` reached name resolution and answered "No device named
* 204BFFD9-9644-4830-B2C1-1B946597A07C" (#2064) — literally true, and unactionable: it names
* neither the flag that does take that value nor the fact that one exists. It is the same class of
* mistake `assertSelectorFlagMatchesPlatform` already answers for a mismatched identity flag, so
* answer it the same way: name the flag the value belongs to. Only an observed identity earns the
* hint — the candidates' own ids, with the flag derived from that device's platform; guessing from
* the value's shape would have to reimplement every platform's identity syntax here. A platform
* with no identity flag at all (web, linux) earns no hint either: `--udid` resolves only Apple
* devices, so naming it would send the user to a flag that provably cannot work.
*/
function deviceIdentityMistakenForNameHint(
candidates: DeviceInfo[],
deviceName: string,
): string | undefined {
const identityMatch = candidates.find((device) => device.id === deviceName);
if (!identityMatch) return undefined;
const flag = deviceIdentityFlag(identityMatch.platform);
if (!flag) return undefined;
return (
`${deviceName} is the id of ${JSON.stringify(identityMatch.name)}, not its name. ` +
`Did you mean --${flag} ${deviceName}?`
);
}
export type DeviceIdentityFlag = 'udid' | 'serial';
/**
* Which flag carries a device identity on a platform: `udid` addresses Apple devices, `serial`
* addresses the serial-addressable ones. Resolution rejects the wrong pairing
* (`assertSelectorFlagMatchesPlatform`), and a caller that resolved a device and has to re-issue it
* as flags — a remote lease request that must bind the device it just picked — has to name the same
* flag, or the two drift and the request binds a selector that resolves a DIFFERENT device.
*
* Two sites still spell the pairing out inline; each differs from this rule in a way that is its own
* decision, so they are tracked as follow-ups rather than folded in here.
*/
export function deviceIdentityFlag(
platform: Platform | PublicPlatform,
): DeviceIdentityFlag | undefined {
if (isApplePlatform(platform)) return 'udid';
if (isSerialAddressablePlatform(platform)) return 'serial';
return undefined;
}
/**
* SINGULAR RESOLUTION. Every caller of `resolveDevice` needs exactly one concrete device, so when
* the request carries no device identity and more than one candidate survives the preference tiers,
* this refuses with the candidates rather than picking one. A quietly chosen device produces a
* successful response describing the WRONG device — indistinguishable from the right one — and
* reads are no safer than writes: three successful snapshots of the wrong emulator are still three
* wrong answers. Multi-device operations (`devices`) never enter this path. The one opt-in
* exception is `boot --pick`, which never reaches here; see `pickNewestBootableDevice`.
*/
function selectDefaultDevice(
candidates: DeviceInfo[],
selector: DeviceSelector,
context: DeviceSelectionContext,
): DeviceInfo {
const onlyCandidate = candidates[0];
if (onlyCandidate !== undefined && candidates.length === 1) return onlyCandidate;
if (candidates.length === 0) {
throwNoDevicesFound(selector, context);
}
const preferred = preferredDeviceCandidates(candidates);
if (preferred.length > 1) throwAmbiguousDeviceSelection(preferred);
const selected = preferred[0];
if (!selected) throwNoDevicesFound(selector, context);
return selected;
}
const AMBIGUOUS_DEVICE_CANDIDATE_LIMIT = 10;
function throwAmbiguousDeviceSelection(candidates: DeviceInfo[]): never {
const listed = candidates.slice(0, AMBIGUOUS_DEVICE_CANDIDATE_LIMIT);
throw new AppError(
'AMBIGUOUS_MATCH',
`${candidates.length} devices match this request equally; select one explicitly.`,
{
// The declared device-candidate details domain (@agent-device/kernel/errors), so the CLI
// and MCP renderers print these candidates without a new shape to learn.
devices: listed.map((device) => ({ id: device.id, name: device.name })),
matches: candidates.length,
hint: buildAmbiguousDeviceHint(listed),
},
);
}
function buildAmbiguousDeviceHint(candidates: DeviceInfo[]): string {
const first = candidates[0];
const identitySelector = first
? `--${deviceIdentityFlag(first.platform) ?? 'udid'} ${first.id}`
: `--udid <id>`;
return (
`Select the intended device explicitly, for example ${identitySelector} ` +
`or --device ${JSON.stringify(first?.name ?? '<name>')}. ` +
`Run agent-device devices to list them.`
);
}
/**
* The candidates left after every ESTABLISHED preference — virtual over physical (Apple ranks its
* kinds/targets instead), then booted over offline. Whatever survives is equally preferred: the
* comparator's remaining tie-breaks are name order and discovery order, which encode nothing about
* intent.
*/
function preferredDeviceCandidates(candidates: DeviceInfo[]): DeviceInfo[] {
const ranked = isAppleDeviceCandidateSet(candidates)
? candidatesWithBestAppleRank(candidates)
: preferVirtualCandidates(candidates);
const booted = ranked.filter((device) => device.booted);
return booted.length > 0 ? booted : ranked;
}
function preferVirtualCandidates(candidates: DeviceInfo[]): DeviceInfo[] {
const virtual = candidates.filter((device) => device.kind !== 'device');
return virtual.length > 0 ? virtual : candidates;
}
function candidatesWithBestAppleRank(candidates: DeviceInfo[]): DeviceInfo[] {
const bestRank = Math.min(...candidates.map((device) => appleDeviceSelectionRank(device)));
return candidates.filter((device) => appleDeviceSelectionRank(device) === bestRank);
}
/** Tie-break policies `boot --pick` accepts. */
export const BOOT_PICK_POLICIES = ['newest'] as const;
export type BootPickPolicy = (typeof BOOT_PICK_POLICIES)[number];
/**
* COLD PICK, the one opt-in exception to SINGULAR RESOLUTION, for `boot --pick newest` only. It
* decides only when several candidates survive the preference tiers and NONE of them is booted:
* the opt-in says any of them is acceptable, nothing runs on them yet to be misread, and once the
* pick boots, booted-over-offline resolves every later unscoped request to it. A booted tie stays
* ambiguous, because the next command would still have to choose. Order: mobile target, newest
* OS version, name, id.
*/
export function pickNewestBootableDevice(candidates: DeviceInfo[]): DeviceInfo | undefined {
const preferred = preferredDeviceCandidates(candidates);
if (preferred.length < 2 || preferred.some((device) => device.booted)) return undefined;
// Built per pick, not at module load: the first collator costs every CLI start its ICU setup.
const collator = new Intl.Collator('en', { numeric: true });
return [...preferred].sort((left, right) => compareNewestBootable(collator, left, right))[0];
}
function compareNewestBootable(
collator: Intl.Collator,
left: DeviceInfo,
right: DeviceInfo,
): number {
return (
Number(isMobileTarget(right)) - Number(isMobileTarget(left)) ||
compareOsVersionsNewestFirst(collator, left.osVersion, right.osVersion) ||
collator.compare(left.name, right.name) ||
collator.compare(left.id, right.id)
);
}
function isMobileTarget(device: DeviceInfo): boolean {
return (device.target ?? 'mobile') === 'mobile';
}
function compareOsVersionsNewestFirst(
collator: Intl.Collator,
left: string | undefined,
right: string | undefined,
): number {
if (left === right) return 0;
if (left === undefined) return 1;
if (right === undefined) return -1;
return collator.compare(right, left);
}
export function matchesDeviceSelector(
device: DeviceInfo,
selector: DeviceSelector,
options: { includeExplicitSelectors?: boolean } = {},
): boolean {
return (
matchesPlatformSelector(device, selector.platform) &&
(!selector.target || (device.target ?? 'mobile') === selector.target) &&
(!options.includeExplicitSelectors || matchesExplicitDeviceSelector(device, selector))
);
}
function matchesExplicitDeviceSelector(device: DeviceInfo, selector: DeviceSelector): boolean {
if (selector.udid && !(device.id === selector.udid && isApplePlatform(device.platform))) {
return false;
}
if (
selector.serial &&
!(device.id === selector.serial && isSerialAddressablePlatform(device.platform))
) {
return false;
}
if (selector.deviceName && !matchesDeviceNameSelector(device, selector.deviceName)) {
return false;
}
return true;
}
export function isSerialAddressablePlatform(
platform: Platform | PublicPlatform,
): platform is 'android' | 'harmonyos' | 'vega' {
return platform === 'android' || platform === 'harmonyos' || platform === 'vega';
}
function serialDeviceNotFoundMessage(selector: DeviceSelector): string {
if (selector.platform === 'android') {
return `No Android device with serial ${selector.serial}`;
}
if (selector.platform === 'vega') {
return `No Vega VVD with serial ${selector.serial}`;
}
if (selector.platform === 'harmonyos') {
return `No HarmonyOS device with serial ${selector.serial}`;
}
return `No Android, HarmonyOS device, or Vega VVD with serial ${selector.serial}`;
}
function throwNoDevicesFound(selector: DeviceSelector, context: DeviceSelectionContext): never {
const simulatorSetPath = context.simulatorSetPath;
if (simulatorSetPath && supportsAppleSimulatorSelection(selector.platform)) {
throw new AppError('DEVICE_NOT_FOUND', 'No devices found in the scoped simulator set', {
simulatorSetPath,
hint: `The simulator set at "${simulatorSetPath}" appears to be empty. Create a compatible simulator first with xcrun simctl --set "${simulatorSetPath}" create, or remove the scoped simulator set.`,
selector,
dispatched: 'no',
});
}
throw new AppError('DEVICE_NOT_FOUND', 'No devices found', { selector, dispatched: 'no' });
}
/**
* Whether a `--device` name selects `device`. Selection and session-binding checks share this
* matcher so a name that picked a device keeps matching it, e.g. AVD `Pixel_9_API_37` for the
* displayed `Pixel 9 API 37`.
*/
export function matchesDeviceNameSelector(
device: Pick<DeviceInfo, 'name'>,
deviceName: string,
): boolean {
return normalizeDeviceName(device.name) === normalizeDeviceName(deviceName);
}
function normalizeDeviceName(value: string): string {
return value.toLowerCase().replaceAll('_', ' ').replaceAll(/\s+/g, ' ').trim();
}
function compareAppleDevicesForSelection<TDevice extends DeviceInfo>(
left: { device: TDevice; index: number },
right: { device: TDevice; index: number },
): number {
return (
appleDeviceSelectionRank(left.device) - appleDeviceSelectionRank(right.device) ||
Number(right.device.booted === true) - Number(left.device.booted === true) ||
left.device.name.localeCompare(right.device.name) ||
left.index - right.index
);
}
function appleDeviceSelectionRank(device: DeviceInfo): number {
if (device.kind === 'simulator') return appleTargetSelectionRank(device, 0, 1, 2, 3);
if (device.kind === 'device' && isApplePlatform(device.platform) && !isMacOs(device))
return appleTargetSelectionRank(device, 10, 11, 12, 13);
return 14;
}
function appleTargetSelectionRank(
device: DeviceInfo,
phoneRank: number,
ipadRank: number,
tvRank: number,
fallbackRank: number,
): number {
const targetRanks: Record<DeviceTarget, number> = {
mobile: isIpadDevice(device) ? ipadRank : phoneRank,
tv: tvRank,
desktop: fallbackRank,
};
return device.appleOs === 'visionos' ? fallbackRank : targetRanks[device.target ?? 'mobile'];
}
function isAppleDeviceCandidateSet(devices: DeviceInfo[]): boolean {
return devices.length > 0 && devices.every((device) => isApplePlatform(device.platform));
}
/**
* Discovery stamps `appleOs` from the device type, which survives a renamed simulator; the name
* is only a fallback for records that predate the discriminant.
*/
function isIpadDevice(device: Pick<DeviceInfo, 'name' | 'appleOs'>): boolean {
if (device.appleOs) return device.appleOs === 'ipados';
return /\bipad\b/i.test(device.name);
}