Skip to content

Commit 64854af

Browse files
authored
fix(ios-runner): slow synthesized replacement so a value-owning field loses fewer characters (callstack#2904)
* fix(ios-runner): bound the synthesized replacement pace so a value-owning field keeps it A replacement burst typed at XCTest's default 60 characters/second outruns an app that owns its field's value and re-applies it after the edit that produced it, which is how a controlled React Native `TextInput` behaves. That write erases whatever the burst typed while it was in flight and the field then sits stable short of the request: first characters and tail survive, a middle run is gone, which is the `fill id="field-email" ada@example` -> `aexample` CI signature. The commit wait can refuse such a value but cannot repair it, because a retype races the same write. 12 characters/second spaces characters ~83 ms apart. The new `--agent-device-text-entry-async-value-write` fixture owns its field's value and the iOS lane test pins the pace against it: raising the pace re-opens the race and turns that test red. A write-back still in flight 150 ms after an edit corrupts a burst at this pace too, so this narrows the window rather than closing it, and the measured wall-clock cost of the pace is recorded next to the commit ceiling it sits upstream of. Closes callstack#2080 * fix(ios-runner): bound synthesized delivery and model the app's render, not a timer Review asked for a delivery ceiling tied to text length, and the iOS lane showed the lane test itself was the weaker half of this change: a fixture that schedules a write lands differently depending on how loaded the host is, and it failed on CI holding `ad@example` at the shipped pace. `TextEntryTiming.synthesizedDeliveryCeiling` bounds how long a burst may spend posting. The private synthesize call delivers as it returns, so text beyond the ceiling would still have been arriving when the transport gave up on the command, leaving the runner typing into a field nobody waits for and the next command finding it busy. `fill` now answers `TEXT_INPUT_SYNTHESIS_BUDGET_EXCEEDED` before posting the first character, and the element-less `type` fallback keeps its long text on the verified application-wide route it already had. The pace stays owned by `RunnerSynthesizedTextEntry` and is read from Swift, so the delivery budget and the acknowledge-window policy derive from one declaration. `testSynthesizedPaceLeavesRoomForAnAppToAcknowledgeEachEdit` pins the pace at two windows per character or slower, and the budget test pins the refusal boundary; both are pure and run on the host lane. The fixture now decides at the edit whether a character overtook a render instead of scheduling one against a timer. A loaded host stretches the gaps between characters, which can only make that app keep up better, so the safe half no longer depends on how busy the machine is. The lane run watches a 5ms window, an app no pace this runner could ship outruns; the red half was verified at the 40ms policy window, where the pre-fix pace leaves the field holding `a` against 20 write-backs. * test(ios-runner): assert the runner's guarantee, not the app's race The lane test failed on CI twice: first holding `ad@example`, then `ada@exampl` with a single write-back. Both were honest `TEXT_INPUT_COMMIT_NOT_OBSERVED` refusals over a field the app had rewritten, and both were the test assuming it knew whether the app had won a round trip. XCTest does not deliver `typingSpeed:` characters evenly — CI saw two characters of a paced burst 4 ms apart — so no acknowledge window a fixture watches is a promise about the host. The test now follows the fixture's own counter: an app that kept up has to show the exact value and an ok, and an app that overtook the burst has to show the refusal. Verified on both branches, the strict one at the 5 ms lane window and the refusal one at 150 ms. That is the invariant the runner owns, and the one callstack#2080 was about: never an ok over a field the app rewrote. * fix(ios-runner): charge a spaced synthesized fill its per-character call and delay A delayed plan posts each character in its own synthesize call and sleeps between calls, but the delivery budget charged it max(delay, interval) per character. At --delay-ms 80 it admitted 360 characters; measured on a simulator, one call costs about 222 ms, so a 155-character fill already took 48 s, past the 45 s command budget. The budget now charges every call the pace for its characters plus a measured 150 ms overhead, and the delay between calls. maxTextLength is derived from the same projection, and the refusal hint names both the undelayed budget and the one at --delay-ms 80. * docs(fill): document TEXT_INPUT_SYNTHESIS_BUDGET_EXCEEDED next to the other text-entry codes * fix(ios-runner): bound synthesized delivery by the main-thread watchdog and pin the pace the app sees A 358-character fill through the daemon was abandoned by the runner's 30 s main-thread watchdog with the burst still typing. The delivery ceiling was a free-standing 30 s sized against the 45 s transport budget, while the whole command runs under mainThreadExecutionTimeout. The ceiling is now derived from that watchdog minus a focus allowance and the commit wait's ceiling (18 s), so the admitted text fits with the longest commit wait: 214 characters undelayed, 57 at --delay-ms 80. The app-owned-value lane test accepted either outcome and stayed green at 60 characters per second. It now asserts the spacing the fixture app receives: a burst's characters average at least one acknowledge window apart. That is red at 60 (11 edits in about 110 ms) and green at 12 (about 780 ms). A strict "the app keeps up" assertion is not possible: at a 40 ms window, 12 characters per second still lost one character in 13 of 20 bursts, because XCTest spaces the characters unevenly. The comments that claimed survival are narrowed to match. The call overhead and the --delay-ms 80 recovery delay move into TextEntryTiming beside the other text-entry timings, and both hints read the recovery delay from there. * fix(ios-runner): charge the delivery budget the whole type command The element-less, keyboard-visible branch tested the budget against the chunk it was about to post. An append peels its first character for warmup and a `--delay-ms` plan posts one character per call, so no chunk ever looked long and the paced synthesizer kept a text the command cannot carry: 215 characters arrived as 1 + 214, both inside the budget. The branch is now charged the command's own length and delay. That branch had no test, so it gained one: 215 characters through an unresolved target type application-wide, and the value arrives unverified because the branch has no element to read back. The fixture field keeps a real input view under `--agent-device-text-entry-soft-keyboard`, without which no branch requiring a visible keyboard is reachable. * fix(ios-runner): charge the warmup split the type plan really makes The review found `projectedSeconds` charging one synthesize call for an append-mode `type` while the route posts a warmup character and then the rest, so the estimate undercounted one call and the wait between them. The over-budget branch that asks is the one with no element, so its warmup wait is one poll: `waitForWarmupValue` has no expected value to wait for. That branch now charges 2 calls and the poll, which is one character less than a replacement of the same length. Also: the budget hint and the docs named one limit and said "the number" for a delayed retry, which reads as the larger one; both now name the limit for the delay in play and say the delay falls between characters. The pace's header comment claimed the acknowledge window is derived from it, which it is not. The synthesized-replacement helper builds its command with JSONSerialization, and the over-budget lane test polls the field under its own deadline instead of reading `value` once on a route that verifies nothing.
1 parent 769ee23 commit 64854af

15 files changed

Lines changed: 583 additions & 24 deletions

‎apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m‎

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ @interface AgentDeviceRunnerViewController : UIViewController
6565
@property(nonatomic, strong) UILabel *alertActivationBusyAnswer;
6666
@property(nonatomic, assign) NSUInteger firstAlertActions;
6767
@property(nonatomic, assign) NSUInteger replacementAlertActions;
68+
@property(nonatomic, strong) UILabel *textEntryWriteBackStatus;
69+
@property(nonatomic, assign) NSUInteger textEntryRenderedEdits;
70+
@property(nonatomic, assign) NSUInteger textEntryWriteBacks;
71+
@property(nonatomic, copy, nullable) NSString *textEntryRenderedValue;
72+
@property(nonatomic, assign) NSTimeInterval textEntryLastEditTime;
73+
@property(nonatomic, assign) NSTimeInterval textEntryBurstStartTime;
74+
@property(nonatomic, assign) NSUInteger textEntryBurstEdits;
75+
@property(nonatomic, assign) NSTimeInterval textEntryBurstMinGap;
76+
@property(nonatomic, assign) NSTimeInterval textEntryAcknowledgeWindowSeconds;
6877
@property(nonatomic, assign) BOOL alertFixtureStarted;
6978
@property(nonatomic, strong) NSTimer *alertActivationBusyBackstop;
7079
@property(nonatomic, strong) NSTimer *alertBannerRepost;
@@ -175,6 +184,17 @@ - (void)updateAlertActionStatus {
175184
(unsigned long)self.replacementAlertActions];
176185
}
177186

