Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apple/snapshot-bridge/SnapshotBridgeCapture.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

NS_ASSUME_NONNULL_BEGIN

/// Native levels one request reads at most; deeper levels arrive through continuations.
Comment thread
thymikee marked this conversation as resolved.
Resolved
extern const NSUInteger kMaximumRequestLevels;
/// Requests one acquisition may issue before it fails as continuation-budget-exhausted.
extern const NSUInteger kMaximumRequestsPerCapture;

typedef id _Nullable (^SnapshotElementReader)(id element, NSUInteger depth, NSUInteger nodes, NSError **error);

/// Native request accounting for one acquisition: requests issued, requests the accessibility
Expand Down
8 changes: 4 additions & 4 deletions apple/snapshot-bridge/SnapshotBridgeCapture.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
// trees the AX server rejects a request that would return more than about 62 levels (measured on
// iOS 26.5), so there the first request is rejected once and the halving ladder settles at 32,
// which the host then sends as a depth hint.
static const NSUInteger maximumRequestLevels = 65;
const NSUInteger kMaximumRequestLevels = 65;
// Sized for the daemon's default depth bound (128 levels). Each root-to-leaf path needs one
// continuation per accepted-depth window, so the budget scales with the depth it must cover.
static const NSUInteger maximumRequests = 64;
const NSUInteger kMaximumRequestsPerCapture = 64;

