Repository navigation
Expand file tree
/
Copy pathrunner-contract.ts
More file actions
872 lines (808 loc) · 36.3 KB
/
Copy pathrunner-contract.ts
File metadata and controls
872 lines (808 loc) · 36.3 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
import {
AppError,
createRequestCanceledError,
discloseDispatch,
toAppErrorCode,
type AppErrorCode,
type DispatchDisclosure,
} from '@agent-device/kernel/errors';
import crypto from 'node:crypto';
import {
ALERT_BUTTON_NOT_FOUND_RUNNER_CODE,
ALERT_NOT_FOUND_RUNNER_CODE,
ALERT_UNRESOLVED_RUNNER_CODE,
} from '@agent-device/contracts/alert-contract';
import type { DeviceRotation } from '@agent-device/contracts/device';
import type { SnapshotPreferredBackend } from '@agent-device/kernel/snapshot';
import type { ClickButton } from '@agent-device/contracts/click-button';
import type {
CoordinateTapTextInputEvidence,
ElementSelectorKey,
} from '@agent-device/contracts/interactor-types';
import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types';
import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture';
import type { ScrollReleaseBehavior } from '@agent-device/contracts/scroll-command';
import { getRequestSignal, isRequestCanceled } from './host.ts';
/**
* The runner's own code for "an earlier command exceeded the execution watchdog and its abandoned
* main-thread work is still draining" (#1105). It is transient by construction — past the wedge
* threshold the runner escalates to `RUNNER_WEDGED` instead — so every host path must publish it
* as retriable.
*/
export const RUNNER_BUSY_RUNNER_CODE = 'RUNNER_BUSY';
/**
* The runner's own code for the command that just tripped the execution watchdog: its main-thread
* work was abandoned and the thread is now occupied (#2552). Unlike `RUNNER_BUSY` (a fast refusal
* of a *later* command), this is the error the *stalling* command itself returns, so it is the only
* typed signal available before any refusal happens. Not retriable: the wait already elapsed and an
* immediate retry would only meet `RUNNER_BUSY`.
*/
export const MAIN_THREAD_TIMEOUT_RUNNER_CODE = 'MAIN_THREAD_TIMEOUT';
/**
* The runner's own code for refusing a repeat of a `commandId` it already finished, when that
* command's classification keeps no response body to replay. The command journal answers this; no
* command ran for the repeat. It is therefore silent about the runner's main thread, and a caller
* must not read it as drained occupancy ({@link runnerMainThreadOccupancyReport}).
*/
export const COMMAND_ALREADY_FINISHED_RUNNER_CODE = 'COMMAND_ALREADY_FINISHED';
/** The longest readiness preflight a ready runner session pays before a conservative command. */
export const RUNNER_READY_PREFLIGHT_TIMEOUT_MS = 1_000;
/**
* The runner's own code for a command it refused because abandoned main-thread work has occupied it
* past the wedge threshold (#1105). Like `RUNNER_BUSY`, the refused command never ran.
*/
export const RUNNER_WEDGED_RUNNER_CODE = 'RUNNER_WEDGED';
/**
* The runner's own code for a read whose session app is not running. No runner read launches the
* app — a bare launch would drop the payload of a launch still pending, such as a deep link held
* behind SpringBoard's confirmation — so the runner refuses any command carrying its read-only
* trait, including a mutation's leading read (a gesture's viewport read, a selector's resolving
* capture). Only the iOS runner refuses (`#if os(iOS)`); the macOS, tvOS and visionOS runners keep the
* activate repair. The refusal describes one poll: the launch that confirmation releases may still be
* starting when the next read arrives, so it is retriable for a `wait`, while the transport reads
* it as a definite answer and never resends it.
*/
const APP_NOT_RUNNING_RUNNER_CODE = 'APP_NOT_RUNNING';
export type RunnerCommand = {
coordinateTapTextInputEvidence?: CoordinateTapTextInputEvidence;
command:
| 'tap'
| 'mouseClick'
| 'longPress'
| 'drag'
| 'remotePress'
| 'type'
| 'swipe'
// Fused frame-resolve + drag scroll (non-tvOS). Intentionally mutating in runner command
// traits so it routes through single-send, command-id tracking, and lost-response status
// recovery like other gestures.
| 'scroll'
// macOS-only frame-resolve + desktop wheel scroll. Kept distinct from `scroll` so mobile
// touch drag semantics remain stable.
| 'desktopScroll'
| 'findText'
| 'querySelector'
| 'readText'
| 'snapshot'
| 'screenshot'
| 'backInApp'
| 'home'
| 'rotate'
| 'gesture'
| 'gestureViewport'
| 'appSwitcher'
| 'actionButton'
| 'volumeUp'
| 'volumeDown'
| 'keyboardDismiss'
| 'keyboardReturn'
| 'alert'
| 'sequence'
| 'recordStart'
| 'recordStop'
| 'status'
| 'uptime'
// The session app's XCUIApplication.state by name. A lifecycle read: it skips the activation
// preflight, so it reports the state the app is in rather than the one a repair leaves.
| 'appState'
// Reads the Simulator AX bridge tree in the runner process, off its journal and command queue.
| 'snapshotBridge'
// Sets the device's general pasteboard from the runner's own process: a simulator's
// `simctl pbcopy` only promises its data from a process that exits before anything reads it.
| 'pasteboardWrite'
| 'activate'
| 'terminate'
| 'targetReset'
| 'shutdown';
commandId?: string;
statusCommandId?: string;
appBundleId?: string;
text?: string;
selectorKey?: ElementSelectorKey;
selectorValue?: string;
allowNonHittableCoordinateFallback?: boolean;
delayMs?: number;
textEntryMode?: 'append' | 'replace';
action?: 'get' | 'accept' | 'dismiss';
x?: number;
y?: number;
button?: ClickButton;
remoteButton?: 'select' | 'menu' | 'home' | 'up' | 'down' | 'left' | 'right';
x2?: number;
y2?: number;
durationMs?: number;
/** Remaining request budget for runner work that performs bounded XCTest queries. */
timeoutMs?: number;
direction?: ScrollDirection;
amount?: number;
pixels?: number;
scrollReleaseBehavior?: ScrollReleaseBehavior;
orientation?: DeviceRotation;
/** Canonical pointer samples planned by the portable gesture runtime. */
gesturePlan?: GesturePlan;
outPath?: string;
fps?: number;
interactiveOnly?: boolean;
/** Pin the snapshot capture backend (same-backend evidence probes). */
preferredBackend?: SnapshotPreferredBackend;
/**
* Read accessibility custom actions for merged leaves. Opt-in: each element
* costs its own AX round trip, and the runner pins the private-AX backend
* because no other backend can carry them.
*/
customActions?: boolean;
observeOnly?: boolean;
depth?: number;
scope?: string;
raw?: boolean;
fullscreen?: boolean;
inlineScreenshot?: boolean;
synthesized?: boolean;
/**
* The lit panel's display and native box in points, sent only for a multi-panel device on a
* command that resolves a screen (ADR 0025).
*/
litPanel?: { displayId: number; widthPt: number; heightPt: number };
sequenceOrientation?: RunnerSequenceOrientation;
steps?: RunnerSequenceStep[];
snapshotBridge?: RunnerSnapshotBridgeRequest;
};
/**
* One request to the Simulator AX bridge reader that the runner serves. `target` names the foreground
* process of `appBundleId`. `describe` reads that process's tree under the guest bridge's own bounds,
* and refuses a process other than `expectedPid` and `expectedProcessStartTime` as a stale target, so
* it cannot be sent without them.
*/
export type RunnerSnapshotBridgeRequest =
| { verb: 'target'; requestId: string; maxDurationMs?: number }
| {
verb: 'describe';
requestId: string;
generation: string;
expectedPid: number;
expectedProcessStartTime: string;
maxDepth?: number;
maxNodes?: number;
maxDurationMs?: number;
maxResponseBytes?: number;
nativeLevelsHint?: number;
/**
* System surface host executables whose running process on this Simulator refuses the read with
* `system-surface-host-present`. The runner names its own Simulator.
*/
surfaceHostExecutables?: readonly string[];
};
/**
* One allowlisted coordinate gesture step inside a fused `sequence` runner command.
* The kind set is intentionally narrow (tap/doubleTap/longPress) and validated on both the
* daemon and runner sides — see `parseRunnerSequenceResult` below (the single interpretation point).
*/
export type RunnerSequenceStep = {
kind: 'tap' | 'doubleTap' | 'longPress';
x: number;
y: number;
durationMs?: number;
pauseMs?: number;
/**
* For `tap` steps on iOS non-tv: use the synthesized HID tap (synthesizedTapAt) fast path
* instead of the drag-based XCUICoordinate tapAt, matching the individual `tap` command.
*/
synthesized?: boolean;
};
export function resolveRunnerRequestSignal(options: {
requestId?: string;
signal?: AbortSignal;
}): AbortSignal | undefined {
const registeredSignal = getRequestSignal(options.requestId);
if (!options.signal) return registeredSignal;
if (!registeredSignal || registeredSignal === options.signal) return options.signal;
return AbortSignal.any([registeredSignal, options.signal]);
}
type RunnerRequestSignalOptions = {
requestId?: string;
signal?: AbortSignal;
};
/**
* Whether an abort reason is a caller's own deadline rather than a cancelled request. A `wait`
* bounds each poll with an abort signal whose reason is a `TimeoutError` (`runWithinWaitDeadline`);
* a cancelled request aborts through the registered request signal or the cancellation registry.
* The typed reason decides, never the error text the transport threw on abort.
*/
export function isCallerDeadlineAbortReason(reason: unknown): boolean {
return reason instanceof DOMException && reason.name === 'TimeoutError';
}
/**
* Whether the caller's own deadline ended this command, as opposed to the request being cancelled.
* A deadline that lands mid-fetch (surfacing as whatever the transport threw on abort) is read the
* same way as one that wakes a delay.
*/
export function callerDeadlineExpired(options: RunnerRequestSignalOptions): boolean {
if (isRequestCanceled(options.requestId) || getRequestSignal(options.requestId)?.aborted) {
return false;
}
return options.signal?.aborted === true && isCallerDeadlineAbortReason(options.signal.reason);
}
/**
* The signal a runner start reacts to. A cancelled request (client disconnect) must kill the
* blocking xctestrun build and the runner launch instead of orphaning them, so the registered request
* signal passes through untouched. A caller's own deadline must not: the runner start it interrupts
* is the one the retry needs, and a start that pays itself again on every short-timeout poll never
* finishes on a slow host (#2894). The start keeps going on its own startup budget, and the caller's
* command is still cut off by its unfiltered signal once the runner answers.
*/
export function resolveRunnerStartupSignal(
options: RunnerRequestSignalOptions,
): AbortSignal | undefined {
const registeredSignal = getRequestSignal(options.requestId);
const callerSignal = options.signal;
if (!callerSignal || callerSignal === registeredSignal) return registeredSignal;
// The caller signal is filtered through its own controller, so a deadline never reaches the
// start; the registered signal is composed with `AbortSignal.any`, which detaches its own
// listener once the composed signal settles, so a request that polls many times does not
// accumulate listeners on its long-lived cancellation signal.
const filtered = new AbortController();
const forward = () => {
if (!isCallerDeadlineAbortReason(callerSignal.reason)) filtered.abort(callerSignal.reason);
};
if (callerSignal.aborted) forward();
else callerSignal.addEventListener('abort', forward, { once: true });
return registeredSignal ? AbortSignal.any([registeredSignal, filtered.signal]) : filtered.signal;
}
/**
* The code the XCTest runner answers with when it declines to place a scroll gesture under the
* on-screen keyboard (#2500). It is the runner's own vocabulary, so it is declared here beside the
* set that keeps it off the wire, and the Apple scroll owner matches it on `details.runnerErrorCode`
* rather than on error text.
*/
export const SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE = 'SCROLL_KEYBOARD_OCCLUDES_SURFACE';
/**
* The runner's own code refusing a `keyboard dismiss` whose visible keyboard exposes no dismiss key
* (#1606). Background taps are never attempted, so no geometry can prove a tap outside the keys is
* side-effect-free; the refusal is the runner's decision and it answers before dispatching anything.
* It is the runner's vocabulary, so it is declared here beside the set that keeps it off the wire,
* and consumers read `details.reason`, never the message prose.
*/
export const KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE = 'KEYBOARD_DISMISS_UNAVAILABLE';
/**
* The codes the XCTest runner answers with when a resolved-display capture it was asked to make did
* not happen (#2728): no window resolved so no display could be named, the resolved window named no
* display, or the resolved display handed back an image it could not encode upright. The runner emits
* them from every consumer of that helper — the `screenshot` command's fallback, `record start`'s
* required first frame, and an optional visual check such as the `back` fallback's before/after
* sample. They are the runner's own vocabulary, so they are declared here beside the set that keeps
* them off the wire; a required capture fails closed on them rather than falling back to a screen
* nobody is on, and an optional one reports the refusal as an unknown. Only the `screenshot` route
* consumes the set for its own simctl-to-runner decision, but the set names the whole family.
*/
const RUNNER_SCREEN_WINDOW_UNRESOLVED_RUNNER_CODE = 'APP_SCREEN_WINDOW_UNRESOLVED';
const RUNNER_SCREEN_UNRESOLVED_RUNNER_CODE = 'APP_SCREEN_UNRESOLVED';
const RUNNER_SCREEN_CAPTURE_UNRENDERABLE_RUNNER_CODE = 'APP_SCREEN_CAPTURE_UNRENDERABLE';
const RUNNER_SCREEN_OFF_LIT_PANEL_RUNNER_CODE = 'APP_SCREEN_OFF_LIT_PANEL';
/**
* Every runner code meaning "this capture did not happen", covering the display, the image, and the
* panel: on a foldable, a target app whose windows are all on the dark panel is refused.
*/
export const RUNNER_SCREEN_CAPTURE_REFUSAL_RUNNER_CODES: ReadonlySet<string> = new Set([
RUNNER_SCREEN_WINDOW_UNRESOLVED_RUNNER_CODE,
RUNNER_SCREEN_UNRESOLVED_RUNNER_CODE,
RUNNER_SCREEN_CAPTURE_UNRENDERABLE_RUNNER_CODE,
RUNNER_SCREEN_OFF_LIT_PANEL_RUNNER_CODE,
]);
/**
* The runner's own code refusing a coordinate `fill` whose point identified no text input (#1721).
* The synthesized first-responder replacement this route would otherwise take has no element, so its
* clear and its typed text reach whichever field already holds focus. The runner refuses before
* dispatching the focus tap, so the reply proves nothing ran.
*/
export const NO_TEXT_INPUT_AT_POINT_RUNNER_CODE = 'NO_TEXT_INPUT_AT_POINT';
/**
* The runner code refusing a coordinate `fill` whose pre-tap input lookup could not answer on the
* degraded channel. Like NO_TEXT_INPUT_AT_POINT it answers before the focus tap, and it is not a
* claim that the point has no input — only that the runner could not tell.
*/
export const TEXT_INPUT_PROBE_UNAVAILABLE_RUNNER_CODE = 'TEXT_INPUT_PROBE_UNAVAILABLE';
/**
* The runner codes for a synthesized long press, scroll, or planned gesture on iOS; the CLI `swipe` is
* a planned fling gesture.
* NOT_DISPATCHED: the event synthesis refused before any of its events reached XCTest, so the
* command sent nothing. OUTCOME_UNKNOWN: failed after its events reached XCTest, so it may have run;
* the runner never falls back to repeat it. Any other refusal, a platform one included, keeps
* UNSUPPORTED_OPERATION.
*/
const SYNTHESIZED_GESTURE_NOT_DISPATCHED_RUNNER_CODE = 'SYNTHESIZED_GESTURE_NOT_DISPATCHED';
const SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN_RUNNER_CODE = 'SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN';
/**
* The runner codes for an iOS `back` swipe. BACK_SWIPE_NO_CHANGE: the swipe was sent and the screen
* did not change. BACK_SWIPE_UNVERIFIED: the swipe was sent but the screen kept changing before it
* or could not be sampled after it. Both ran the swipe, so they stay `unknown`.
* BACK_SWIPE_NOT_DISPATCHED: the swipe was refused before any touch went down.
*/
const BACK_SWIPE_NO_CHANGE_RUNNER_CODE = 'BACK_SWIPE_NO_CHANGE';
const BACK_SWIPE_UNVERIFIED_RUNNER_CODE = 'BACK_SWIPE_UNVERIFIED';
const BACK_SWIPE_NOT_DISPATCHED_RUNNER_CODE = 'BACK_SWIPE_NOT_DISPATCHED';
/**
* Runner codes that classify a failure for the host without renaming it on the wire. They stay
* `COMMAND_FAILED` unless their row names the code the caller already reads the family under, and
* survive as `details.runnerErrorCode`, which is what family policy reads: `RUNNER_BUSY` for
* retriable contention, `ALERT_NOT_FOUND` for an alert that is not there yet, the scroll keyboard
* refusal for a surface the runner declined to swipe under the keys, the retriable
* `APP_NOT_RUNNING` for a read the runner refused rather than launch the session app, and the
* keyboard-dismiss refusal, which stays `UNSUPPORTED_OPERATION` because that is the code
* `keyboard dismiss` already refuses with.
*/
const DIAGNOSTIC_ONLY_RUNNER_ERROR_CODES: ReadonlyMap<
string,
Readonly<{ wireCode?: AppErrorCode; retriable?: true }>
> = new Map([
[RUNNER_BUSY_RUNNER_CODE, { retriable: true }],
[MAIN_THREAD_TIMEOUT_RUNNER_CODE, {}],
[APP_NOT_RUNNING_RUNNER_CODE, { retriable: true }],
[ALERT_NOT_FOUND_RUNNER_CODE, {}],
[SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE, {}],
[KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE, { wireCode: 'UNSUPPORTED_OPERATION' }],
[SYNTHESIZED_GESTURE_NOT_DISPATCHED_RUNNER_CODE, {}],
[SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN_RUNNER_CODE, {}],
[BACK_SWIPE_NO_CHANGE_RUNNER_CODE, {}],
[BACK_SWIPE_UNVERIFIED_RUNNER_CODE, {}],
[BACK_SWIPE_NOT_DISPATCHED_RUNNER_CODE, {}],
...[...RUNNER_SCREEN_CAPTURE_REFUSAL_RUNNER_CODES].map((code) => [code, {}] as const),
]);
/**
* `details.reason` for the runner codes a consumer acts on, so it reads one field instead of
* `details.runnerErrorCode`, which stays for the runner's own vocabulary. Both the codes that stay
* off the wire and the codes that travel under their own name are answered from this one table.
*/
const RUNNER_REPORTED_ERROR_REASONS: ReadonlyMap<string, RunnerReportedErrorReason> = new Map([
[RUNNER_BUSY_RUNNER_CODE, 'runner_busy'],
[MAIN_THREAD_TIMEOUT_RUNNER_CODE, 'runner_main_thread_timeout'],
[NO_TEXT_INPUT_AT_POINT_RUNNER_CODE, 'no_text_input_at_point'],
[TEXT_INPUT_PROBE_UNAVAILABLE_RUNNER_CODE, 'text_input_probe_unavailable'],
[SYNTHESIZED_GESTURE_NOT_DISPATCHED_RUNNER_CODE, 'synthesized_gesture_not_dispatched'],
[SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN_RUNNER_CODE, 'synthesized_gesture_outcome_unknown'],
[BACK_SWIPE_NO_CHANGE_RUNNER_CODE, 'back_swipe_no_change'],
[BACK_SWIPE_UNVERIFIED_RUNNER_CODE, 'back_swipe_unverified'],
[BACK_SWIPE_NOT_DISPATCHED_RUNNER_CODE, 'back_swipe_not_dispatched'],
[KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE, 'keyboard_dismiss_unavailable'],
]);
/**
* Runner codes whose reply proves the command never reached the device. The refusals answer before
* the command runs, the selector refusals included: the runner resolves the element and refuses
* before any gesture. `INVALID_ARGS` comes only from request decoding and argument validation,
* each ahead of any gesture. Every other code, and a reply without one, is `unknown`:
* `UNSUPPORTED_OPERATION` is also what an element or coordinate tap reports after it ran.
*/
const RUNNER_ERROR_CODE_DISPATCH: ReadonlyMap<string, DispatchDisclosure> = new Map([
['INVALID_ARGS', 'no'],
['ELEMENT_NOT_FOUND', 'no'],
['ELEMENT_OFFSCREEN', 'no'],
['AMBIGUOUS_MATCH', 'no'],
[RUNNER_BUSY_RUNNER_CODE, 'no'],
[RUNNER_WEDGED_RUNNER_CODE, 'no'],
[APP_NOT_RUNNING_RUNNER_CODE, 'no'],
['OBSERVATION_UNAVAILABLE', 'no'],
[SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE, 'no'],
[ALERT_NOT_FOUND_RUNNER_CODE, 'no'],
[NO_TEXT_INPUT_AT_POINT_RUNNER_CODE, 'no'],
[TEXT_INPUT_PROBE_UNAVAILABLE_RUNNER_CODE, 'no'],
[ALERT_BUTTON_NOT_FOUND_RUNNER_CODE, 'no'],
[ALERT_UNRESOLVED_RUNNER_CODE, 'no'],
[SYNTHESIZED_GESTURE_NOT_DISPATCHED_RUNNER_CODE, 'no'],
[BACK_SWIPE_NOT_DISPATCHED_RUNNER_CODE, 'no'],
[KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE, 'no'],
...[...RUNNER_SCREEN_CAPTURE_REFUSAL_RUNNER_CODES].map((code) => [code, 'no'] as const),
]);
/**
* `details.reason` for the runner codes a consumer acts on, so it reads one field instead of
* `details.runnerErrorCode`, which stays for the runner's own vocabulary.
*/
type RunnerReportedErrorReason =
| 'runner_busy'
| 'runner_main_thread_timeout'
| 'no_text_input_at_point'
| 'text_input_probe_unavailable'
| 'synthesized_gesture_not_dispatched'
| 'synthesized_gesture_outcome_unknown'
| 'back_swipe_no_change'
| 'back_swipe_unverified'
| 'back_swipe_not_dispatched'
| 'keyboard_dismiss_unavailable';
/** Wire code plus the details every path must publish for one runner-reported error code. */
export type RunnerReportedErrorClass = Readonly<{
code: AppError['code'];
details: Readonly<{
runnerErrorCode?: string;
retriable?: true;
reason?: RunnerReportedErrorReason;
dispatched: DispatchDisclosure;
}>;
}>;
/**
* The one reading of a runner-reported error code (#2484 follow-up). A runner failure reaches the
* host by two routes — the command's own response, and the lifecycle journal a status probe reads
* back after the transport response was lost — and both must classify it identically, or the same
* runner condition surfaces under two codes with only one of them marked retriable.
*/
export function classifyRunnerReportedError(
runnerErrorCode: string | undefined,
): RunnerReportedErrorClass {
const diagnosticOnly =
runnerErrorCode === undefined
? undefined
: DIAGNOSTIC_ONLY_RUNNER_ERROR_CODES.get(runnerErrorCode);
const reason =
runnerErrorCode === undefined ? undefined : RUNNER_REPORTED_ERROR_REASONS.get(runnerErrorCode);
return Object.freeze({
code: diagnosticOnly
? (diagnosticOnly.wireCode ?? 'COMMAND_FAILED')
: toAppErrorCode(runnerErrorCode),
details: Object.freeze({
runnerErrorCode,
...(diagnosticOnly?.retriable === true ? { retriable: true as const } : {}),
...(reason === undefined ? {} : { reason }),
dispatched:
(runnerErrorCode === undefined
? undefined
: RUNNER_ERROR_CODE_DISPATCH.get(runnerErrorCode)) ?? 'unknown',
}),
});
}
export type RunnerResponsePayload = {
ok?: unknown;
error?: { code?: unknown; message?: unknown; hint?: unknown };
data?: unknown;
};
/**
* The one decoding of a runner response body (#2662). The envelope arrives at three readers — a
* command's own response, the lifecycle journal a status probe reads back after the transport
* response was lost, and the adoption `uptime` probe — and all three must agree on what is
* readable, or a body one of them refuses becomes an answer for another.
*
* Only a JSON object can be an envelope. A body that is not JSON at all, and a JSON scalar or array
* that carries no `ok`, are both transport-shaped: neither is something the runner's encoder emits,
* and reading either as an empty reply would let a proxy page or a half-written body answer for a
* command the runner may still be executing.
*/
export function decodeRunnerResponseBody(text: string): RunnerResponsePayload {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
}
if (!isRunnerEnvelopeObject(parsed)) {
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
}
return parsed;
}
function isRunnerEnvelopeObject(parsed: unknown): parsed is RunnerResponsePayload {
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed);
}
/** The runner's `ok` is a Swift `Bool`, so only the literal `true` is an answer. */
export function isRunnerResponseOk(payload: RunnerResponsePayload): boolean {
return payload.ok === true;
}
export function readRunnerResponseData(payload: RunnerResponsePayload): Record<string, unknown> {
if (!payload.data || typeof payload.data !== 'object' || Array.isArray(payload.data)) return {};
return payload.data as Record<string, unknown>;
}
export function buildRunnerResponseError(
payload: RunnerResponsePayload,
logPath?: string,
): AppError {
const runnerErrorCode = readRunnerErrorCode(payload.error?.code);
const errorMessage =
typeof payload.error?.message === 'string' ? payload.error.message : undefined;
const hint = typeof payload.error?.hint === 'string' ? payload.error.hint : undefined;
const classification = classifyRunnerReportedError(runnerErrorCode);
return new AppError(classification.code, errorMessage ?? 'Runner error', {
runner: payload,
...classification.details,
xcodebuild: {
exitCode: 1,
stdout: '',
stderr: '',
},
hint,
logPath,
});
}
function readRunnerErrorCode(rawCode: unknown): string | undefined {
return typeof rawCode === 'string' && rawCode.trim().length > 0 ? rawCode.trim() : undefined;
}
export function withRunnerCommandId(command: RunnerCommand): RunnerCommand {
if (command.command === 'status') return command;
if (command.commandId?.trim()) return command;
return { ...command, commandId: createRunnerCommandId() };
}
function createRunnerCommandId(): string {
return `runner-${crypto.randomUUID()}`;
}
export function assertRunnerRequestActive(requestId: string | undefined): void {
if (!isRequestCanceled(requestId)) return;
throw createRequestCanceledError();
}
// ── Listener endpoint and token ─────────────────────────────────────────────────────────────────
const RUNNER_TOKEN_HEADER = 'X-Agent-Device-Runner-Token';
const RUNNER_TOKEN_ENFORCED_HEADER = 'X-Agent-Device-Runner-Auth';
const RUNNER_TOKEN_BYTES = 24;
export const RUNNER_TOKEN_UNSUPPORTED_REASON = 'runner_token_unsupported';
/** How to reach one runner generation: its listener port and the token it requires. */
export type RunnerEndpoint = Readonly<{
port: number;
token: string;
/** A provider's authenticated forwarding route; omitted for local and USB runners. */
http?: Readonly<{ url: string; headers?: Readonly<Record<string, string>> }>;
}>;
export function mintRunnerToken(): string {
return crypto.randomBytes(RUNNER_TOKEN_BYTES).toString('base64url');
}
/** What the runner reads at launch to open its listener; see `RunnerTests+Environment.swift`. */
export function runnerListenerEnv(
endpoint: RunnerEndpoint,
bindAddress?: string,
): Record<string, string> {
return {
AGENT_DEVICE_RUNNER_PORT: String(endpoint.port),
AGENT_DEVICE_RUNNER_TOKEN: endpoint.token,
...(bindAddress ? { AGENT_DEVICE_RUNNER_BIND_IP: bindAddress } : {}),
};
}
export function runnerRequestHeaders(endpoint: RunnerEndpoint): Record<string, string> {
return { 'Content-Type': 'application/json', [RUNNER_TOKEN_HEADER]: endpoint.token };
}
/**
* Passes a reply only from a runner that declares it requires the token. A runner built before the
* token existed listens without one, so it is refused rather than driven.
*/
export function requireTokenEnforcingRunner(response: Response): Response {
if (response.headers.get(RUNNER_TOKEN_ENFORCED_HEADER) === 'required') return response;
throw new AppError('COMMAND_FAILED', 'XCTest runner does not require a listener token', {
reason: RUNNER_TOKEN_UNSUPPORTED_REASON,
hint: 'Rebuild the runner with this agent-device version. A configured iosXctestrunFile must come from the same version.',
});
}
// --- Sequence commands ---
export const SEQUENCEABLE_RUNNER_STEP_KINDS = ['tap', 'doubleTap', 'longPress'] as const;
export type SequenceableRunnerStepKind = (typeof SEQUENCEABLE_RUNNER_STEP_KINDS)[number];
/**
* Hard cap on steps per `sequence` request. Two constraints set this bound:
* - The retained journal response stays well under the 16KB cap: 20 steps x ~150B
* per-step result (~3-4KB worst case) leaves ample headroom for lost-response recovery.
* - It bounds the UI-uncertainty window when a transport response is lost mid-sequence —
* at most 20 ordered mutating steps can have run unobserved.
* Longer daemon-side series chunk into ceil(N/20) requests (still stop-on-failure across chunks).
*/
export const MAX_RUNNER_SEQUENCE_STEPS = 20;
// The runner clamps durationMs to 16..10000 (RunnerTests+SequenceExecution.swift), so the
// validator only guards the upper bound and finiteness; the floor is the runner's job. This keeps
// legal CLI input like `press --hold-ms 5` (holdMs min 0) acceptable instead of rejecting it here.
const MIN_DURATION_MS = 0;
const MAX_DURATION_MS = 10_000;
const MIN_PAUSE_MS = 0;
const MAX_PAUSE_MS = 10_000;
export type RunnerSequenceStepResult = {
ok: boolean;
kind: string;
errorCode?: string;
errorMessage?: string;
errorHint?: string;
gestureStartUptimeMs?: number;
gestureEndUptimeMs?: number;
};
export type ParsedRunnerSequenceResult = {
results: RunnerSequenceStepResult[];
completedSteps: number;
failedStepIndex?: number;
sequenceOrientation?: RunnerSequenceOrientation;
};
export type RunnerSequenceOrientation = 1 | 2 | 3 | 4;
function isSequenceableKind(kind: unknown): kind is SequenceableRunnerStepKind {
return (
typeof kind === 'string' && (SEQUENCEABLE_RUNNER_STEP_KINDS as readonly string[]).includes(kind)
);
}
/** A sequence the daemon refuses before sending it: nothing reached the runner. */
function invalidSequence(message: string, details: Record<string, unknown>): AppError {
return discloseDispatch(
new AppError('INVALID_ARGS', message, { ...details, reason: 'runner_sequence_invalid' }),
'no',
);
}
function invalidStep(index: number, kind: unknown, message: string): AppError {
return invalidSequence(message, {
stepIndex: index,
kind: typeof kind === 'string' ? kind : undefined,
});
}
/**
* Validates an ordered list of sequence steps before sending, throwing AppError('INVALID_ARGS')
* naming the offending step index and kind. The runner rejects the same kinds, missing coords, and
* over-length lists with nothing executed; durations differ — the runner clamps durationMs into
* 16..10000 rather than rejecting, so this validator only rejects non-finite/negative/too-high
* durations and leaves the floor to the runner's clamp.
*/
export function validateRunnerSequenceSteps(steps: RunnerSequenceStep[]): void {
if (!Array.isArray(steps) || steps.length === 0) {
throw invalidSequence('sequence requires at least one step', {
stepCount: Array.isArray(steps) ? steps.length : 0,
});
}
if (steps.length > MAX_RUNNER_SEQUENCE_STEPS) {
throw invalidSequence(
`sequence accepts at most ${MAX_RUNNER_SEQUENCE_STEPS} steps, received ${steps.length}`,
{ stepCount: steps.length, maxSteps: MAX_RUNNER_SEQUENCE_STEPS },
);
}
steps.forEach((step, index) => validateRunnerSequenceStep(step, index));
}
function validateRunnerSequenceStep(step: RunnerSequenceStep, index: number): void {
if (!isSequenceableKind(step.kind)) {
throw invalidStep(
index,
step.kind,
`sequence step ${index} has unsupported kind "${String(step.kind)}"; allowed: ${SEQUENCEABLE_RUNNER_STEP_KINDS.join(', ')}`,
);
}
if (!Number.isFinite(step.x) || !Number.isFinite(step.y)) {
throw invalidStep(
index,
step.kind,
`sequence step ${index} (${step.kind}) requires finite x and y`,
);
}
if (step.durationMs !== undefined) {
assertInRange(
step.durationMs,
MIN_DURATION_MS,
MAX_DURATION_MS,
index,
step.kind,
'durationMs',
);
}
if (step.pauseMs !== undefined) {
assertInRange(step.pauseMs, MIN_PAUSE_MS, MAX_PAUSE_MS, index, step.kind, 'pauseMs');
}
}
function assertInRange(
value: number,
min: number,
max: number,
index: number,
kind: string,
field: string,
): void {
if (!Number.isFinite(value) || value < min || value > max) {
throw invalidStep(
index,
kind,
`sequence step ${index} (${kind}) ${field} must be between ${min} and ${max}`,
);
}
}
export function buildRunnerSequenceCommand(
steps: RunnerSequenceStep[],
appBundleId?: string,
): RunnerCommand {
validateRunnerSequenceSteps(steps);
return { command: 'sequence', steps, appBundleId };
}
/**
* Single interpretation point for a `sequence` runner response. The runner returns
* ok:true even when a step failed (step failure is data, so the tracked unit completed
* and its results are retained for lost-response recovery). This maps a present
* failedStepIndex into a deterministic AppError keyed off the failing step's errorCode,
* naming the step index and kind, with completedSteps + per-step results in details.
*
* Any future caller issuing `sequence` MUST route the response through here, or step
* failures will be silently ignored.
*/
export function parseRunnerSequenceResult(
data: Record<string, unknown>,
): ParsedRunnerSequenceResult {
const results = readSequenceResults(data.sequenceResults);
const completedSteps =
typeof data.completedSteps === 'number' && Number.isFinite(data.completedSteps)
? data.completedSteps
: results.filter((result) => result.ok).length;
const detectedFailedStepIndex = results.findIndex((result) => !result.ok);
const failedStepIndex =
typeof data.failedStepIndex === 'number' && Number.isFinite(data.failedStepIndex)
? data.failedStepIndex
: detectedFailedStepIndex >= 0
? detectedFailedStepIndex
: undefined;
if (failedStepIndex !== undefined) {
throw buildSequenceStepError(results, completedSteps, failedStepIndex);
}
const orientation = data.sequenceOrientation;
return {
results,
completedSteps,
failedStepIndex,
...(orientation === 1 || orientation === 2 || orientation === 3 || orientation === 4
? { sequenceOrientation: orientation }
: {}),
};
}
function buildSequenceStepError(
results: RunnerSequenceStepResult[],
completedSteps: number,
failedStepIndex: number,
): AppError {
const failed = results[failedStepIndex];
const kind = failed?.kind ?? 'step';
const message = failed?.errorMessage ?? `sequence step ${failedStepIndex} (${kind}) failed`;
// A step code the runner keeps off the wire (such as SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN) reads as
// it does on a standalone command: COMMAND_FAILED with its runner code, reason, and dispatch.
// `runApplePressSeries` turns it into `unknown` once an earlier step ran.
const stepCode = toAppErrorCode(failed?.errorCode);
const classification = classifyRunnerReportedError(failed?.errorCode);
const diagnosticOnly = classification.code !== stepCode;
return new AppError(diagnosticOnly ? classification.code : stepCode, message, {
...(diagnosticOnly
? {
runnerErrorCode: failed?.errorCode,
...(classification.details.reason === undefined
? {}
: { reason: classification.details.reason }),
}
: {}),
// Only a step code that classifies a dispatch publishes one; a plain refusal or a code-less step
// leaves it unset, as a sequence failure always did.
...(sequenceStepClassifiesDispatch(failed?.errorCode)
? { dispatched: classification.details.dispatched }
: {}),
failedStepIndex,
failedStepKind: kind,
completedSteps,
sequenceResults: results,
hint:
failed?.errorHint ??
'Run snapshot -i to inspect the current UI, then continue from the observed state.',
});
}
function sequenceStepClassifiesDispatch(code: string | undefined): boolean {
return (
code !== undefined &&
(RUNNER_ERROR_CODE_DISPATCH.has(code) ||
code === SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN_RUNNER_CODE)
);
}
function readSequenceResults(value: unknown): RunnerSequenceStepResult[] {
if (!Array.isArray(value)) return [];
return value.map((entry) => {
const record = (entry ?? {}) as Record<string, unknown>;
return {
ok: record.ok === true,
kind: typeof record.kind === 'string' ? record.kind : 'unknown',
errorCode: typeof record.errorCode === 'string' ? record.errorCode : undefined,
errorMessage: typeof record.errorMessage === 'string' ? record.errorMessage : undefined,
errorHint: typeof record.errorHint === 'string' ? record.errorHint : undefined,
gestureStartUptimeMs:
typeof record.gestureStartUptimeMs === 'number' ? record.gestureStartUptimeMs : undefined,
gestureEndUptimeMs:
typeof record.gestureEndUptimeMs === 'number' ? record.gestureEndUptimeMs : undefined,
};
});
}