187+
- (void)updateTextEntryWriteBackStatus {
188+
NSTimeInterval burstSpan = self.textEntryLastEditTime - self.textEntryBurstStartTime;
189+
self.textEntryWriteBackStatus.text = [NSString
190+
stringWithFormat:@"edits=%lu write-backs=%lu burst-edits=%lu burst-ms=%lu min-gap-ms=%lu",
191+
(unsigned long)self.textEntryRenderedEdits,
192+
(unsigned long)self.textEntryWriteBacks,
193+
(unsigned long)self.textEntryBurstEdits,
194+
(unsigned long)llround(burstSpan * 1000),
195+
(unsigned long)llround(self.textEntryBurstMinGap * 1000)];
196+
}
197+
178198
- (void)presentAlertFixtureReplacement:(BOOL)replacement {
179199
NSArray<NSString *> *arguments = NSProcessInfo.processInfo.arguments;
180200
BOOL sameTitle = [arguments containsObject:@"--agent-device-alert-same-title"];
@@ -232,7 +252,51 @@ - (void)viewDidAppear:(BOOL)animated {
232252
}
233253
#endif
234254

255+
// How fast an app that owns this field's value can acknowledge edits: one render per window, passed
256+
// by the test as `--agent-device-text-entry-acknowledge-window <seconds>`. An edit that arrives
257+
// inside that window overtook the render still in flight, so the value that render commits predates
258+
// it and writing it erases the characters that got ahead of the app. The app then reads its own
259+
// erasure back into its model, which is why the field stays wrong instead of healing when the burst
260+
// finishes. The window is decided at the edit rather than scheduled, so a loaded host, which
261+
// stretches the gaps between characters, can only make this app keep up better.
262+
static NSTimeInterval AgentDeviceTextEntryAcknowledgeWindow(void) {
263+
NSArray<NSString *> *arguments = NSProcessInfo.processInfo.arguments;
264+
NSUInteger index = [arguments indexOfObject:@"--agent-device-text-entry-acknowledge-window"];
265+
return index == NSNotFound || index + 1 >= arguments.count ? 0 : [arguments[index + 1] doubleValue];
266+
}
267+
268+
// Edits further apart than this belong to different bursts: one runner command's characters arrive
269+
// well inside it, and two commands are separated by at least a commit-wait poll and a status read.
270+
static const NSTimeInterval AgentDeviceTextEntryBurstBreakSeconds = 1.0;
271+
235272
- (void)agentDeviceTextEntryDidChange:(UITextField *)textField {
273+
// A field whose app owns its value, the way a controlled React Native `TextInput` does. A burst
274+
// typed faster than the app renders loses the characters that arrived while a render was in
275+
// flight, and the field settles stable short of the request.
276+
if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-text-entry-app-owned-value"]) {
277+
NSTimeInterval now = NSProcessInfo.processInfo.systemUptime;
278+
NSTimeInterval gap = now - self.textEntryLastEditTime;
279+
BOOL overtookARender = self.textEntryRenderedValue != nil && gap < self.textEntryAcknowledgeWindowSeconds;
280+
if (self.textEntryBurstEdits == 0 || gap > AgentDeviceTextEntryBurstBreakSeconds) {
281+
self.textEntryBurstStartTime = now;
282+
self.textEntryBurstEdits = 0;
283+
self.textEntryBurstMinGap = 0;
284+
} else if (self.textEntryBurstEdits == 1 || gap < self.textEntryBurstMinGap) {
285+
self.textEntryBurstMinGap = gap;
286+
}
287+
self.textEntryBurstEdits += 1;
288+
self.textEntryLastEditTime = now;
289+
if (overtookARender) {
290+
if (![textField.text isEqualToString:self.textEntryRenderedValue]) {
291+
textField.text = self.textEntryRenderedValue;
292+
self.textEntryWriteBacks += 1;
293+
}
294+
} else {
295+
self.textEntryRenderedValue = [textField.text copy];
296+
self.textEntryRenderedEdits += 1;
297+
}
298+
[self updateTextEntryWriteBackStatus];
299+
}
236300
if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-text-entry-disappear-after-input"] &&
237301
textField.text.length > 0) {
238302
[textField removeFromSuperview];
@@ -281,7 +345,13 @@ - (void)viewDidLoad {
281345
UITextField *textField = [[UITextField alloc] init];
282346
textField.accessibilityIdentifier = @"agent-device-hardware-keyboard-input";
283347
textField.borderStyle = UITextBorderStyleRoundedRect;
284-
textField.inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
348+
// An empty input view keeps the software keyboard down, which is the hardware-keyboard responder
349+
// these routes are addressed to. `--agent-device-text-entry-soft-keyboard` leaves the real input
350+
// view in place, so a lane test can reach the branch that requires a visible keyboard.
351+
if (![NSProcessInfo.processInfo.arguments
352+
containsObject:@"--agent-device-text-entry-soft-keyboard"]) {
353+
textField.inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
354+
}
285355
[textField addTarget:self
286356
action:@selector(agentDeviceTextEntryDidChange:)
287357
forControlEvents:UIControlEventEditingChanged];
@@ -293,6 +363,21 @@ - (void)viewDidLoad {
293363
[textField.widthAnchor constraintEqualToConstant:240],
294364
[textField.heightAnchor constraintEqualToConstant:44],
295365
]];
366+
if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-text-entry-app-owned-value"]) {
367+
self.textEntryAcknowledgeWindowSeconds = AgentDeviceTextEntryAcknowledgeWindow();
368+
// Reports how many edits this app rendered and how many writes it had to make because a
369+
// character overtook one, so a lane test can tell a burst the app kept up with from an inert
370+
// fixture. Counts only: no field content crosses into the test.
371+
self.textEntryWriteBackStatus = [[UILabel alloc] init];
372+
self.textEntryWriteBackStatus.accessibilityIdentifier = @"agent-device-text-entry-write-backs";
373+
self.textEntryWriteBackStatus.translatesAutoresizingMaskIntoConstraints = NO;
374+
[self.view addSubview:self.textEntryWriteBackStatus];
375+
[NSLayoutConstraint activateConstraints:@[
376+
[self.textEntryWriteBackStatus.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
377+
[self.textEntryWriteBackStatus.topAnchor constraintEqualToAnchor:textField.bottomAnchor constant:12],
378+
]];
379+
[self updateTextEntryWriteBackStatus];
380+
}
296381
}
297382

