diff --git a/packages/capture-kit/src/ios-snapshot-engine/noise-overlay.test.ts b/packages/capture-kit/src/ios-snapshot-engine/noise-overlay.test.ts new file mode 100644 index 0000000000..fc9d9658db --- /dev/null +++ b/packages/capture-kit/src/ios-snapshot-engine/noise-overlay.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from 'vitest'; +import { attachRefs, type RawSnapshotNode } from '@agent-device/kernel/snapshot'; +import { buildIosInteractiveSnapshotPresentation } from './semantic-index.ts'; + +function buildSnapshotState(nodes: RawSnapshotNode[]) { + return attachRefs(buildIosInteractiveSnapshotPresentation(nodes).nodes); +} + +test('the wrapper pass collapses the full-screen parent of a count-badge warning banner', () => { + // From two entries up, the banner's label starts with the LogBox entry count instead of `!`, so + // the wrapper pass reads the banner by LogBox's placement rather than by its label. + const nodes: RawSnapshotNode[] = [ + { + index: 0, + depth: 0, + type: 'Application', + label: 'Agent Device Tester', + rect: { x: 0, y: 0, width: 402, height: 874 }, + }, + { + index: 1, + depth: 1, + parentIndex: 0, + type: 'Other', + label: '20, Failed to fetch', + rect: { x: 0, y: 0, width: 402, height: 874 }, + }, + { + index: 2, + depth: 2, + parentIndex: 1, + type: 'Other', + label: '20, Failed to fetch', + rect: { x: 10, y: 786.666, width: 382, height: 67.333 }, + }, + ]; + + expect( + buildSnapshotState(nodes).map((node) => [ + node.type, + node.label, + node.rect?.y, + node.parentIndex, + ]), + ).toEqual([ + ['Application', 'Agent Device Tester', 0, undefined], + ['Other', '20, Failed to fetch', 786.666, 0], + ]); +}); diff --git a/packages/capture-kit/src/react-native-overlay.test.ts b/packages/capture-kit/src/react-native-overlay.test.ts index 3b74f933ff..f2c54e4837 100644 --- a/packages/capture-kit/src/react-native-overlay.test.ts +++ b/packages/capture-kit/src/react-native-overlay.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from 'vitest'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import { snapshotViewportSizeFrom } from '@agent-device/kernel/rect'; import { analyzeReactNativeOverlay, formatReactNativeOverlayWarning, @@ -152,3 +153,197 @@ describe('React Native overlay evidence', () => { expect(analyzeReactNativeOverlay(nodes).detected).toBe(true); }); }); + +/** + * From two entries up, LogBox's badge renders the entry count instead of `!` + * (`LogBoxNotificationCountBadge`), so the banner's joined label starts with a number. App rows + * open the same way, which is why the count form arms only on LogBox's own banner placement. + */ +describe('React Native collapsed banner with the entry-count badge', () => { + const iosViewport = snapshotViewportSizeFrom({ x: 0, y: 0, width: 402, height: 874 }); + const androidViewport = snapshotViewportSizeFrom({ x: 0, y: 0, width: 1080, height: 2400 }); + /** LogBox's frame on a 402x874 surface: `left: 10; right: 10; bottom: 20`, notification 48 high. */ + const iosCountBannerRect = { x: 10, y: 806, width: 382, height: 48 }; + + test('a banner whose badge shows the entry count is an overlay and a dismiss target', () => { + const state = analyzeReactNativeOverlay( + [ + node({ + index: 0, + ref: 'e1', + label: '20, Failed to fetch', + rect: iosCountBannerRect, + hittable: true, + }), + ], + iosViewport, + ); + + expect(state.detected).toBe(true); + expect(state.primaryAction).toMatchObject({ + action: 'close-collapsed-banner', + ref: 'e1', + label: '20, Failed to fetch', + }); + }); + + test('a device-pixel count banner floating off the bottom edge is an overlay', () => { + // Android rects are physical pixels, so LogBox's 10 dp inset reads as 10 x density there: 26.25 + // px on this 420 dpi capture, and the 20 dp bottom gap as 52.5 px. + const state = analyzeReactNativeOverlay( + [ + node({ + index: 0, + ref: 'e1', + label: '8, Network request failed', + rect: { x: 26.25, y: 2213.25, width: 1027.5, height: 126 }, + hittable: true, + }), + ], + { width: 1080, height: 2400, rectUnitsPerDp: 2.625 }, + ); + + expect(state.detected).toBe(true); + }); + + test('a device-pixel count banner is not an overlay when the capture published no density', () => { + // Without the density, 26 px cannot be read as LogBox's 10 dp, and guessing one would arm on any + // inset card whose gap happens to measure ten pixels. + const state = analyzeReactNativeOverlay( + [ + node({ + index: 0, + ref: 'e1', + label: '8, Network request failed', + rect: { x: 26.25, y: 2213.25, width: 1027.5, height: 126 }, + hittable: true, + }), + ], + androidViewport, + ); + + expect(state.detected).toBe(false); + }); + + test('an ordinary row whose label starts with a number is not an overlay', () => { + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '2, Morning', + rect: { x: 0, y: 320, width: 402, height: 52 }, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, iosViewport).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, iosViewport)).toBe(undefined); + }); + + test('a tab bar row whose label starts with a number is not an overlay', () => { + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '3, Cart', + rect: { x: 202, y: 811, width: 200, height: 63 }, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, iosViewport).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, iosViewport)).toBe(undefined); + }); + + test('a full-width footer row flush with the bottom edge is not an overlay', () => { + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '2, Continue shopping', + rect: { x: 0, y: 822, width: 402, height: 52 }, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, iosViewport).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, iosViewport)).toBe(undefined); + }); + + test('a tablet-width count banner keeps the fixed LogBox side gap', () => { + // LogBox pins the banner 10 units from both edges whatever the surface: a 13" iPad Pro portrait + // window, an iPad in landscape, an unfolded foldable. + const iPadViewport = snapshotViewportSizeFrom({ x: 0, y: 0, width: 1032, height: 1376 }); + const state = analyzeReactNativeOverlay( + [ + node({ + index: 0, + ref: 'e1', + label: '7, Unable to load image', + rect: { x: 10, y: 1308, width: 1012, height: 48 }, + hittable: true, + }), + ], + iPadViewport, + ); + + expect(state.detected).toBe(true); + }); + + test('an inset card above the tab bar is not an overlay', () => { + // The card keeps 16pt side gaps, wider than LogBox's fixed 10, so only the banner's own gap + // width separates it from a count banner. + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '3, New messages', + rect: { x: 16, y: 719, width: 370, height: 72 }, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, iosViewport).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, iosViewport)).toBe(undefined); + }); + + test('an inset card on a landscape tablet is not an overlay', () => { + // The same 16pt card on a 1366x1024 surface: the gap stays 16 while the surface grows, and + // LogBox's own gap stays 10, so a card cannot reach the banner's placement by being wide. + const landscape = snapshotViewportSizeFrom({ x: 0, y: 0, width: 1366, height: 1024 }); + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '4, 3 messages failed to send', + rect: { x: 16, y: 900, width: 1334, height: 72 }, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, landscape).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, landscape)).toBe(undefined); + }); + + test('a price label is not an overlay', () => { + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '20,000원', + rect: iosCountBannerRect, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes, iosViewport).detected).toBe(false); + expect(formatReactNativeOverlayWarning(nodes, iosViewport)).toBe(undefined); + }); + + test('a count banner is not an overlay when the capture published no box', () => { + const nodes = [ + node({ + index: 0, + ref: 'e1', + label: '20, Failed to fetch', + rect: iosCountBannerRect, + hittable: true, + }), + ]; + expect(analyzeReactNativeOverlay(nodes).detected).toBe(false); + }); +}); diff --git a/packages/capture-kit/src/react-native-overlay.ts b/packages/capture-kit/src/react-native-overlay.ts index d4f9e08903..664105e29f 100644 --- a/packages/capture-kit/src/react-native-overlay.ts +++ b/packages/capture-kit/src/react-native-overlay.ts @@ -7,12 +7,16 @@ import { import { rectArea } from '@agent-device/kernel/rect'; import { isReactNativeCollapsedWarningBanner, + isReactNativeCollapsedWarningCountBadgeBanner, isReactNativeCollapsedWarningEvidenceLabel, isReactNativeCollapsedWarningLabel, isReactNativeOverlayDismissLabel, isReactNativeOverlayMinimizeLabel, } from '@agent-device/contracts/react-native-overlay'; -import type { ReactNativeOverlayNode } from '@agent-device/contracts/react-native-overlay'; +import type { + ReactNativeOverlayNode, + ReactNativeOverlaySurface, +} from '@agent-device/contracts/react-native-overlay'; export type ReactNativeOverlayState = { detected: boolean; @@ -35,6 +39,7 @@ type ReactNativeOverlayFacts = { dismissNodes: SnapshotNode[]; minimizeNodes: SnapshotNode[]; collapsedNodes: SnapshotNode[]; + collapsedCountBadgeNodes: SnapshotNode[]; detected: boolean; }; @@ -46,8 +51,11 @@ const REACT_NATIVE_STACK_FRAME_PATTERNS = [ ] as const; const CLOSE_ICON_LABELS = new Set(['x', '×', '✕', '✖', '⨯']); -export function formatReactNativeOverlayWarning(nodes: SnapshotNode[]): string | undefined { - const overlay = analyzeReactNativeOverlay(nodes); +export function formatReactNativeOverlayWarning( + nodes: SnapshotNode[], + surface?: ReactNativeOverlaySurface, +): string | undefined { + const overlay = analyzeReactNativeOverlay(nodes, surface); if (!overlay.detected) return undefined; return [ 'Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.', @@ -56,8 +64,11 @@ export function formatReactNativeOverlayWarning(nodes: SnapshotNode[]): string | ].join('\n'); } -export function analyzeReactNativeOverlay(nodes: SnapshotNode[]): ReactNativeOverlayState { - const facts = collectReactNativeOverlayFacts(nodes); +export function analyzeReactNativeOverlay( + nodes: SnapshotNode[], + surface?: ReactNativeOverlaySurface, +): ReactNativeOverlayState { + const facts = collectReactNativeOverlayFacts(nodes, surface); const primaryAction = facts.detected ? resolveSafeDismissAction(facts) : null; return { @@ -69,15 +80,14 @@ export function analyzeReactNativeOverlay(nodes: SnapshotNode[]): ReactNativeOve }; } -function collectReactNativeOverlayFacts(nodes: SnapshotNode[]): ReactNativeOverlayFacts { +function collectReactNativeOverlayFacts( + nodes: SnapshotNode[], + surface: ReactNativeOverlaySurface | undefined, +): ReactNativeOverlayFacts { const text = nodes.map(formatNodeSearchText).join('\n').toLowerCase(); const dismissNodes = collectOverlayNodes(nodes, isDismissControlLabel); const minimizeNodes = collectOverlayNodes(nodes, isReactNativeOverlayMinimizeLabel); - const collapsedNodes = collectOverlayNodes( - nodes, - isReactNativeCollapsedWarningLabel, - isLikelyCollapsedWarningControl, - ); + const collapsedNodes = nodes.filter((node) => node.ref && isCollapsedWarningNode(node, surface)); const openDebuggerWarningNodes = collectOverlayNodes( nodes, isReactNativeOpenDebuggerWarningLabel, @@ -85,25 +95,45 @@ function collectReactNativeOverlayFacts(nodes: SnapshotNode[]): ReactNativeOverl const hasReactNativeStackFrame = isReactNativeStackFrame(text); const hasControllessRedBoxText = hasUnableToDownloadAssetRedBox(text); const hasOverlayControl = hasReactNativeOverlayControlText(text, dismissNodes, minimizeNodes); + const collapsedCountBadgeNodes = collapsedNodes.filter((node) => + isReactNativeCollapsedWarningCountBadgeBanner(node, surface), + ); return { dismissNodes, minimizeNodes, collapsedNodes, + collapsedCountBadgeNodes, detected: isReactNativeOverlayDetected({ text, hasReactNativeStackFrame, hasOverlayControl, hasControllessRedBoxText, collapsedNodes, - collapsedEvidenceNodes: collectOverlayNodes( - collapsedNodes, - isReactNativeCollapsedWarningEvidenceLabel, + collapsedEvidenceNodes: collapsedNodes.filter((node) => + nodeHasMatchingLabel(node, isReactNativeCollapsedWarningEvidenceLabel), ), + collapsedCountBadgeNodes, openDebuggerWarningNodes, }), }; } +/** + * A banner candidate: either its label names a collapsed warning and its shape allows one, or it + * carries LogBox's entry-count badge in a LogBox banner's place. A count label alone reads like an + * ordinary row, so only the placement — measured in the capture's own box — says banner. + */ +function isCollapsedWarningNode( + node: SnapshotNode, + surface: ReactNativeOverlaySurface | undefined, +): boolean { + if (isReactNativeCollapsedWarningCountBadgeBanner(node, surface)) return true; + return ( + isLikelyCollapsedWarningControl(node) && + nodeHasMatchingLabel(node, isReactNativeCollapsedWarningLabel) + ); +} + function resolveSafeDismissAction( facts: ReactNativeOverlayFacts, ): ReactNativeOverlayDismissTarget | null { @@ -111,7 +141,7 @@ function resolveSafeDismissAction( if (dismiss) return targetFromNode(dismiss, actionFromDismissNode(dismiss)); const collapsed = chooseCollapsedWarningNode( - facts.collapsedNodes.filter(isSafeCollapsedWarningCoordinateFallback), + facts.collapsedNodes.filter((node) => isSafeCollapsedWarningCoordinateFallback(node, facts)), ); if (!collapsed?.rect) return null; return { @@ -156,12 +186,14 @@ function isReactNativeOverlayDetected(params: { hasControllessRedBoxText: boolean; collapsedNodes: SnapshotNode[]; collapsedEvidenceNodes: SnapshotNode[]; + collapsedCountBadgeNodes: SnapshotNode[]; openDebuggerWarningNodes: SnapshotNode[]; }): boolean { const hasOverlayContext = params.hasReactNativeStackFrame || hasKnownReactNativeOverlayText(params.text); return ( params.collapsedEvidenceNodes.length > 0 || + params.collapsedCountBadgeNodes.length > 0 || (params.collapsedNodes.length > 0 && hasOverlayContext) || params.openDebuggerWarningNodes.length > 0 || params.hasControllessRedBoxText || @@ -194,30 +226,32 @@ function isLikelyCollapsedWarningControl(node: SnapshotNode): boolean { return !node.rect || node.rect.height <= 180; } -function isSafeCollapsedWarningCoordinateFallback(node: SnapshotNode): boolean { +function isSafeCollapsedWarningCoordinateFallback( + node: SnapshotNode, + facts: ReactNativeOverlayFacts, +): boolean { + if (facts.collapsedCountBadgeNodes.includes(node)) return true; + if (!isReactNativeCollapsedWarningBanner(node)) return false; const label = readNodeLabel(node)?.trim().toLowerCase() ?? ''; - return ( - (isReactNativeOpenDebuggerWarningLabel(label) || isCollapsedWarningSummaryLabel(label)) && - isReactNativeCollapsedWarningBanner(node) - ); + return isReactNativeOpenDebuggerWarningLabel(label) || isCollapsedWarningSummaryLabel(label); +} + +/** Reads every text a node carries, lowercased, against a label classifier. */ +function nodeHasMatchingLabel( + node: ReactNativeOverlayNode, + matches: (label: string) => boolean, +): boolean { + return [node.label, node.value, node.identifier] + .map((value) => value?.trim().toLowerCase()) + .filter((value): value is string => Boolean(value)) + .some((value) => matches(value)); } function collectOverlayNodes( nodes: SnapshotNode[], matches: (label: string) => boolean, - includeNode: (node: SnapshotNode) => boolean = () => true, ): SnapshotNode[] { - const matchedNodes: SnapshotNode[] = []; - for (const node of nodes) { - if (!node.ref) continue; - if (!includeNode(node)) continue; - const labels = [node.label, node.value, node.identifier] - .map((value) => value?.trim().toLowerCase()) - .filter((value): value is string => Boolean(value)); - if (!labels.some((label) => matches(label))) continue; - matchedNodes.push(node); - } - return matchedNodes; + return nodes.filter((node) => node.ref && nodeHasMatchingLabel(node, matches)); } function firstControlNodeWithRect(nodes: SnapshotNode[]): SnapshotNode | null { diff --git a/packages/capture-kit/src/screenshot-overlay.ts b/packages/capture-kit/src/screenshot-overlay.ts index 306c43a037..748e30117e 100644 --- a/packages/capture-kit/src/screenshot-overlay.ts +++ b/packages/capture-kit/src/screenshot-overlay.ts @@ -13,6 +13,7 @@ import { resolveSnapshotBounds, } from './snapshot-rect-projection.ts'; import { analyzeReactNativeOverlay } from './react-native-overlay.ts'; +import { reactNativeOverlaySurfaceFromCapture } from '@agent-device/contracts/react-native-overlay'; import { buildSnapshotNodeMap, findSnapshotAncestor, @@ -134,7 +135,10 @@ function addReactNativeOverlayActionCandidates( screenshotWidth: number, screenshotHeight: number, ): void { - const overlay = analyzeReactNativeOverlay(snapshot.nodes); + const overlay = analyzeReactNativeOverlay( + snapshot.nodes, + reactNativeOverlaySurfaceFromCapture(snapshot), + ); const action = overlay.primaryAction; if (!action?.ref || !action.rect || !hasPositiveRect(action.rect)) return; diff --git a/packages/capture-kit/src/snapshot-state.ts b/packages/capture-kit/src/snapshot-state.ts index a03693b917..4094d2aa9d 100644 --- a/packages/capture-kit/src/snapshot-state.ts +++ b/packages/capture-kit/src/snapshot-state.ts @@ -6,6 +6,7 @@ import { attachSnapshotTextInputGeometry, snapshotCaptureAnnotationsFrom, publicSnapshotCaptureAnnotations, + type AndroidSnapshotBackendMetadata, } from '@agent-device/contracts/capture'; import { isAndroidInputMethodNode } from '@agent-device/contracts/android-input-ownership'; import { @@ -135,7 +136,7 @@ export function buildSnapshotState( ...(data.presentedSurface ? { presentedSurface: data.presentedSurface } : {}), ...(data.targetActivation ? { targetActivation: data.targetActivation } : {}), ...(data.keyboard ? { keyboard: data.keyboard } : {}), - ...snapshotStateGeometry(data), + ...snapshotStateGeometry(data, annotations), presentationKey: buildSnapshotPresentationKey(presentation), presentation, // Only broad Android snapshots become freshness baselines. If the user asked for a scoped @@ -147,13 +148,22 @@ export function buildSnapshotState( function snapshotStateGeometry( data: Readonly<{ viewport?: SnapshotViewportSize; captureScale?: SnapshotCaptureScale }>, -): Pick { + annotations: Readonly<{ androidSnapshot?: AndroidSnapshotBackendMetadata }>, +): Pick { return { ...(data.viewport ? { viewport: data.viewport } : {}), ...(data.captureScale ? { captureScale: data.captureScale } : {}), + ...(isUsableUnitScale(annotations.androidSnapshot?.pixelDensity) + ? { rectUnitsPerDp: annotations.androidSnapshot?.pixelDensity } + : {}), }; } +/** Only a real density read converts a dp constant; anything else leaves the rects in their own units. */ +function isUsableUnitScale(value: number | undefined): boolean { + return typeof value === 'number' && Number.isFinite(value) && value > 0; +} + /** * The hint a node carries when the rect it is published with has no area. That is not evidence * that the node is off screen, but nothing confirms that it is on screen either: a scroll view diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot.ts index 06d4cbd267..12e003e61b 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot.ts @@ -39,6 +39,7 @@ import { formatPostGestureOutcomeWarning } from '@agent-device/capture-kit/post- import { buildSnapshotVisibility } from '@agent-device/capture-kit/snapshot-visibility'; import { ANDROID_SYSTEM_SURFACE_DISCLOSURE } from '@agent-device/contracts/android-system-surface-disclosure'; import { formatReactNativeOverlayWarning } from '@agent-device/capture-kit/react-native-overlay'; +import { reactNativeOverlaySurfaceFromCapture } from '@agent-device/contracts/react-native-overlay'; import { now } from '../../runtime-common.ts'; import type { AuditSnapshotCommandOptions, @@ -343,7 +344,10 @@ function buildSnapshotWarnings(params: { warnings.push(...buildMergedAccessibilityLeafWarnings(params.snapshot.nodes)); } - const reactNativeOverlayWarning = formatReactNativeOverlayWarning(params.snapshot.nodes); + const reactNativeOverlayWarning = formatReactNativeOverlayWarning( + params.snapshot.nodes, + reactNativeOverlaySurfaceFromCapture(params.snapshot), + ); if (reactNativeOverlayWarning) warnings.push(reactNativeOverlayWarning); const systemSurfaceWarning = formatAndroidSystemSurfaceWarning(params.annotations); diff --git a/packages/contracts/src/react-native-overlay.ts b/packages/contracts/src/react-native-overlay.ts index 0d8373d8fb..fef8fbc318 100644 --- a/packages/contracts/src/react-native-overlay.ts +++ b/packages/contracts/src/react-native-overlay.ts @@ -1,17 +1,75 @@ -import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; +import type { RawSnapshotNode, Rect } from '@agent-device/kernel/snapshot'; export type ReactNativeOverlayNode = Pick< RawSnapshotNode, 'index' | 'type' | 'role' | 'subrole' | 'label' | 'value' | 'identifier' | 'rect' | 'hittable' >; +/** + * The box a banner rect is measured in: the capture's published viewport, or the full-screen + * container a banner sits inside. Absent means the reader holds no box, so a placement rule cannot + * run. + * + * `rectUnitsPerDp` says how many of the box's rect units make one density-independent pixel: 1 for a + * tree published in points (Apple), the display's density for one published in physical pixels + * (Android). Absent means 1, so a capture whose rects are already layout units needs no extra fact; + * a producer that publishes a bigger number is the only one that can shift a dp-written constant. + */ +export type ReactNativeOverlaySurface = Readonly<{ + width: number; + height: number; + rectUnitsPerDp?: number; +}>; + +/** The capture facts a placement rule measures against: the published box and the units it carries. */ +export type ReactNativeOverlayCaptureSurface = Readonly<{ + viewport?: Readonly<{ width: number; height: number }>; + rectUnitsPerDp?: number; +}>; + +/** + * The surface a capture offers a placement rule, or nothing when it published no box. Callers hand + * over the state they already hold, so the box and the units it is measured in travel together. + */ +export function reactNativeOverlaySurfaceFromCapture( + capture: ReactNativeOverlayCaptureSurface, +): ReactNativeOverlaySurface | undefined { + if (!capture.viewport) return undefined; + return { + width: capture.viewport.width, + height: capture.viewport.height, + ...(capture.rectUnitsPerDp === undefined ? {} : { rectUnitsPerDp: capture.rectUnitsPerDp }), + }; +} + /** App text such as "Error: invalid email" also starts this way, so it is not overlay evidence alone. */ const GENERIC_SEVERITY_PREFIX_PATTERN = /^(warn|warning|error):\s+/; +/** + * From two entries up, LogBox's badge renders the entry count instead of `!` + * (`LogBoxNotificationCountBadge`), and both platforms join the badge text with the message after + * `", "`, so a count banner reads `"20, Failed to fetch"`. Ordinary app rows open the same way, so + * the shape arms only on LogBox's own banner placement — see + * {@link isReactNativeCollapsedWarningCountBadgeBanner}. + */ +const COLLAPSED_COUNT_BADGE_PREFIX_PATTERN = /^(?:[2-9]|[1-9][0-9]+),\s+\S/; const COLLAPSED_WARNING_PREFIX_PATTERNS = [ /^!,\s+/, GENERIC_SEVERITY_PREFIX_PATTERN, /\b(?:possible\s+)?unhandled (?:promise )?rejection\b/, ] as const; +/** + * LogBox pins its banner stack with `left: 10; right: 10; bottom: 20` inside its own + * `LogBoxNotificationContainer`, and the notification row is 48 high. Those are dp constants, so the + * side gap reads as 10 rect units only where a unit is a dp; on a device-pixel capture it reads as + * 10 times the display's density. A banner's two side gaps are its own width, so they match each + * other; an inset app card sits further in, and a flush row — a tab bar, a footer, a bottom sheet — + * sits at 0 and is app chrome however it opens. The tolerance absorbs sub-pixel rounding in the tree. + */ +const COLLAPSED_BANNER_SIDE_INSET_DP = 10; +const COLLAPSED_BANNER_SIDE_INSET_TOLERANCE = 1; +/** LogBox anchors the stack 20 dp above the bottom edge, and the row is 48 dp, in any unit scale. */ +const COLLAPSED_BANNER_BOTTOM_FLOAT_MIN_DP = 12; +const COLLAPSED_BANNER_BOTTOM_FLOAT_MAX_DP = 160; const COLLAPSED_WARNING_TEXT_MARKERS = [ 'open debugger to view warnings', 'getsnapshot should be cached to avoid an infinite loop', @@ -24,8 +82,11 @@ const COLLAPSED_WARNING_TEXT_MARKERS = [ export function isReactNativeCollapsedWarningWrapperCandidate( node: ReactNativeOverlayNode, ): boolean { + const label = node.label?.trim(); return ( - isReactNativeCollapsedWarningLabel(node.label?.trim()) && isFullScreenOverlayRect(node.rect) + (isReactNativeCollapsedWarningLabel(label) || + isReactNativeCollapsedWarningCountBadgeLabel(label)) && + isFullScreenOverlayRect(node.rect) ); } @@ -35,9 +96,11 @@ export function isReactNativeCollapsedWarningWrapperWithVisibleBanner( ): boolean { const nodeLabel = node.label?.trim(); if (!nodeLabel || !isReactNativeCollapsedWarningWrapperCandidate(node)) return false; + const surface = reactNativeOverlaySurfaceFrom(node.rect); return descendants.some( (descendant) => - descendant.label?.trim() === nodeLabel && isReactNativeCollapsedWarningBanner(descendant), + descendant.label?.trim() === nodeLabel && + isReactNativeCollapsedWarningBannerNode(descendant, surface), ); } @@ -65,6 +128,46 @@ export function isReactNativeCollapsedWarningEvidenceLabel(rawLabel: string | un ); } +/** The `, ` shape a collapsed banner carries from two entries up. */ +function isReactNativeCollapsedWarningCountBadgeLabel(rawLabel: string | undefined): boolean { + const label = rawLabel?.trim().toLowerCase(); + if (!label) return false; + return COLLAPSED_COUNT_BADGE_PREFIX_PATTERN.test(label); +} + +/** + * A banner whose label carries the entry-count badge, proven by LogBox's own placement: it floats + * just inside the surface's sides and just above its bottom edge. Without a box to measure against, + * the placement cannot be read, so the answer is no. + */ +export function isReactNativeCollapsedWarningCountBadgeBanner( + node: ReactNativeOverlayNode, + surface: ReactNativeOverlaySurface | undefined, +): boolean { + if (!isReactNativeCollapsedWarningCountBadgeLabel(node.label)) return false; + if (!node.rect || !isReactNativeCollapsedWarningBanner(node)) return false; + return isCollapsedBannerAtLogBoxPlacement(node.rect, surface); +} + +/** A banner-sized node that either names itself as a collapsed warning or places like one. */ +function isReactNativeCollapsedWarningBannerNode( + node: ReactNativeOverlayNode, + surface: ReactNativeOverlaySurface | undefined, +): boolean { + if (!node.rect || !isReactNativeCollapsedWarningBanner(node)) return false; + return ( + isReactNativeCollapsedWarningLabel(node.label?.trim()) || + isReactNativeCollapsedWarningCountBadgeBanner(node, surface) + ); +} + +function reactNativeOverlaySurfaceFrom( + rect: Rect | undefined, +): ReactNativeOverlaySurface | undefined { + if (!rect) return undefined; + return { width: rect.width, height: rect.height }; +} + export function isReactNativeOverlayDismissLabel(label: string): boolean { return /^dismiss(?:\s*\([^)]*\))?$/i.test(label); } @@ -78,6 +181,31 @@ export function isReactNativeCollapsedWarningBanner(node: ReactNativeOverlayNode return node.rect.width >= 120 && node.rect.height >= 36 && node.rect.height <= 180; } +function isCollapsedBannerAtLogBoxPlacement( + rect: Rect, + surface: ReactNativeOverlaySurface | undefined, +): boolean { + if (!surface) return false; + const { width, height } = surface; + if (!(width > 0) || !(height > 0)) return false; + const unitsPerDp = surface.rectUnitsPerDp ?? 1; + const sideInset = COLLAPSED_BANNER_SIDE_INSET_DP * unitsPerDp; + const leftInset = rect.x; + const rightInset = width - (rect.x + rect.width); + const bottomFloat = (height - (rect.y + rect.height)) / unitsPerDp; + return ( + isCloseTo(leftInset, sideInset) && + isCloseTo(rightInset, sideInset) && + bottomFloat >= COLLAPSED_BANNER_BOTTOM_FLOAT_MIN_DP && + bottomFloat <= COLLAPSED_BANNER_BOTTOM_FLOAT_MAX_DP + ); +} + +/** True when a measured gap is the one LogBox renders, allow for sub-pixel rounding in the tree. */ +function isCloseTo(measured: number, expected: number): boolean { + return Math.abs(measured - expected) <= COLLAPSED_BANNER_SIDE_INSET_TOLERANCE; +} + function isFullScreenOverlayRect(rect: RawSnapshotNode['rect']): boolean { if (!rect) return false; return rect.x <= 1 && rect.y <= 1 && rect.width >= 300 && rect.height >= 600; diff --git a/packages/contracts/src/snapshot-model.ts b/packages/contracts/src/snapshot-model.ts index eb763d513c..c4877c0ef2 100644 --- a/packages/contracts/src/snapshot-model.ts +++ b/packages/contracts/src/snapshot-model.ts @@ -143,6 +143,14 @@ export type SnapshotState = { * producer's scale. See {@link SnapshotCaptureScale}. */ captureScale?: SnapshotCaptureScale; + /** + * Rect units per density-independent pixel of the surface these rects are measured in: 1 where the + * producer publishes points (Apple), the display's density where it publishes physical pixels + * (Android). A consumer that reads a layout constant written in dp — LogBox's 10-unit banner inset + * — can only check it on a device-pixel tree with this fact, so the state carries it beside + * `viewport`. Absent means the producer published nothing, which reads as 1. + */ + rectUnitsPerDp?: number; /** * iOS: this capture's own command found the session app out of foreground and the runner * activated it before answering, so an earlier observation in the session described whatever held diff --git a/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts b/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts index 429037400f..38c13f2182 100644 --- a/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts +++ b/packages/daemon/src/execution/handlers/__tests__/react-native.test.ts @@ -5,6 +5,7 @@ import { captureSnapshot } from '../../../core/snapshot-capture.ts'; import { SessionStore } from '../../../core/session-store.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { snapshotViewportSizeFrom } from '@agent-device/kernel/rect'; import { getRuntimeBindings, mockTapPoint, @@ -151,6 +152,69 @@ test('react-native dismiss-overlay prefers non-trailing collapsed warning close }); }); +test('react-native dismiss-overlay taps a collapsed banner whose badge shows the entry count', async () => { + const sessionName = 'rn-count-badge-session'; + const sessionStore = makeSessionStore(); + sessionStore.publish(sessionName, makeSession(sessionName)); + mockCaptureSnapshot + .mockResolvedValueOnce({ + snapshot: { + nodes: [ + { + index: 0, + ref: 'e90', + label: '20, Failed to fetch', + rect: { x: 10, y: 787, width: 382, height: 48 }, + hittable: true, + }, + ], + viewport: snapshotViewportSizeFrom({ x: 0, y: 0, width: 402, height: 874 }), + createdAt: Date.now(), + }, + }) + .mockResolvedValueOnce({ + snapshot: { + nodes: [ + { + index: 0, + ref: 'e1', + label: 'Submit order', + rect: { x: 24, y: 600, width: 180, height: 52 }, + }, + ], + createdAt: Date.now(), + }, + }); + + const response = await handleReactNativeCommands({ + createCommandSurface: fakeCreateCommandSurface, + req: { + token: 't', + session: sessionName, + command: 'react-native', + positionals: ['dismiss-overlay'], + flags: {}, + }, + sessionName, + logPath: '/tmp/daemon.log', + sessionStore, + contextFromFlags: () => ({}), + ...getRuntimeBindings(), + }); + + expect(response?.ok).toBe(true); + expect(mockDismissTap).toHaveBeenCalledWith( + expect.objectContaining({ point: { x: 370, y: 811 } }), + ); + expect(response?.ok && response.data).toMatchObject({ + action: 'dismiss-overlay', + overlayAction: 'close-collapsed-banner', + verified: true, + x: 370, + y: 811, + }); +}); + test('react-native dismiss-overlay does not confuse app dismiss buttons with overlay controls', async () => { const sessionName = 'rn-collapsed-with-app-dismiss-session'; const sessionStore = makeSessionStore(); diff --git a/packages/daemon/src/execution/handlers/react-native.ts b/packages/daemon/src/execution/handlers/react-native.ts index f6771edc0a..d88fe29d19 100644 --- a/packages/daemon/src/execution/handlers/react-native.ts +++ b/packages/daemon/src/execution/handlers/react-native.ts @@ -9,6 +9,7 @@ import { analyzeReactNativeOverlay, type ReactNativeOverlayDismissTarget, } from '@agent-device/capture-kit/react-native-overlay'; +import { reactNativeOverlaySurfaceFromCapture } from '@agent-device/contracts/react-native-overlay'; import { normalizeError } from '@agent-device/kernel/errors'; import { stripUndefined } from '@agent-device/kernel/record'; import { successText } from '@agent-device/kernel/success-text'; @@ -75,7 +76,10 @@ export async function handleReactNativeCommands( if (isSparseSnapshotQualityVerdict(snapshot.snapshotQuality)) { return responseForSparseReactNativeOverlaySnapshot(snapshot.snapshotQuality); } - const overlay = analyzeReactNativeOverlay(snapshot.nodes); + const overlay = analyzeReactNativeOverlay( + snapshot.nodes, + reactNativeOverlaySurfaceFromCapture(snapshot), + ); const target = overlay.primaryAction; if (!target) { return responseForMissingReactNativeOverlayTarget(overlay.detected); @@ -217,7 +221,10 @@ async function verifyReactNativeOverlayDismissal(params: InteractionRouteInput): nextCommand: 'agent-device screenshot', }; } - const overlay = analyzeReactNativeOverlay(verificationSnapshot.nodes); + const overlay = analyzeReactNativeOverlay( + verificationSnapshot.nodes, + reactNativeOverlaySurfaceFromCapture(verificationSnapshot), + ); if (!overlay.detected) { return { verified: true,