@interface SnapshotTreeCapture : NSObject
@property(nonatomic, copy) SnapshotElementReader reader;
Expand All @@ -31,7 +31,7 @@ - (nullable NSDictionary *)read:(id)element depth:(NSUInteger)depth error:(NSErr
{
NSUInteger attemptDepth = MIN(depth, self.acceptedDepth);
for (NSUInteger retries = 0;; retries++) {
if (self.requests >= maximumRequests) {
if (self.requests >= kMaximumRequestsPerCapture) {
if (error) *error = [NSError errorWithDomain:@"agent-device.snapshot" code:1
userInfo:@{NSLocalizedDescriptionKey: @"snapshot continuation request budget exhausted"}];
return nil;
Expand Down Expand Up @@ -130,7 +130,7 @@ - (nullable NSDictionary *)materialize:(NSDictionary *)tree depth:(NSUInteger)de
{
SnapshotTreeCapture *capture = [SnapshotTreeCapture new];
capture.reader = reader;
NSUInteger firstRequestLevels = nativeLevelsHint > 0 ? MIN(nativeLevelsHint, maximumRequestLevels) : maximumRequestLevels;
NSUInteger firstRequestLevels = nativeLevelsHint > 0 ? MIN(nativeLevelsHint, kMaximumRequestLevels) : kMaximumRequestLevels;
capture.acceptedDepth = MIN(maxDepth + 1, firstRequestLevels);
capture.remainingNodes = maxNodes;
capture.maximumNodes = maxNodes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ int main(int argc, const char *argv[])
NSString *scenario = @(argv[1]);
if ([scenario isEqual:@"identity"] || [scenario isEqual:@"request-budget"] || [scenario hasPrefix:@"api-depth-"]) {
BOOL budget = [scenario isEqual:@"request-budget"];
NSUInteger depth = [scenario hasPrefix:@"api-depth-"] ? [[scenario substringFromIndex:10] integerValue] : 64;
NSUInteger depth = [scenario hasPrefix:@"api-depth-"] ? [[scenario substringFromIndex:10] integerValue] : kMaximumRequestLevels - 1;
NSMutableArray *children = [NSMutableArray array];
for (NSUInteger i = 0; i < (budget ? 80 : 2); i++) {
[children addObject:@{@"UIAccessibilitySnapshotKeyAttributes": @{}, @"UIAccessibilitySnapshotKeyChildren": @[],
Expand All @@ -165,7 +165,7 @@ int main(int argc, const char *argv[])
requests++;
if ([scenario hasPrefix:@"api-depth-"]) {
NSUInteger start = [element isKindOfClass:NSNumber.class] ? [element unsignedIntegerValue] : 0;
require(levels == MIN(depth + 1 - start, 65), @"native levels must include the root exactly once, at most 65 per request");
require(levels == MIN(depth + 1 - start, kMaximumRequestLevels), [NSString stringWithFormat:@"native levels must include the root exactly once, at most %lu per request", (unsigned long)kMaximumRequestLevels]);
NSUInteger end = MIN(start + levels, depth + 1);
NSDictionary *tree = nil;
for (NSUInteger level = end; level-- > start;) tree = @{@"UIAccessibilitySnapshotKeyAttributes": @{}, @"UIAccessibilitySnapshotKeyElement": @(level), @"UIAccessibilitySnapshotKeyChildrenCount": [scenario isEqual:@"api-depth-unknown"] ? [NSNull null] : @(level < depth ? 1 : 0), @"UIAccessibilitySnapshotKeyChildren": tree ? @[tree] : @[]};
Expand All @@ -174,12 +174,13 @@ int main(int argc, const char *argv[])
if ([element isEqual:@"root"]) return root;
return @{@"UIAccessibilitySnapshotKeyAttributes": @{}, @"UIAccessibilitySnapshotKeyChildren": @[@{@"UIAccessibilitySnapshotKeyAttributes": @{}, @"UIAccessibilitySnapshotKeyChildren": @[]}]};
}, &truncated, NULL, &failure);
if (budget) require(!result && failure.code == 1 && requests == 64, @"request budget must fail without publishing partial content");
if (budget) require(!result && failure.code == 1 && requests == kMaximumRequestsPerCapture, @"request budget must fail without publishing partial content");
else if ([scenario isEqual:@"identity"]) require(result == root && requests == 1, @"healthy capture must reuse the native tree");
else {
NSUInteger count = 0;
for (NSDictionary *node = result; node; node = [node[@"UIAccessibilitySnapshotKeyChildren"] firstObject]) count++;
require(count == depth + 1 && truncated == [scenario isEqual:@"api-depth-unknown"] && requests == (depth + 1 > 65 ? 2 : 1), @"every requested depth must include root plus permitted descendants");
// Each continuation re-reads its root, so one request adds at most kMaximumRequestLevels - 1 edges.
require(count == depth + 1 && truncated == [scenario isEqual:@"api-depth-unknown"] && requests == MAX(1, (depth + kMaximumRequestLevels - 2) / (kMaximumRequestLevels - 1)), @"every requested depth must include root plus permitted descendants");
}
return 0;
}
Expand All @@ -193,7 +194,7 @@ int main(int argc, const char *argv[])
NSString *expectedCode = nil;
NSUInteger expectedCaptures = 0;
if ([scenario isEqual:@"runtime-budget"]) {
expectedCaptures = 64;
expectedCaptures = kMaximumRequestsPerCapture;
expectedCode = @"continuation-budget-exhausted";
} else if ([scenario hasPrefix:@"wide-"] || [scenario isEqual:@"zero-depth"]) {
expectedCaptures = [scenario isEqual:@"wide-continuation"] ? 2 : 1;
Expand Down
46 changes: 46 additions & 0 deletions packages/platform-apple/src/snapshot-source/limits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { test } from 'vitest';
import { MAXIMUM_REQUEST_LEVELS, resolveSnapshotSourceLimits } from './limits.ts';
import type { SnapshotSourceLimits } from './types.ts';

// The host and the native bridge share these bounds only through source, so this guard reads
// each native literal and fails if either side drifts.
const nativeSource = (
await Promise.all(
['SnapshotBridgeRuntime.m', 'SnapshotBridgeCapture.m'].map((fileName) =>
readFile(
path.join(import.meta.dirname, '../../../../apple/snapshot-bridge', fileName),
'utf8',
),
),
)
).join('\n');

function nativeConstant(name: string): number {
const match = new RegExp(
`^const (?:NSUInteger|uint32_t) ${name} = (\\d+(?: \\* \\d+)*);$`,
'm',
).exec(nativeSource);
const value = match?.[1];
assert.ok(value, `the native bridge no longer declares ${name}`);
return value.split(' * ').reduce((product, factor) => product * Number(factor), 1);
}

test('the first-request window matches the native bridge', () => {
assert.equal(MAXIMUM_REQUEST_LEVELS, nativeConstant('kMaximumRequestLevels'));
});

test.each([
['maxResponseBytes', 'kMaximumFrameBytes'],
['maxTraversalDepth', 'kMaximumDepth'],
['maxNodes', 'kMaximumNodes'],
['maxDurationMs', 'kMaximumDurationMs'],
] as const)('%s accepts the native %s and rejects one more', (limit, native) => {
const bound = nativeConstant(native);
const resolve = (value: number) =>
resolveSnapshotSourceLimits({ [limit]: value } satisfies Partial<SnapshotSourceLimits>);
assert.equal(resolve(bound)[limit], bound);
assert.throws(() => resolve(bound + 1), { code: 'INVALID_ARGS' });
});
2 changes: 1 addition & 1 deletion packages/platform-apple/src/snapshot-source/limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const MAXIMUM_FRAME_BYTES = 16 * 1024 * 1024;
const MAXIMUM_DURATION_MS = 120_000;
// Mirrors the native bridge's kMaximumDepth.
const MAXIMUM_DEPTH = 128;
// Mirrors the native bridge's maximumRequestLevels: one native request reads at most this many
// Mirrors the native bridge's kMaximumRequestLevels: one native request reads at most this many
// levels, and deeper levels arrive through continuations.
export const MAXIMUM_REQUEST_LEVELS = 65;
const MAXIMUM_NODES = 10_000;
Expand Down
Loading