298383
if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-crowded-screen"]) {

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.h‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,19 @@ typedef NS_ENUM(NSInteger, RunnerSynthesizedTextEntryStatus) {
1717

1818
@interface RunnerSynthesizedTextEntry : NSObject
1919

20+
// Characters per second the synthesized text-input records are typed at. Declared here, where the
21+
// typing happens, so the delivery budget that bounds a burst is charged the same pace the app sees.
22+
// The edit-acknowledge window that pace is sized for is a separate assumption about the app
23+
// (TextEntryTiming.synthesizedAcknowledgeWindowSeconds), not a value derived from this one.
24+
+ (NSUInteger)typingSpeedCharactersPerSecond;
25+
2026
// Synthesizes keyboard input for the current first responder without resolving an
2127
// XCUIElement or serializing the application's accessibility tree.
2228
+ (RunnerSynthesizedTextEntryResult *)synthesizeTextWithApplication:(id)application
2329
text:(NSString *)text;
2430

25-
// Replaces the current first responder's contents using one synthesized
26-
// Command-A, Delete, and text-input event sequence.
31+
// Replaces the current first responder's contents with one synthesized Command-A record
32+
// followed by a text-input record, typed at the bounded pace declared in the implementation.
2733
+ (RunnerSynthesizedTextEntryResult *)replaceTextWithApplication:(id)application
2834
text:(NSString *)text;
2935

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.m‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,20 @@
55

66
static NSString *const RunnerTextSynthesisSurface = @"text";
77

8+
// XCTest's `typingSpeed:` argument is characters per second. At 60 the 11 characters of a `fill`
9+
// arrived at a fixture field across 131 ms (~13 ms per gap), which is faster than an app that owns
10+
// its field's value and re-applies it after the edit (a controlled React Native `TextInput`, an
11+
// async validator) can acknowledge: such a write lands between two characters of the burst and
12+
// erases what was typed while it was in flight, leaving a value that is stable short of the
13+
// request. 12 characters/second spaces them ~83 ms apart on average, which reduces that loss but
14+
// does not remove it: XCTest does not space the characters evenly, and two of them can reach the
15+
// app a few milliseconds apart. Against a fixture app that acknowledges each edit within 40 ms, 60
16+
// characters/second left 1 of 11 characters in 20 of 20 bursts, and this pace left 10 or 11. The
17+
// command refuses a field left short; back-pressure from the field (#2906) is what would prevent
18+
// it. The app-owned-value lane test pins the average spacing the app sees, and the delivery budget
19+
// in TextEntryTiming bounds what the pace costs a long text.
20+
static const NSUInteger RunnerTextEntryTypingSpeedCharactersPerSecond = 12;
21+
822
typedef id (*RunnerTextMsgSendInit)(id, SEL, NSString *);
923
typedef id (*RunnerTextMsgSendInitPath)(id, SEL);
1024
typedef void (*RunnerTextMsgSendType)(id, SEL, NSString *, NSTimeInterval, NSUInteger, BOOL);
@@ -51,6 +65,10 @@ @implementation RunnerSynthesizedTextEntryResult
5165

5266
@implementation RunnerSynthesizedTextEntry
5367

68+
+ (NSUInteger)typingSpeedCharactersPerSecond {
69+
return RunnerTextEntryTypingSpeedCharactersPerSecond;
70+
}
71+
5472
+ (RunnerSynthesizedTextEntryResult *)synthesizeTextWithApplication:(id)application
5573
text:(NSString *)text {
5674
return RunnerSynthesizeTextWithMode(application, text, NO);
@@ -128,7 +146,14 @@ + (RunnerSynthesizedTextEntryResult *)replaceTextWithApplication:(id)application
128146
);
129147
}
130148
((RunnerMsgSendSetInteger)objc_msgSend)(record, bridge.core.setTargetProcessIDSelector, targetProcessID);
131-
((RunnerTextMsgSendType)objc_msgSend)(path, bridge.typeTextSelector, text, 0.0, 60, YES);
149+
((RunnerTextMsgSendType)objc_msgSend)(
150+
path,
151+
bridge.typeTextSelector,
152+
text,
153+
0.0,
154+
RunnerTextEntryTypingSpeedCharactersPerSecond,
155+
YES
156+
);
132157
((RunnerMsgSendAddPath)objc_msgSend)(record, bridge.core.addPathSelector, path);
133158

