diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java index e640ef1b99a..b380b240515 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java @@ -62,10 +62,13 @@ private static Result captureOnce(UiAutomation automation, int maxDepth, int max ? null : stats.activeWindowMetadata.withIndex(windowCount); if (root != null + && AccessibilityTreeXml.remainingDocumentChars(xml) + > AccessibilityTreeXml.NODE_SUFFIX_RESERVE_CHARS && AccessibilityCaptureStabilizer.canAppendActiveWindowFallback( windowCount, fallbackMetadata != null)) { AccessibilityTreeXml.appendNode( - xml, root, windowCount, 0, maxDepth, maxNodes, stats, fallbackMetadata); + xml, root, windowCount, 0, maxDepth, maxNodes, stats, fallbackMetadata, + xml.length() + AccessibilityTreeXml.remainingDocumentChars(xml)); windowCount += 1; stats.activeWindowRootMissing = false; } @@ -191,7 +194,9 @@ private static int appendInteractiveWindowRoots( } int windowCount = 0; for (int index = 0; index < windows.size(); index += 1) { - if (stats.nodeCount >= maxNodes) { + if (stats.nodeCount >= maxNodes + || AccessibilityTreeXml.remainingDocumentChars(xml) + <= AccessibilityTreeXml.NODE_SUFFIX_RESERVE_CHARS) { stats.truncated = true; break; } @@ -222,7 +227,8 @@ private static int appendInteractiveWindowRoots( maxDepth, maxNodes, windowStats, - windowMetadata); + windowMetadata, + AccessibilityTreeXml.remainingDocumentChars(xml)); xml.append(windowXml); stats.copyFrom(windowStats); windowCount += 1; diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java index 9b0a5583016..5556ffad784 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java @@ -12,8 +12,17 @@ /** Serializes accessibility nodes using the helper's host-consumed XML contract. */ final class AccessibilityTreeXml { + static final int MAX_XML_CHARS = 8 * 1024 * 1024; + private static final int MAX_APP_ATTRIBUTE_CHARS = 64 * 1024; + private static final int MAX_TEXT_ATTRIBUTE_CHARS = 6 * 64 * 1024; + static final int NODE_SUFFIX_RESERVE_CHARS = 8 * MAX_APP_ATTRIBUTE_CHARS + 4096; + private AccessibilityTreeXml() {} + static int remainingDocumentChars(StringBuilder document) { + return MAX_XML_CHARS - document.length() - "".length(); + } + @SuppressWarnings("deprecation") static void appendNode( StringBuilder xml, @@ -23,8 +32,10 @@ static void appendNode( int maxDepth, int maxNodes, Stats stats, - WindowMetadata windowMetadata) { - if (stats.nodeCount >= maxNodes) { + WindowMetadata windowMetadata, + int maxXmlChars) { + if (stats.nodeCount >= maxNodes + || xml.length() + NODE_SUFFIX_RESERVE_CHARS >= maxXmlChars) { stats.truncated = true; return; } @@ -39,7 +50,7 @@ static void appendNode( } CharSequence text = node.getText(); if (text != null) { - appendAttribute(xml, "text", text); + appendTextAttribute(xml, text, stats, maxXmlChars - NODE_SUFFIX_RESERVE_CHARS); } // getText() returns the HINT for an empty field on modern Android, so `text` alone cannot // distinguish a cleared field from one whose value equals its hint; only this flag can @@ -48,18 +59,30 @@ static void appendNode( appendAttribute(xml, "hint-showing", Boolean.toString(node.isShowingHintText())); // The hint itself, whether or not the field is showing it: `text` holds the hint only while // the field is empty, so a filled field's placeholder is readable nowhere else. - appendNonEmptyAttribute(xml, "hint", node.getHintText()); + appendAppAttribute( + xml, "hint", node.getHintText(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); } appendAttribute(xml, "editable", Boolean.toString(node.isEditable())); // Accessibility selection offsets, not a measurement of the value's length. Read-only // selectable text exposes a selection too, so they do not depend on `editable`; -1 = unavailable. appendNonNegativeAttribute(xml, "selection-start", node.getTextSelectionStart()); appendNonNegativeAttribute(xml, "selection-end", node.getTextSelectionEnd()); - appendNonEmptyAttribute(xml, "resource-id", node.getViewIdResourceName()); - appendAttribute(xml, "class", node.getClassName()); - appendNonEmptyAttribute(xml, "package", node.getPackageName()); - appendNonEmptyAttribute(xml, "content-desc", node.getContentDescription()); - appendNonEmptyAttribute(xml, "role-description", roleDescription(node)); + appendAppAttribute( + xml, "resource-id", node.getViewIdResourceName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "class", node.getClassName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "package", node.getPackageName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "content-desc", node.getContentDescription(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "role-description", roleDescription(node), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendTrueAttribute(xml, "heading", isHeading(node)); appendAttribute(xml, "visible-to-user", Boolean.toString(node.isVisibleToUser())); appendDrawingOrderAttribute(xml, node); @@ -95,7 +118,7 @@ static void appendNode( } appendAttribute(xml, "password", Boolean.toString(node.isPassword())); appendBoundsAttribute(xml, "bounds", bounds.left, bounds.top, bounds.right, bounds.bottom); - appendScreenReaderFacts(xml, node, stats); + appendScreenReaderFacts(xml, node, stats, maxXmlChars - NODE_SUFFIX_RESERVE_CHARS); int childCount = depth >= maxDepth ? 0 : node.getChildCount(); if (depth >= maxDepth && node.getChildCount() > 0) { @@ -108,7 +131,8 @@ static void appendNode( xml.append(">"); int index = 0; - while (index < childCount && stats.nodeCount < maxNodes) { + while (index < childCount && stats.nodeCount < maxNodes + && xml.length() + NODE_SUFFIX_RESERVE_CHARS < maxXmlChars) { int count = Math.min( AccessibilityReadBatch.MAX_READS, Math.min(childCount - index, maxNodes - stats.nodeCount)); int offset = 0; @@ -116,10 +140,13 @@ static void appendNode( new AccessibilityReadBatch<>( index, count, childIndex -> AccessibilityNodeReads.child(node, childIndex), AccessibilityNodeInfo::recycle)) { - for (; offset < count && stats.nodeCount < maxNodes; offset += 1) { + for (; offset < count && stats.nodeCount < maxNodes + && xml.length() + NODE_SUFFIX_RESERVE_CHARS < maxXmlChars; offset += 1) { AccessibilityNodeInfo child = children.get(offset); if (child != null) { - appendNode(xml, child, index + offset, depth + 1, maxDepth, maxNodes, stats, null); + appendNode( + xml, child, index + offset, depth + 1, maxDepth, maxNodes, stats, null, + maxXmlChars); } } } @@ -168,6 +195,58 @@ private static void appendNonEmptyAttribute( appendAttribute(xml, name, value); } + static void appendAppAttribute( + StringBuilder xml, String name, CharSequence value, Stats stats) { + appendAppAttribute(xml, name, value, stats, MAX_XML_CHARS, MAX_APP_ATTRIBUTE_CHARS); + } + + static void appendTextAttribute( + StringBuilder xml, CharSequence value, Stats stats, int maxXmlChars) { + appendAppAttribute(xml, "text", value, stats, maxXmlChars, MAX_TEXT_ATTRIBUTE_CHARS); + } + + private static void appendAppAttribute( + StringBuilder xml, + String name, + CharSequence value, + Stats stats, + int maxXmlChars, int maxAttributeChars) { + if (value == null || value.length() == 0) return; + String prefix = " " + name + "=\""; + int escapedBudget = + Math.min(maxAttributeChars, maxXmlChars - xml.length() - prefix.length() - 1); + if (escapedBudget <= 0) { + stats.truncated = true; + return; + } + xml.append(prefix); + int attributeStart = xml.length() - prefix.length(); + int valueStart = xml.length(); + int consumed = appendEscaped(xml, value, escapedBudget); + String clippedMarker = " " + name + "-clipped=\"true\""; + if (consumed < value.length() + && escapedBudget < maxAttributeChars + && escapedBudget >= clippedMarker.length()) { + xml.setLength(valueStart); + consumed = appendEscaped(xml, value, escapedBudget - clippedMarker.length()); + } + xml.append('"'); + if (consumed < value.length()) { + if (!name.equals("text")) { + xml.setLength(attributeStart); + stats.truncated = true; + return; + } + boolean markerFits = xml.length() + clippedMarker.length() <= maxXmlChars; + if (markerFits) { + xml.append(clippedMarker); + } else { + xml.setLength(attributeStart); + } + if (escapedBudget < maxAttributeChars || !markerFits) stats.truncated = true; + } + } + private static void appendNonNegativeAttribute(StringBuilder xml, String name, int value) { if (value >= 0) { appendAttribute(xml, name, Integer.toString(value)); @@ -230,7 +309,7 @@ static void appendLongClickableAttribute(StringBuilder xml, boolean longClickabl // its focus rules read. `checked` above already marks a checkable node. @SuppressWarnings("deprecation") private static void appendScreenReaderFacts( - StringBuilder xml, AccessibilityNodeInfo node, Stats stats) { + StringBuilder xml, AccessibilityNodeInfo node, Stats stats, int maxXmlChars) { appendTraversalLink(xml, "traversal-before", node.getTraversalBefore(), stats); appendTraversalLink(xml, "traversal-after", node.getTraversalAfter(), stats); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { @@ -242,7 +321,9 @@ private static void appendScreenReaderFacts( appendTrueAttribute( xml, "focus-action", hasAccessibilityAction(node, AccessibilityAction.ACTION_FOCUS)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - appendNonEmptyAttribute(xml, "state-description", node.getStateDescription()); + appendAppAttribute( + xml, "state-description", node.getStateDescription(), stats, maxXmlChars, + MAX_APP_ATTRIBUTE_CHARS); } appendTrueAttribute(xml, "collection", node.getCollectionInfo() != null); appendTrueAttribute(xml, "range", node.getRangeInfo() != null); @@ -270,38 +351,57 @@ private static boolean hasAccessibilityAction( } private static void appendEscaped(StringBuilder xml, String value) { + appendEscaped(xml, value, Integer.MAX_VALUE); + } + + private static int appendEscaped(StringBuilder xml, CharSequence value, int maxChars) { + int appendedChars = 0; for (int index = 0; index < value.length(); index += 1) { char character = value.charAt(index); + String escaped; switch (character) { case '&': - xml.append("&"); + escaped = "&"; break; case '<': - xml.append("<"); + escaped = "<"; break; case '>': - xml.append(">"); + escaped = ">"; break; case '"': - xml.append("""); + escaped = """; break; case '\'': - xml.append("'"); + escaped = "'"; break; case '\n': - xml.append(" "); + escaped = " "; break; case '\r': - xml.append(" "); + escaped = " "; break; case '\t': - xml.append(" "); + escaped = " "; break; default: - xml.append(character); - break; + int sourceChars = + Character.isHighSurrogate(character) + && index + 1 < value.length() + && Character.isLowSurrogate(value.charAt(index + 1)) + ? 2 + : 1; + if (appendedChars + sourceChars > maxChars) return index; + xml.append(value, index, index + sourceChars); + appendedChars += sourceChars; + index += sourceChars - 1; + continue; } + if (appendedChars + escaped.length() > maxChars) return index; + xml.append(escaped); + appendedChars += escaped.length(); } + return value.length(); } static final class Stats { diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index 8aec97b2cf2..05e01e20823 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -10,6 +10,83 @@ static void run() { " window-bounds=\"[-2147483648,-1][0,2147483647]\""); assertLongClickable(true, " long-clickable=\"true\""); assertLongClickable(false, " long-clickable=\"false\""); + assertAppAttributeBoundsEscapedOutput(); + assertClippedDescriptionIsOmitted(); + assertTextAttributeAdmitsMaximumFill(); + assertDocumentLimitedTextMarksClip(); + assertUnmarkedPartialTextIsOmitted(); + assertWindowBudgetUsesDocumentLength(); + } + + private static void assertAppAttributeBoundsEscapedOutput() { + StringBuilder value = new StringBuilder(); + for (int index = 0; index < 64 * 1024; index += 1) value.append('&'); + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendAppAttribute(xml, "text", value, stats); + if (xml.length() > 64 * 1024 + " text=\"\" text-clipped=\"true\"".length()) { + throw new AssertionError("Escaped app attribute exceeded its serialized limit"); + } + if (stats.truncated || !xml.toString().endsWith(" text-clipped=\"true\"")) { + throw new AssertionError("Clipped value must stay distinct from missing nodes and stay well formed"); + } + } + + private static void assertClippedDescriptionIsOmitted() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendAppAttribute(xml, "content-desc", "x".repeat(70 * 1024), stats); + if (!stats.truncated || xml.length() != 0) { + throw new AssertionError("Clipped descriptions must not look complete to the host"); + } + } + + private static void assertTextAttributeAdmitsMaximumFill() { + StringBuilder value = new StringBuilder(); + for (int index = 0; index < 64 * 1024; index += 1) value.append('"'); + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, value, stats, AccessibilityTreeXml.MAX_XML_CHARS); + if (stats.truncated || xml.indexOf("text-clipped") >= 0 + || xml.length() != " text=\"\"".length() + 6 * 64 * 1024) { + throw new AssertionError("Maximum admitted fill text must remain complete after XML escaping"); + } + } + + private static void assertWindowBudgetUsesDocumentLength() { + StringBuilder document = new StringBuilder(""); + int fillerChars = AccessibilityTreeXml.MAX_XML_CHARS + - document.length() - "".length() - 16; + document.append("x".repeat(fillerChars)); + if (AccessibilityTreeXml.remainingDocumentChars(document) != 16) { + throw new AssertionError("Document setup must leave 16 remaining chars"); + } + StringBuilder nextWindow = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute( + nextWindow, "&".repeat(64), stats, AccessibilityTreeXml.remainingDocumentChars(document)); + if (!stats.truncated || nextWindow.length() > 16) { + throw new AssertionError("A second window must use only the document's remaining characters"); + } + } + + private static void assertDocumentLimitedTextMarksClip() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, "x".repeat(70 * 1024), stats, 64 * 1024); + if (!stats.truncated || !xml.toString().endsWith(" text-clipped=\"true\"") + || xml.length() > 64 * 1024) { + throw new AssertionError("Document-limited text must report its clip within the document budget"); + } + } + + private static void assertUnmarkedPartialTextIsOmitted() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, "abcdef", stats, 10); + if (!stats.truncated || xml.length() != 0) { + throw new AssertionError("Partial text without room for a clip marker must be omitted"); + } } private static void assertLongClickable(boolean longClickable, String expected) { diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts index d937b6db39a..9fac7cdb097 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts @@ -76,6 +76,7 @@ test.each>([ { identifier: 'create' }, { contentDescription: 'Create a draft' }, { text: '' }, + { textClipped: true }, { enabled: false }, { selected: true }, { checked: true }, diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts index b98fefae212..5d79f51041c 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts @@ -120,6 +120,7 @@ const PRESENTATION_SCALAR_FIELDS = { value: true, contentDescription: true, text: true, + textClipped: true, identifier: true, enabled: true, editable: true, diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index bc88d209637..dd519808354 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -652,6 +652,8 @@ const getCommandFacet = defineCommandFacet({ text: { summary: 'Read element text or attributes', searchHint: 'value label', + cliDetail: + 'On Android, get text refuses a clipped field value with reason android_text_clipped when the live read cannot provide complete text. The snapshot can still be complete; inspect textClipped on the node.', }, metadata: metadata('get'), run: (client, input) => client.interactions.get(toGetOptions(input)), diff --git a/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts b/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts index 492ad368548..bf95b17f6e7 100644 --- a/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts @@ -7,6 +7,12 @@ import { } from '@agent-device/contracts/element-text-runtime'; import { readTextForNode } from '../selector-text-runtime.ts'; +const diagnostic = vi.hoisted(() => ({ emitDiagnostic: vi.fn() })); +vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({ + ...(await importOriginal()), + emitDiagnostic: diagnostic.emitDiagnostic, +})); + /** * Bound at the seam the handler consumes (the runtime's `readTextAtPoint` operation), never at * `-device/device-selection/dispatch-resolve`: `get` is migrated, so the live read reaches this fake through the request @@ -34,7 +40,10 @@ const baseParams = { }; describe('readTextForNode', () => { - beforeEach(() => readTextAtPoint.mockClear()); + beforeEach(() => { + readTextAtPoint.mockClear(); + diagnostic.emitDiagnostic.mockClear(); + }); it('returns snapshot text without a live read for non-editable nodes', async () => { const text = await readTextForNode({ @@ -109,6 +118,21 @@ describe('readTextForNode', () => { node: node({ type: 'textfield', value: 'snap' }), }); expect(text).toBe('snap'); + expect(diagnostic.emitDiagnostic).toHaveBeenCalledWith( + expect.objectContaining({ phase: 'interaction_read_fallback' }), + ); + }); + + it('refuses a clipped Android prefix before reporting a fallback', async () => { + readTextAtPoint.mockResolvedValueOnce({ status: 'unreadable', reason: 'no-text-at-point' }); + await expect( + readTextForNode({ + ...baseParams, + device: { platform: 'android' } as never, + node: node({ type: 'android.widget.EditText', value: 'prefix', textClipped: true }), + }), + ).rejects.toMatchObject({ details: { reason: 'android_text_clipped' } }); + expect(diagnostic.emitDiagnostic).not.toHaveBeenCalled(); }); it('classifies a blank live read as no-text-at-point rather than reading blank text', async () => { diff --git a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts index b03c8dc454d..6fe8a8d1690 100644 --- a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts +++ b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts @@ -17,6 +17,7 @@ import { runInteraction } from '../__tests__/support/touch-interaction-runner.ts import { handleInteractionCommands } from './interaction/index.ts'; import { contextFromFlags, + makeAndroidSession, makeSession, makeStaleRefSession, } from './interaction/internal/__tests__/interaction-touch-fixtures.ts'; @@ -201,6 +202,52 @@ test('get text answers from the captured tree when the bound owner advertises no } }); +test('get text refuses a clipped Android field instead of returning its cached prefix', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'get-text-clipped-android'; + const session = makeAndroidSession(sessionName); + session.snapshot = { + nodes: attachRefs([ + { + index: 0, + depth: 0, + type: 'android.widget.EditText', + identifier: 'com.android.settings:id/name', + bundleId: 'com.android.settings', + label: 'partial value', + value: 'partial value', + textClipped: true, + rect: { x: 20, y: 40, width: 120, height: 80 }, + }, + ]), + createdAt: Date.now(), + backend: 'android', + producer: 'android-uiautomator', + }; + sessionStore.publish(sessionName, session); + + const response = await handleInteractionCommands({ + createCommandSurface: touchCreateCommandSurface, + req: { + token: 't', + session: sessionName, + command: 'get', + positionals: ['text', '@e1'], + flags: {}, + }, + sessionName, + sessionStore, + contextFromFlags, + ...getRuntimeBindings(), + }); + + expect(response?.ok).toBe(false); + if (response && !response.ok) { + expect(response.error.details).toMatchObject({ reason: 'android_text_clipped' }); + } + expect(mockReadTextAtPoint).toHaveBeenCalledOnce(); +}); + // ADR 0019 regression: `get` declares `device-runtime`, so an ELIGIBLE direct-iOS selector — // one the fast path would otherwise answer without a tree capture — must not reach the device // until the request has resolved, admitted, and bound. A refused admission means zero runner diff --git a/packages/daemon/src/execution/selector-text-runtime.ts b/packages/daemon/src/execution/selector-text-runtime.ts index 8bdafcfc80f..885a366bc49 100644 --- a/packages/daemon/src/execution/selector-text-runtime.ts +++ b/packages/daemon/src/execution/selector-text-runtime.ts @@ -4,6 +4,7 @@ import type { ElementTextUnreadableReason, } from '@agent-device/contracts/element-text-runtime'; import { isIosFamily } from '@agent-device/kernel/device'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { runtimeExecutionFromContext } from '../core/snapshot-runtime-capture-input.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; @@ -18,6 +19,11 @@ import { resolveRectCenter } from '@agent-device/kernel/rect-center'; export type ReadElementTextAtPoint = ElementTextRuntimeOperations['readTextAtPoint']; +const SELECTOR_TEXT_READ_REASONS = { + // The Android helper returned only a prefix, and the live read did not supply the full value. + clipped: { reason: 'android_text_clipped', commands: ['get'] }, +} as const satisfies ReasonTable<'get'>; + export async function readTextForNode(params: { device: DeviceInfo; node: SnapshotNode; @@ -31,10 +37,10 @@ export async function readTextForNode(params: { const { device, node, flags, appBundleId, traceOutPath, surface, contextFromFlags } = params; const fallbackText = extractReadableText(node); const readTextAtPoint = params.readTextAtPoint; - if (!readTextAtPoint) return fallbackText; + if (!readTextAtPoint) return safeFallbackText(device, node, fallbackText); const center = resolveRectCenter(node.rect); if (!center) { - return fallbackText; + return safeFallbackText(device, node, fallbackText); } if (isIosFamily(device) && fallbackText && !prefersValueForReadableText(node.type ?? '')) { @@ -56,6 +62,7 @@ export async function readTextForNode(params: { execution: runtimeExecutionFromContext(context), }); if (outcome.status === 'read') return outcome.text; + const fallback = safeFallbackText(device, node, fallbackText); emitDiagnostic({ level: 'warn', phase: 'interaction_read_fallback', @@ -66,7 +73,16 @@ export async function readTextForNode(params: { platform: device.platform, }, }); - return fallbackText; + return fallback; +} + +function safeFallbackText(device: DeviceInfo, node: SnapshotNode, text: string): string { + if (device.platform === 'android' && node.textClipped) { + throw new AppError('COMMAND_FAILED', 'Android text value was clipped by the snapshot helper', { + reason: SELECTOR_TEXT_READ_REASONS.clipped.reason, + }); + } + return text; } function classifiedFallbackReason(reason: ElementTextUnreadableReason): string { diff --git a/packages/kernel/src/snapshot.ts b/packages/kernel/src/snapshot.ts index cba6ab2cc14..69622b67ba7 100644 --- a/packages/kernel/src/snapshot.ts +++ b/packages/kernel/src/snapshot.ts @@ -321,6 +321,8 @@ export type RawSnapshotNode = { * so `text ?? label` is the text the view shows. */ text?: string; + /** Android helper reports that the visible text is only a prefix of the field value. */ + textClipped?: boolean; identifier?: string; rect?: Rect; enabled?: boolean; diff --git a/packages/platform-android/src/__tests__/fill-diagnostics.test.ts b/packages/platform-android/src/__tests__/fill-diagnostics.test.ts index 5b95c7bab04..6c1c4858eb8 100644 --- a/packages/platform-android/src/__tests__/fill-diagnostics.test.ts +++ b/packages/platform-android/src/__tests__/fill-diagnostics.test.ts @@ -55,6 +55,21 @@ test('buildFillFailureDetails keeps non-masked text diagnostics visible', () => assert.equal(details.actualInput?.text, 'search'); }); +test('clipped fill evidence never includes the submitted or partial text', () => { + const details = buildFillFailureDetails('private-submission', { + ok: false, + actual: 'private-sub', + reason: 'text_clipped', + targetInput: node({ text: 'private-sub', focused: true }), + actualInput: node({ text: 'private-sub', focused: true }), + }); + assert.equal(details.failureReason, 'text_clipped'); + assert.equal(details.expectedLength, 'private-submission'.length); + assert.equal(details.targetInput?.text, null); + assert.equal(details.actualInput?.text, null); + assert.doesNotMatch(JSON.stringify(details), /private-sub/); +}); + test('buildFillFailureDetails infers sensitivity from password nodes', () => { const details = buildFillFailureDetails('Secret123', { ok: false, diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 81201caefd9..7330376d9c6 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -8,11 +8,12 @@ // whether any of a commit reached the field, which both the soft-success guard and the IME rebind // share. -import { afterEach, beforeEach, test } from 'vitest'; +import { afterEach, beforeEach, test, vi } from 'vitest'; import './test-utils/android-host-test-setup.ts'; import assert from 'node:assert/strict'; import { underFakeTimers } from './test-utils/fake-timers.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { Deadline, type DeadlineClock } from '@agent-device/host-kit/retry'; import { withAndroidAdbProvider, type AndroidAdbProvider } from '../adb-executor.ts'; import type { AndroidFillVerificationNode } from '../fill-diagnostics.ts'; import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; @@ -20,6 +21,7 @@ import { isAndroidFillCommitDropped, readAndroidFillTargetBeforeMutation, verifyAndroidFilledText, + verifyAndroidFilledTextWithDeadline, } from '../fill-verification.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; import { @@ -36,6 +38,16 @@ const device: DeviceInfo = { booted: true, }; +function sampleBudget(samples: number): DeadlineClock { + const startedAt = Date.now(); + const budgetMs = samples * 150; + return { + remainingMs: () => Math.max(0, budgetMs - (Date.now() - startedAt)), + elapsedMs: () => Date.now() - startedAt, + isExpired: () => Date.now() - startedAt >= budgetMs, + }; +} + beforeEach(async () => { await resetAndroidSnapshotHelperSessions(); }); @@ -108,7 +120,7 @@ test('a value the app renders late still verifies, as long as it lands before th await withFillHelperProvider( session.provider, async () => - await verifyAndroidFilledText(device, 10, 10, 'chips', { + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { helperSessionScope: 'daemon-session', }), ), @@ -122,28 +134,42 @@ test('a value that never lands is a mismatch read from the last sample', async ( const session = createFillHelperSession({ textForCapture: (captureIndex) => `Key echo ${captureIndex}`, }); - let elapsedMs = 0; - - const verification = await underFakeTimers(async () => { - const startedAt = Date.now(); - const result = await withFillHelperProvider( - session.provider, - async () => - await verifyAndroidFilledText(device, 10, 10, 'chips', { - helperSessionScope: 'daemon-session', - }), - ); - elapsedMs = Date.now() - startedAt; - return result; - }); + const verification = await underFakeTimers( + async () => + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { + helperSessionScope: 'daemon-session', + }), + ), + ); assert.equal(verification.ok, false); assert.equal(verification.reason, 'text_mismatch'); assert.equal(verification.actual, `Key echo ${session.captureCount()}`); - assert.ok( - elapsedMs >= 1_500 && elapsedMs < 1_650, - `sampled until the deadline, took ${elapsedMs} ms`, - ); + assert.ok(session.captureCount() >= 10, 'verification polls through the full sample budget'); +}); + +test('default verification uses a 1500 ms deadline', async () => { + const session = createFillHelperSession({ + textForCapture: (captureIndex) => `Key echo ${captureIndex}`, + }); + const fromTimeout = vi.spyOn(Deadline, 'fromTimeoutMs'); + try { + await underFakeTimers(async () => { + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledText(device, 10, 10, 'chips', { + helperSessionScope: 'daemon-session', + }), + ); + }); + assert.equal(fromTimeout.mock.calls[0]?.[0], 1500); + } finally { + fromTimeout.mockRestore(); + } }); test('the pre-action target read shares the daemon-session helper with the samples', async () => { diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts index ef9848a31ba..9864cf40723 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts @@ -31,6 +31,27 @@ test('a session launch owns one abstract socket name and the forward targets it' ); }); +test('the host response ceiling admits the helper XML character budget', () => { + const java = readFileSync( + new URL( + '../../../../android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java', + import.meta.url, + ), + 'utf8', + ); + const cap = /MAX_XML_CHARS = (\d+) \* (\d+) \* (\d+);/.exec(java); + assert.ok(cap, 'expected an XML character cap in AccessibilityTreeXml'); + const protocol = readFileSync( + new URL('../snapshot-helper-session-protocol.ts', import.meta.url), + 'utf8', + ); + const responseCap = /MAX_RESPONSE_BYTES = (\d+) \* (\d+) \* (\d+);/.exec(protocol); + assert.ok(responseCap, 'expected a session response byte cap'); + const maxXmlChars = Number(cap[1]) * Number(cap[2]) * Number(cap[3]); + const maxResponseBytes = Number(responseCap[1]) * Number(responseCap[2]) * Number(responseCap[3]); + assert.ok(maxResponseBytes >= maxXmlChars * 4); +}); + test('the host socket namespace, session mode and byte cap agree with the Android helper', () => { const java = readFileSync( new URL( diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts index a6d118df701..e8c1dd674f4 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts @@ -79,6 +79,28 @@ async function listenOnce(onSocket: (socket: net.Socket) => void) { return { port: address.port, close }; } +test('authenticated helper response stops at its byte ceiling', async () => { + const listener = await listenOnce((socket) => { + onSessionCommand(socket, () => { + socket.write(Buffer.alloc(32 * 1024 * 1024 + 1)); + }); + }); + try { + await assert.rejects( + sendAndroidSnapshotHelperSessionCommand( + { port: listener.port, secret: Buffer.from(FIXTURE_SESSION_SECRET, 'hex') }, + 'snapshot req-oversized', + 5_000, + ), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'android_snapshot_helper_session_response_too_large', + ); + } finally { + await listener.close(); + } +}); + test.each([ { label: 'a refused connection', closedBeforeConnect: true }, { label: 'a socket that closes before the hello', closedBeforeConnect: false }, diff --git a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts index 40565921ef6..3423419ad25 100644 --- a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts @@ -87,7 +87,13 @@ function createFillWorld( if (options.shellTextError) throw options.shellTextError; fieldText = args[3] ?? ''; } - if (args.includes('--show-versioncode')) return await persistent.exec(args, execOptions); + if ( + args.includes('--show-versioncode') || + args.join(' ') === 'shell pm path com.callstack.agentdevice.snapshothelper' || + args[0] === 'pull' + ) { + return await persistent.exec(args, execOptions); + } if (args[0] === 'shell' && args[1] !== 'am') return { exitCode: 0, stdout: '', stderr: '' }; return await persistent.exec(args, execOptions); }, diff --git a/packages/platform-android/src/__tests__/text-input-fill.test.ts b/packages/platform-android/src/__tests__/text-input-fill.test.ts index 642cd69c2e3..c7eabea16ff 100644 --- a/packages/platform-android/src/__tests__/text-input-fill.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill.test.ts @@ -12,6 +12,7 @@ import { withAndroidAdbProvider, type AndroidAdbExecutor } from '../adb-executor import { androidFillFailureDetails, androidFillFailureMessage, + buildAndroidFillUnconfirmedVerification, readAndroidTextAtPointInHierarchy, verifyAndroidFilledTextInHierarchy, } from '../fill-verification.ts'; @@ -540,6 +541,26 @@ test('verifyAndroidFilledTextInHierarchy rejects near-complete prefixes', () => assert.equal(verification.actual, 'filed the expens'); }); +test('verifyAndroidFilledTextInHierarchy does not verify clipped text prefixes', () => { + const xml = androidInputXml({ text: 'filed the expense' }).replace( + 'text="filed the expense"', + 'text="filed the expense" text-clipped="true"', + ); + const verification = verifyAndroidFilledTextInHierarchy(xml, 10, 10, 'filed the expense'); + + assert.equal(verification.ok, false); + assert.equal(verification.reason, 'text_clipped'); + assert.equal(verification.actualInput?.textClipped, true); + assert.equal( + buildAndroidFillUnconfirmedVerification( + 'filed the expense', + verification.targetInput, + verification, + ), + null, + ); +}); + test('verifyAndroidFilledTextInHierarchy does not treat inputmethod substring as IME ownership', () => { const verification = verifyAndroidFilledTextInHierarchy( appPackageWithInputMethodSubstringHierarchy(), @@ -711,7 +732,13 @@ test('fillAndroid confirms a moved clear through one warm helper', async () => { exec: async (args, options) => { if (isDeleteKey(args)) typed = ''; if (isTextInput(args)) typed = args[3] ?? ''; - if (args.includes('--show-versioncode')) return provider.exec(args, options); + if ( + args.includes('--show-versioncode') || + (args[0] === 'shell' && args[1] === 'pm' && args[2] === 'path') || + args[0] === 'pull' + ) { + return provider.exec(args, options); + } if (args[0] === 'shell' && args[1] !== 'am') return adbResult(''); return await provider.exec(args, options); }, diff --git a/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts b/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts index 8b05994af3a..9db2cff4cee 100644 --- a/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts +++ b/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts @@ -21,6 +21,18 @@ test.each([false, true])( }, ); +test.each([false, true])('clipped text remains marked on a complete tree (raw=%s)', (raw) => { + const tree = parseUiHierarchyTree(``); + const { nodes, truncated } = buildUiHierarchySnapshot(tree, undefined, { raw }); + expect(truncated).not.toBe(true); + expect(nodes.find((node) => node.identifier === 'field')).toMatchObject({ + value: 'partial value', + textClipped: true, + }); +}); + test('selection offsets survive on a read-only selectable node (independent of editable)', () => { const tree = parseUiHierarchyTree(` { + const clipped = ``; + expect(readAndroidTextAtPointInHierarchy(clipped, 10, 10, identity)).toBeNull(); + expect(readAndroidTextAtPointInHierarchy(clipped, 10, 10)).toBeNull(); + expect( + readAndroidTextAtPointInHierarchy(clipped, 10, 10, { ...identity, identifier: 'missing' }), + ).toBeNull(); + expect( + readAndroidTextAtPointInHierarchy(clipped.replace('text-clipped="true"', ''), 10, 10, identity), + ).toBe('prefix'); +}); + test('a moved Compose container reads by its published button role', () => { const xml = ` diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 30b801317c1..78987286d15 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -1,7 +1,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, discloseDispatch } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry'; +import { Deadline, pollUntilSettled, type DeadlineClock } from '@agent-device/host-kit/retry'; import { containsPoint } from '@agent-device/kernel/rect'; import type { Rect } from '@agent-device/kernel/snapshot'; import { @@ -96,7 +96,27 @@ export async function verifyAndroidFilledText( helper: AndroidHelperSessionOptions = {}, beforeCapture?: AndroidFillTargetCapture | null, ): Promise { - const deadline = Deadline.fromTimeoutMs(FILL_VERIFICATION_DEADLINE_MS); + return await verifyAndroidFilledTextWithDeadline( + device, + x, + y, + expected, + Deadline.fromTimeoutMs(FILL_VERIFICATION_DEADLINE_MS), + helper, + beforeCapture, + ); +} + +/** @internal Runs fill verification against the caller's poll budget. */ +export async function verifyAndroidFilledTextWithDeadline( + device: DeviceInfo, + x: number, + y: number, + expected: string, + deadline: DeadlineClock, + helper: AndroidHelperSessionOptions = {}, + beforeCapture?: AndroidFillTargetCapture | null, +): Promise { const capture = await captureAndroidUiHierarchy(device, { ...helper, idleWait: 'none' }); let initialObservation: AndroidFillObservation | undefined = parseAndroidFillObservation( capture.xml, @@ -272,6 +292,7 @@ export function buildAndroidFillUnconfirmedVerification( // and the soft-success would also skip the second, bigger delete burst. requested.length === 0 || verification.reason === 'ime_capture' || + verification.reason === 'text_clipped' || isAndroidFillCommitDropped(verification, beforeTarget) || !beforeTarget || !afterTarget || @@ -341,6 +362,16 @@ function verifyAndroidFilledTextInObservation( }; } + if (inspection.actualInput?.textClipped) { + return { + ok: false, + actual: inspection.actualInput.text, + reason: 'text_clipped', + targetInput: inspection.targetInput, + actualInput: inspection.actualInput, + }; + } + return ( maskedAndroidFillVerification(inspection, expected) ?? textAndroidFillVerification(inspection, expected) @@ -355,14 +386,8 @@ export function readAndroidTextAtPointInHierarchy( ): string | null { const observation = parseAndroidFillObservation(xml); if (target?.identifier) { - const matches = observation.nodes.filter((node) => androidNodeMatchesFillTarget(node, target)); - const candidates = matches.flatMap((node) => { - const candidate = androidFillCandidateFromNode(node, {}); - return candidate ? [candidate] : []; - }); - if (matches.length === 1 && candidates.length === 1) return candidates[0]!.text; - const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); - if (atPoint.length === 1) return atPoint[0]!.text; + const identityCandidate = textCandidateByIdentity(observation, x, y, target); + if (identityCandidate) return completeAndroidText(identityCandidate); } // Reads are point-targeted: a focused sibling may be a different app field or an IME // composing surface, so it must not override the node that contains the requested point. @@ -373,7 +398,27 @@ export function readAndroidTextAtPointInHierarchy( (target?.type && !androidRawClassMatchesPublishedType(pointTarget.className, target.type)) ) return null; - return pointTarget.text; + return completeAndroidText(pointTarget); +} + +function textCandidateByIdentity( + observation: AndroidFillObservation, + x: number, + y: number, + target: ElementTextTarget, +): AndroidFillVerificationCandidate | null { + const matches = observation.nodes.filter((node) => androidNodeMatchesFillTarget(node, target)); + const candidates = matches.flatMap((node) => { + const candidate = androidFillCandidateFromNode(node, {}); + return candidate ? [candidate] : []; + }); + if (matches.length === 1 && candidates.length === 1) return candidates[0]!; + const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); + return atPoint.length === 1 ? atPoint[0]! : null; +} + +function completeAndroidText(candidate: AndroidFillVerificationCandidate): string | null { + return candidate.textClipped ? null : candidate.text; } export function androidFillFailureMessage(verification: AndroidFillVerification | null): string { @@ -383,6 +428,9 @@ export function androidFillFailureMessage(verification: AndroidFillVerification if (verification?.reason === 'masked_unverified') { return 'Android fill verification could not confirm masked text value'; } + if (verification?.reason === 'text_clipped') { + return 'Android fill verification could not confirm clipped text value'; + } return 'Android fill verification failed'; } @@ -606,6 +654,7 @@ function androidFillCandidateFromNode( const area = Math.max(1, node.rect.width * node.rect.height); return { text: text || null, + textClipped: node.textClipped === true, className: node.className, resourceId: node.resourceId, packageName: node.packageName, diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index 076f516d3ee..dc2b575c74e 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -43,6 +43,10 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise { // A 64 KiB `fill --text-stdin` value of JSON-escaped control characters encodes to 524,368 Base64 // bytes, and the action and request id follow; SessionPeerPolicy.java owns the full derivation. export const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_COMMAND_BYTES = 513 * 1024; +// AccessibilityTreeXml budgets the whole hierarchy at 8 MiB UTF-16 chars, including windows. +// UTF-8 needs at most three bytes per UTF-16 code unit, so 32 MiB admits the tree plus its +// bounded final-node structural overshoot while still rejecting an unbounded peer. +const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES = 32 * 1024 * 1024; /** * What this host launched one session with: the abstract socket the helper was told to bind, named @@ -73,6 +77,8 @@ const SNAPSHOT_HELPER_SESSION_REASONS = { requestTimeout: { reason: 'android_snapshot_helper_session_request_timeout' }, // The listener could not prove the session secret, so it is not the helper this session launched. peerUnverified: { reason: 'android_snapshot_helper_session_peer_unverified' }, + // The helper answer exceeded the authenticated session's response byte limit. + responseTooLarge: { reason: 'android_snapshot_helper_session_response_too_large' }, // The helper process never reported readiness before the readiness budget ran out. readyTimeout: { reason: 'android_snapshot_helper_session_ready_timeout' }, // The readiness record the helper sent does not prove this session's protocol, socket, or secret. @@ -135,6 +141,7 @@ export function sendAndroidSnapshotHelperSessionCommand( let phase: 'nonce-sent' | 'proven' | 'refused' = 'nonce-sent'; let hello = Buffer.alloc(0); const chunks: Buffer[] = []; + let responseBytes = 0; const timer = setTimeout(() => { cleanup(); socket.destroy(); @@ -186,7 +193,27 @@ export function sendAndroidSnapshotHelperSessionCommand( socket.on('connect', () => socket.write(`${clientNonce}\n`)); // Only the helper that printed the secret can answer the nonce; anything else is refused. socket.on('data', (chunk) => { - if (phase === 'proven') return void chunks.push(Buffer.from(chunk)); + if (phase === 'proven') { + responseBytes += chunk.byteLength; + if (responseBytes > ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES) { + phase = 'refused'; + cleanup(); + socket.destroy(); + reject( + new AppError( + 'COMMAND_FAILED', + 'Android snapshot helper response exceeds the size limit', + { + reason: SNAPSHOT_HELPER_SESSION_REASONS.responseTooLarge.reason, + limitBytes: ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES, + }, + ), + ); + return; + } + chunks.push(Buffer.from(chunk)); + return; + } if (phase === 'refused') return; // Keep at most the one hello line, `<64 hex nonce> <64 hex proof>\n`. An honest helper sends // nothing more before the client proof, so any byte past that window, or a line of any other diff --git a/packages/platform-android/src/ui-hierarchy-node.ts b/packages/platform-android/src/ui-hierarchy-node.ts index c1d7a30ef81..930271871a7 100644 --- a/packages/platform-android/src/ui-hierarchy-node.ts +++ b/packages/platform-android/src/ui-hierarchy-node.ts @@ -8,6 +8,7 @@ type AndroidPassiveNodeFacts = Pick< RawSnapshotNode, | 'contentDescription' | 'text' + | 'textClipped' | 'enabled' | 'selected' | 'heading' diff --git a/packages/platform-android/src/ui-hierarchy.ts b/packages/platform-android/src/ui-hierarchy.ts index 94e0642b32e..7791f376a40 100644 --- a/packages/platform-android/src/ui-hierarchy.ts +++ b/packages/platform-android/src/ui-hierarchy.ts @@ -25,6 +25,8 @@ export type { /** Parsed node metadata plus status/navigation subtree provenance when present. */ export type AndroidUiNodeMetadata = { text: string | null; + /** Helper-only: the `text` attribute contains only a prefix of the observed value. */ + textClipped?: boolean; desc: string | null; resourceId: string | null; packageName: string | null; @@ -165,6 +167,7 @@ function readNodeAttributes(node: string): Omit { }; return { text: getAttr('text'), + ...optionalBoolAttr('textClipped', 'text-clipped'), desc: getAttr('content-desc'), resourceId: getAttr('resource-id'), packageName: getAttr('package'), @@ -353,6 +356,7 @@ function normalizeAndroidUiHierarchyNode( passiveFacts: { contentDescription: attrs.desc && attrs.desc !== label ? attrs.desc : undefined, text: label && !attrs.text ? '' : undefined, + textClipped: attrs.textClipped, enabled: attrs.enabled, selected: attrs.selected, heading: attrs.heading, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 552560b1298..77af9de6b43 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -875,10 +875,11 @@ agent-device get text @e1 agent-device get attrs @e1 ``` +- On Android, `get text` fails with `android_text_clipped` when the snapshot has only a field-value prefix and a live read cannot provide the complete text. Check the node's `textClipped` flag; the tree itself can still be complete. - `--raw` returns the full provider tree, including offscreen nodes and structural wrappers. See [iOS capture behavior](/docs/snapshots#ios-capture-behavior) and [Android capture behavior](/docs/snapshots#android-capture-behavior). - A source checkout must run `pnpm build:android` before Android verification, because Android snapshots install a bundled helper. -- `truncated: true` means the capture hit a backend node limit and the last elements are missing; see [Truncated captures](/docs/snapshots#truncated-captures). +- `truncated: true` means the capture hit a backend node limit or Android's total XML character budget, so later elements may be missing; see [Truncated captures](/docs/snapshots#truncated-captures). - For `viewport`, `--scope`, and `--actions`, see [Snapshots](/docs/snapshots). - `diff snapshot` compares with the previous snapshot in the session, then makes the new one the baseline. A snapshot read with different flags starts a new baseline instead of listing changes. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index de5c147e0e8..e3a89daa61d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -151,6 +151,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `GESTURE_TRAJECTORY_NON_FINITE` | A trajectory sample carries a non-finite coordinate. | | `GESTURE_TRAJECTORY_OUT_OF_BOUNDS` | A trajectory sample leaves the viewport, so the contact would press outside the screen, or a two-finger path cannot keep its contacts the minimum span apart inside it. | +### `get` + +| Reason | Meaning | +| --- | --- | +| `android_text_clipped` | The Android helper returned only a prefix, and the live read did not supply the full value. | + ### `home` | Reason | Meaning | @@ -509,6 +515,7 @@ These reasons can come from more than one command. | `android_snapshot_helper_runtime_occupied` | Another helper process still holds UiAutomation, so nothing can take the runtime. | | `android_snapshot_helper_session_request_timeout` | The helper accepted the session request but sent no answer before the command deadline. | | `android_snapshot_helper_session_peer_unverified` | The listener could not prove the session secret, so it is not the helper this session launched. | +| `android_snapshot_helper_session_response_too_large` | The helper answer exceeded the authenticated session's response byte limit. | | `android_snapshot_helper_session_ready_timeout` | The helper process never reported readiness before the readiness budget ran out. | | `android_snapshot_helper_session_ready_malformed` | The readiness record the helper sent does not prove this session's protocol, socket, or secret. | | `android_snapshot_helper_session_exited_before_ready` | The helper process ended before it reported readiness. | diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 677d51ac14a..c8bd7659c6a 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -203,9 +203,12 @@ agent-device snapshot -s @e12 ## Truncated captures -`truncated: true` means the Android snapshot helper or the iOS Simulator accessibility bridge hit its -5000-node limit, or the web provider hit its own bound. On Android the limit applies before any `-s` -scope. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with +`truncated: true` means the Android snapshot helper hit its 5000-node or total XML character +budget, the iOS Simulator accessibility bridge hit its 5000-node limit, or the web provider hit +its own bound. On Android the node limit applies before any `-s` scope. An Android node with a +value clipped at the 384 KiB escaped-text limit (64 KiB for other attributes) has +`textClipped: true` on the snapshot node. The tree remains complete, but `get text` rejects that +partial value. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with `--raw`) the snapshot fails with a hint to scope it or take a screenshot instead. Every backend walks the tree in document order, so what gets cut is what comes last: footers, tab