134159
NSError *error = nil;

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ extension RunnerTests {
176176
}
177177
return try runMainThreadWork(
178178
"command_execution",
179-
timeout: mainThreadExecutionTimeout,
179+
timeout: Self.mainThreadExecutionTimeout,
180180
timeoutError: mainThreadExecutionTimeoutError
181181
) {
182182
try self.executeOnMainSafely(command: command, routeToSpringboard: routeToSpringboard)
@@ -279,7 +279,7 @@ extension RunnerTests {
279279
while true {
280280
let failureCountBefore = try runMainThreadWork(
281281
"recorded_failure_count",
282-
timeout: mainThreadExecutionTimeout,
282+
timeout: Self.mainThreadExecutionTimeout,
283283
timeoutError: mainThreadExecutionTimeoutError
284284
) {
285285
self.currentXCTestFailureCount()
@@ -296,7 +296,7 @@ extension RunnerTests {
296296
}
297297
let recordedFailureResponse = try runMainThreadWork(
298298
"recorded_failure_count",
299-
timeout: mainThreadExecutionTimeout,
299+
timeout: Self.mainThreadExecutionTimeout,
300300
timeoutError: mainThreadExecutionTimeoutError
301301
) {
302302
self.didRecordXCTestFailure(since: failureCountBefore)
@@ -306,7 +306,7 @@ extension RunnerTests {
306306
if let recordedFailureResponse {
307307
try runMainThreadWork(
308308
"target_invalidation",
309-
timeout: mainThreadExecutionTimeout,
309+
timeout: Self.mainThreadExecutionTimeout,
310310
timeoutError: mainThreadExecutionTimeoutError
311311
) {
312312
self.invalidateCachedTarget(reason: "xctest_recorded_failure")
@@ -321,7 +321,7 @@ extension RunnerTests {
321321
hasRetried = true
322322
try runMainThreadWork(
323323
"target_invalidation",
324-
timeout: mainThreadExecutionTimeout,
324+
timeout: Self.mainThreadExecutionTimeout,
325325
timeoutError: mainThreadExecutionTimeoutError
326326
) {
327327
self.invalidateCachedTarget(reason: "response_unavailable")

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotExecution.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ extension RunnerTests {
1111
private func executeSnapshotDispatchedOnce(command: Command) throws -> Response {
1212
let preparation: SnapshotCommandPreparation = try runMainThreadWork(
1313
"command_preparation",
14-
timeout: mainThreadExecutionTimeout,
14+
timeout: Self.mainThreadExecutionTimeout,
1515
timeoutError: mainThreadExecutionTimeoutError
1616
) { () -> SnapshotCommandPreparation in
1717
switch try self.prepareActiveCommandContextSafely(command: command, routeToSpringboard: false) {

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift‎

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,23 +82,97 @@ extension RunnerTests {
8282
text: String,
8383
delaySeconds: Double
8484
) -> [SynthesizedReplacementStep] {
85-
let characters = Array(text)
86-
guard delaySeconds > 0, characters.count > 1 else {
85+
guard synthesizedReplacementIsSpaced(characterCount: text.count, delaySeconds: delaySeconds)
86+
else {
8787
return [SynthesizedReplacementStep(text: text, replacesExistingText: true)]
8888
}
89-
return characters.enumerated().map { index, character in
89+
return Array(text).enumerated().map { index, character in
9090
SynthesizedReplacementStep(
9191
text: String(character),
9292
replacesExistingText: index == 0
9393
)
9494
}
9595
}
9696

97+
/// Whether a replacement is posted one character per synthesize call, `delaySeconds` apart,
98+
/// rather than as one burst.
99+
static func synthesizedReplacementIsSpaced(characterCount: Int, delaySeconds: Double) -> Bool {
100+
delaySeconds > 0 && characterCount > 1
101+
}
102+
103+
/// What a synthesized burst costs in wall clock, and the ceiling it has to fit inside before the
104+
/// first character is posted. `synthesizedReplacementSteps` decides how a text is posted; this
105+
/// decides whether the runner may start posting it at all.
106+
enum SynthesizedDeliveryBudget {
107+
/// Seconds between two characters of one synthesized burst.
108+
static var characterInterval: TimeInterval {
109+
1.0 / Double(RunnerSynthesizedTextEntry.typingSpeedCharactersPerSecond())
110+
}
111+
112+
/// Seconds the plan spends posting: each synthesize call types its characters at the pace and
113+
/// pays its overhead, a spaced plan sleeps `delaySeconds` between two calls, and a plan that
114+
/// peels one character as a warmup (`typeWarmup`) pays one more call and the wait before the
115+
/// rest is posted. That wait is one poll here because the caller that asks has no element to
116+
/// read the warmup character back from, so `waitForWarmupValue` has no value to wait for.
117+
static func projectedSeconds(
118+
textLength: Int,
119+
delaySeconds: TimeInterval,
120+
typeWarmup: Bool = false
121+
) -> TimeInterval {
122+
let spaced = synthesizedReplacementIsSpaced(characterCount: textLength, delaySeconds: delaySeconds)
123+
let warmupSplit = typeWarmup && textLength > 1 && !spaced
124+
let calls = spaced ? textLength : (warmupSplit ? 2 : 1)
125+
return Double(textLength) * characterInterval
126+
+ Double(calls) * TextEntryTiming.synthesizeCallOverhead
127+
+ Double(calls - 1) * delaySeconds
128+
+ (warmupSplit ? TextEntryTiming.pollInterval : 0)
129+
}
130+
131+
static func exceeds(
132+
textLength: Int,
133+
delaySeconds: TimeInterval,
134+
typeWarmup: Bool = false
135+
) -> Bool {
136+
projectedSeconds(textLength: textLength, delaySeconds: delaySeconds, typeWarmup: typeWarmup)
137+
> TextEntryTiming.synthesizedDeliveryCeiling
138+
}
139+
140+
/// Longest text `exceeds` admits at `delaySeconds`, which is what the refusal tells the caller.
141+
static func maxTextLength(delaySeconds: TimeInterval) -> Int {
142+
var length = 1
143+
while !exceeds(textLength: length + 1, delaySeconds: delaySeconds) {
144+
length += 1
145+
}
146+
return length
147+
}
148+
}
149+
97150
func runSynthesizedReplacementRoute(
98151
_ request: SynthesizedReplacementRequest
99152
) -> SynthesizedReplacementRouteOutcome {
100153
#if os(iOS)
101154
NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_ROUTE route=synthesized-first-responder-replacement")
155+
if SynthesizedDeliveryBudget.exceeds(
156+
textLength: request.text.count,
157+
delaySeconds: request.delaySeconds
158+
) {
159+
NSLog(
160+
"AGENT_DEVICE_RUNNER_TEXT_ENTRY_ROUTE route=synthesized-first-responder-replacement "
161+
+ "reason=delivery-budget-refused chars=%d budgetChars=%d",
162+
request.text.count,
163+
SynthesizedDeliveryBudget.maxTextLength(delaySeconds: request.delaySeconds)
164+
)
165+
return .completed(
166+
TextEntryResult(
167+
verified: nil,
168+
repaired: false,
169+
expectedText: request.text,
170+
observedText: nil,
171+
textEntryRoute: "synthesized-first-responder-replacement",
172+
failure: .synthesisBudgetExceeded
173+
)
174+
)
175+
}
102176
let steps = Self.synthesizedReplacementSteps(
103177
text: request.text,
104178
delaySeconds: request.delaySeconds

0 commit comments

Comments
 (0)