diff --git a/apple/snapshot-presentation/Package.swift b/apple/snapshot-presentation/Package.swift index 87ce726160..018a655709 100644 --- a/apple/snapshot-presentation/Package.swift +++ b/apple/snapshot-presentation/Package.swift @@ -21,13 +21,14 @@ let package = Package( ], targets: [ .target(name: "AgentDeviceSnapshotPresentation"), + .target(name: "RecordingSupport", dependencies: ["AgentDeviceSnapshotPresentation"]), .executableTarget( name: "SnapshotPresentationConformance", - dependencies: ["AgentDeviceSnapshotPresentation"] + dependencies: ["AgentDeviceSnapshotPresentation", "RecordingSupport"] ), .testTarget( name: "AgentDeviceSnapshotPresentationTests", - dependencies: ["AgentDeviceSnapshotPresentation"] + dependencies: ["AgentDeviceSnapshotPresentation", "RecordingSupport"] ), ] ) diff --git a/apple/snapshot-presentation/Sources/RecordingSupport/FixtureRect.swift b/apple/snapshot-presentation/Sources/RecordingSupport/FixtureRect.swift new file mode 100644 index 0000000000..6706ec7721 --- /dev/null +++ b/apple/snapshot-presentation/Sources/RecordingSupport/FixtureRect.swift @@ -0,0 +1,30 @@ +import CoreGraphics +import Foundation + +/// A rect as a `contracts/fixtures/` table spells it. JSON has no infinity, so the two unusable +/// boxes are named: `{"infinite": true}` is `CGRect.infinite`, and `{"nonFinite": true}` is a +/// box whose components are infinite. +package struct FixtureRect: Decodable { + private enum CodingKeys: String, CodingKey { + case x, y, width, height, infinite, nonFinite + } + + package let cgRect: CGRect + + package init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if try container.decodeIfPresent(Bool.self, forKey: .infinite) == true { + self.cgRect = .infinite + } else if try container.decodeIfPresent(Bool.self, forKey: .nonFinite) == true { + self.cgRect = CGRect(x: -.infinity, y: -.infinity, width: .infinity, height: .infinity) + } else { + self.cgRect = CGRect( + x: try container.decode(Double.self, forKey: .x), + y: try container.decode(Double.self, forKey: .y), + width: try container.decode(Double.self, forKey: .width), + height: try container.decode(Double.self, forKey: .height) + ) + } + } +} + diff --git a/apple/snapshot-presentation/Sources/RecordingSupport/RawAlertRecording.swift b/apple/snapshot-presentation/Sources/RecordingSupport/RawAlertRecording.swift new file mode 100644 index 0000000000..8174e2772c --- /dev/null +++ b/apple/snapshot-presentation/Sources/RecordingSupport/RawAlertRecording.swift @@ -0,0 +1,75 @@ +import Foundation +import AgentDeviceSnapshotPresentation + +package struct RawAlertRecording: Decodable { + package struct Node: Decodable { + package let index: Int + package let parentIndex: Int? + package let element: String + package let type: String + package let identifier: String + package let label: String + package let rect: FixtureRect + } + + let format: Int + package let plain: [Node] + package let honorModal: [Node] + + package static func load(_ file: URL) throws -> RawAlertRecording { + func invalid(_ detail: String) -> NSError { + NSError(domain: "alert-recording", code: 1, userInfo: [NSLocalizedDescriptionKey: "\(file.path): \(detail)"]) + } + let recording: Self + do { + recording = try JSONDecoder().decode(Self.self, from: Data(contentsOf: file)) + } catch let error as DecodingError { + let context: DecodingError.Context + switch error { + case let .keyNotFound(_, value), let .valueNotFound(_, value), + let .typeMismatch(_, value), let .dataCorrupted(value): context = value + @unknown default: throw error + } + let path = context.codingPath.map { $0.intValue.map { "node \($0)" } ?? $0.stringValue }.joined(separator: ".") + throw invalid("\(path): \(context.debugDescription)") + } + guard recording.format == 2 else { throw invalid("format \(recording.format) is not 2. Capture it again.") } + for (name, nodes) in [("plain", recording.plain), ("honorModal", recording.honorModal)] { + guard !nodes.isEmpty else { throw invalid("\(name): empty tree") } + for (position, node) in nodes.enumerated() { + guard node.index == position, node.parentIndex.map({ $0 >= 0 && $0 < position }) ?? (position == 0) else { + throw invalid("\(name) node \(position): invalid preorder index or parent") + } + } + } + return recording + } + + package static func tree(_ nodes: [Node], at root: Int = 0) -> AlertSurfaceNode { + var children: [Int: [Int]] = [:] + for node in nodes { + if let parent = node.parentIndex { children[parent, default: []].append(node.index) } + } + func build(_ index: Int) -> AlertSurfaceNode { + let node = nodes[index] + return AlertSurfaceNode( + type: node.type, + identifier: node.identifier, + label: node.label, + frame: node.rect.cgRect, + children: (children[index] ?? []).map(build) + ) + } + return build(root) + } + + package static func modalScopeNodes(_ nodes: [Node]) -> [ModalScopeNode] { + nodes.map { node in + ModalScopeNode( + element: node.element, + parentElement: node.parentIndex.map { nodes[$0].element }, + frame: node.rect.cgRect + ) + } + } +} diff --git a/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/PrintAlertSurface.swift b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/PrintAlertSurface.swift new file mode 100644 index 0000000000..880ec8ca09 --- /dev/null +++ b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/PrintAlertSurface.swift @@ -0,0 +1,50 @@ +import AgentDeviceSnapshotPresentation +import CoreGraphics +import Foundation + +import RecordingSupport + +func printAlertSurface(_ arguments: [String]) throws { + guard let file = arguments.first, arguments.count <= 2, + arguments.count == 1 || ["honorModal", "plain"].contains(arguments[1]) + else { + throw NSError(domain: "print:alert-surface", code: 1, userInfo: [ + NSLocalizedDescriptionKey: "Usage: pnpm print:alert-surface [honorModal|plain]" + ]) + } + let recording = try RawAlertRecording.load(URL(fileURLWithPath: file)) + let plain = RawAlertRecording.modalScopeNodes(recording.plain) + let honorModal = RawAlertRecording.modalScopeNodes(recording.honorModal) + let reading = ModalSurface.read( + plain: plain, honorModal: honorModal, confirmingHonorModal: honorModal, truncated: false + ) + let answer: String + var markers: [Int: String] = [:] + switch reading { + case let .modal(surfaces): + answer = "modal" + for surface in surfaces { + markers[surface.host] = " [surface roots: \(surface.roots.map(String.init).joined(separator: ", "))]" + } + case .noExclusion: + answer = "noExclusion" + case let .unknown(.unstable(instability)): + answer = "unknown(unstable(\(instability.rawValue)))" + case let .unknown(reason): + answer = "unknown(\(reason))" + } + print("ModalSurface reads (the rule's answer, not ground truth): \(answer)") + let printPlain = arguments.count == 2 && arguments[1] == "plain" + let nodes = printPlain ? recording.plain : recording.honorModal + var depths: [Int] = [] + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + for node in nodes { + let depth = node.parentIndex.map { depths[$0] + 1 } ?? 0 + depths.append(depth) + let label = String(decoding: try encoder.encode(node.label), as: UTF8.self) + let index = String(repeating: " ", count: max(0, 4 - String(node.index).count)) + String(node.index) + let marker = printPlain ? "" : markers[node.index] ?? "" + print("\(index) \(String(repeating: " ", count: depth))\(node.type) \(label)\(marker)") + } +} diff --git a/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift index 6b5ea3a3ba..e0dd9b7818 100644 --- a/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift +++ b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift @@ -144,12 +144,21 @@ private func reason(for failure: SnapshotPresentationFailure) -> String { } } -private let input = try JSONDecoder().decode( - BatchInput.self, - from: FileHandle.standardInput.readDataToEndOfFile() -) -private let output = try JSONEncoder().encode( - BatchOutput(cases: input.cases.map(present)) -) -FileHandle.standardOutput.write(output) -FileHandle.standardOutput.write(Data([0x0a])) +if CommandLine.arguments.dropFirst().first == "print-alert-surface" { + do { + try printAlertSurface(Array(CommandLine.arguments.dropFirst(2))) + } catch { + FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8)) + exit(1) + } +} else { + let input = try JSONDecoder().decode( + BatchInput.self, + from: FileHandle.standardInput.readDataToEndOfFile() + ) + let output = try JSONEncoder().encode( + BatchOutput(cases: input.cases.map(present)) + ) + FileHandle.standardOutput.write(output) + FileHandle.standardOutput.write(Data([0x0a])) +} diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift index c3a65eaad8..47d018dd96 100644 --- a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift @@ -1,3 +1,4 @@ +import RecordingSupport import AgentDeviceSnapshotPresentation import CoreGraphics import Foundation diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/CoordinateSpaceTests.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/CoordinateSpaceTests.swift index 60e4f7009c..5a4c64110e 100644 --- a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/CoordinateSpaceTests.swift +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/CoordinateSpaceTests.swift @@ -1,3 +1,4 @@ +import RecordingSupport import AgentDeviceSnapshotPresentation import CoreGraphics import Foundation diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/FixtureRect.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/FixtureRect.swift index f3152d43b4..730b2fa52a 100644 --- a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/FixtureRect.swift +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/FixtureRect.swift @@ -1,32 +1,5 @@ -import CoreGraphics import Foundation - -/// A rect as a `contracts/fixtures/` table spells it. JSON has no infinity, so the two unusable -/// boxes are named: `{"infinite": true}` is `CGRect.infinite`, and `{"nonFinite": true}` is a -/// box whose components are infinite. -struct FixtureRect: Decodable { - private enum CodingKeys: String, CodingKey { - case x, y, width, height, infinite, nonFinite - } - - let cgRect: CGRect - - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - if try container.decodeIfPresent(Bool.self, forKey: .infinite) == true { - self.cgRect = .infinite - } else if try container.decodeIfPresent(Bool.self, forKey: .nonFinite) == true { - self.cgRect = CGRect(x: -.infinity, y: -.infinity, width: .infinity, height: .infinity) - } else { - self.cgRect = CGRect( - x: try container.decode(Double.self, forKey: .x), - y: try container.decode(Double.self, forKey: .y), - width: try container.decode(Double.self, forKey: .width), - height: try container.decode(Double.self, forKey: .height) - ) - } - } -} +import RecordingSupport func contractsFixtureURL(_ name: String, from filePath: String = #filePath) -> URL { URL(fileURLWithPath: filePath) diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/PrintAlertSurfaceTests.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/PrintAlertSurfaceTests.swift new file mode 100644 index 0000000000..650c3733f7 --- /dev/null +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/PrintAlertSurfaceTests.swift @@ -0,0 +1,24 @@ +import Foundation +import XCTest + +final class PrintAlertSurfaceTests: XCTestCase { + func testPrintModeDispatchAndCorpusOutput() throws { + let package = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let process = Process() + process.executableURL = package.appendingPathComponent(".build/debug/snapshot-presentation-conformance") + process.arguments = [ + "print-alert-surface", + package.appendingPathComponent("Tests/AlertSurfaceCorpus/iphone-duo-folded-safari-open-this-page-in-app.json").path, + ] + let output = Pipe() + process.standardOutput = output + try process.run() + let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0) + XCTAssertTrue(text.hasPrefix("ModalSurface reads (the rule's answer, not ground truth): modal\n")) + XCTAssertTrue(text.contains("[surface roots:")) + XCTAssertTrue(text.contains("Application")) + } +} diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/RecordedAlertSurface.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/RecordedAlertSurface.swift index 85a0324d32..2af2711da0 100644 --- a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/RecordedAlertSurface.swift +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/RecordedAlertSurface.swift @@ -1,24 +1,14 @@ import CoreGraphics import Foundation @testable import AgentDeviceSnapshotPresentation +import RecordingSupport /// Two trees of one screen recorded by `pnpm capture:alert-surface`, and what the rules must find in /// them. Trees are never edited by hand. `expect` names, for each alert source, the one surface that /// source must find in the honor-modal tree; a source it does not name must find nothing. /// `expectModalScope` is what `ModalSurface` must read from the pair. -struct RecordedAlertSurface: Decodable { - static let format = 2 - - struct Node: Decodable { - let index: Int - let parentIndex: Int? - let element: String - let type: String - let identifier: String - let label: String - let rect: FixtureRect - } - +struct RecordedAlertSurface { + typealias Node = RawAlertRecording.Node struct Expectation: Decodable { let title: String let buttons: [String] @@ -41,57 +31,30 @@ struct RecordedAlertSurface: Decodable { let excludedActions: [String]? } - let format: Int - let expect: [String: Expectation] - let expectModalScope: ModalScopeExpectation - let plain: [Node] - let honorModal: [Node] - - static func load(_ file: URL) throws -> RecordedAlertSurface { - let recorded = try JSONDecoder().decode(RecordedAlertSurface.self, from: Data(contentsOf: file)) - guard recorded.format == format, isPreorder(recorded.plain), isPreorder(recorded.honorModal) else { - throw CocoaError(.coderReadCorrupt) - } - return recorded + private struct Expectations: Decodable { + let expect: [String: Expectation] + let expectModalScope: ModalScopeExpectation } - // Each node's index is its position, and its parent comes before it. - private static func isPreorder(_ nodes: [Node]) -> Bool { - !nodes.isEmpty && nodes.indices.allSatisfy { position in - let node = nodes[position] - guard node.index == position else { return false } - guard let parent = node.parentIndex else { return position == 0 } - return parent >= 0 && parent < position - } + private let recording: RawAlertRecording + private let expectations: Expectations + var expect: [String: Expectation] { expectations.expect } + var expectModalScope: ModalScopeExpectation { expectations.expectModalScope } + var plain: [Node] { recording.plain } + var honorModal: [Node] { recording.honorModal } + + static func load(_ file: URL) throws -> RecordedAlertSurface { + RecordedAlertSurface( + recording: try RawAlertRecording.load(file), + expectations: try JSONDecoder().decode(Expectations.self, from: Data(contentsOf: file)) + ) } static func tree(_ nodes: [Node], at root: Int = 0) -> AlertSurfaceNode { - var children: [Int: [Int]] = [:] - for node in nodes { - if let parent = node.parentIndex { children[parent, default: []].append(node.index) } - } - func build(_ index: Int) -> AlertSurfaceNode { - let node = nodes[index] - return AlertSurfaceNode( - type: node.type, - identifier: node.identifier, - label: node.label, - frame: node.rect.cgRect, - children: (children[index] ?? []).map(build) - ) - } - return build(root) + RawAlertRecording.tree(nodes, at: root) } + static let modalScopeNodes = RawAlertRecording.modalScopeNodes - static func modalScopeNodes(_ nodes: [Node]) -> [ModalScopeNode] { - nodes.map { node in - ModalScopeNode( - element: node.element, - parentElement: node.parentIndex.map { nodes[$0].element }, - frame: node.rect.cgRect - ) - } - } } func recordedAlertSurfaces() throws -> [(name: String, recorded: RecordedAlertSurface)] { diff --git a/apple/snapshot-presentation/Tests/AlertSurfaceCorpus/README.md b/apple/snapshot-presentation/Tests/AlertSurfaceCorpus/README.md index 4ce6c2aafc..25da57b86c 100644 --- a/apple/snapshot-presentation/Tests/AlertSurfaceCorpus/README.md +++ b/apple/snapshot-presentation/Tests/AlertSurfaceCorpus/README.md @@ -41,11 +41,10 @@ checking each root and action against the screenshot. pnpm print:alert-surface apple/snapshot-presentation/Tests/AlertSurfaceCorpus/iphone-duo-folded-springboard-open-in-app.json ``` - Each line after the first shows a node's index, type, and label. `[kept 1 of 3 children]` - marks a node where the honor-modal tree removed children. The first line is what - `ModalSurface` reads, labeled as the rule's answer, not ground truth. It is `modal`, - `noExclusion`, or `unknown()` with the node where the read failed, and nodes are - marked only when it is `modal`. To print the whole tree, add `plain` after the path. If the + The command runs the Swift package's rule directly. Each line after the first shows a node's + index, type, and label. `[surface roots: 3]` marks a modal host and lists its kept roots. + The first line is what `ModalSurface` reads, labeled as the rule's answer, not ground truth. + It is `modal`, `noExclusion`, or `unknown()`. Hosts are marked only for `modal`. To print the whole tree, add `plain` after the path. If the recording does not load in the replay, the command stops with one line that names the problem. 4. Add `expect` from the screenshot. For each source that must find the prompt, give its title and @@ -64,8 +63,7 @@ checking each root and action against the screenshot. screen. Don't add the recording. Report the screen in an issue, and attach the recording. - If the first line reads `unknown(duplicatedChild)`, a node lists one element more than once and the honor-modal tree kept only some of the copies, so the rule can't tell which copy - lost children. The line shows the element as its raw AX `element` id, such as - `99943:4829729792.1219`. Search the recording for that id to find the copies. Write + lost children. Inspect repeated AX `element` ids under the same parent in the recording. Write `{"reading": "unknown", "reason": "duplicatedChild"}` only after you confirm those copies in the recording. - If the first line reads `unknown` with any other reason, the replay rejects the recording. @@ -88,9 +86,9 @@ of its printout: ```text ModalSurface reads (the rule's answer, not ground truth): modal - 0 Application "" [kept 1 of 40 children] - 1 Window "" [kept 1 of 3 children] - 2 Other "" [kept 1 of 3 children] + 0 Application "" + 1 Window "" + 2 Other "" [surface roots: 3] 3 Alert "Open in “Agent Device Tester”?" 4 Other "" 5 Other "" diff --git a/package.json b/package.json index 7035902303..e22743881c 100644 --- a/package.json +++ b/package.json @@ -225,7 +225,7 @@ "test:linux:command-evidence": "node --experimental-strip-types test/integration/linux-e2e/live-runner.ts", "prepublishOnly": "echo 'agent-device publishes from .github/workflows/release.yml; see CONTRIBUTING.md.' >&2 && exit 1", "capture:alert-surface": "node --experimental-strip-types scripts/capture-alert-surface.ts", - "print:alert-surface": "node --experimental-strip-types scripts/print-alert-surface-tree.ts" + "print:alert-surface": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift run --package-path apple/snapshot-presentation snapshot-presentation-conformance print-alert-surface" }, "files": [ "bin", diff --git a/scripts/package-apple-runner-source.mjs b/scripts/package-apple-runner-source.mjs index 00510f20ee..287d2e43ac 100644 --- a/scripts/package-apple-runner-source.mjs +++ b/scripts/package-apple-runner-source.mjs @@ -18,6 +18,7 @@ const SNAPSHOT_PRESENTATION_RUNNER_MANIFEST = 'Package.runner.swift'; const SNAPSHOT_PRESENTATION_DEVELOPMENT_DIR_NAMES = new Set([ 'Tests', 'SnapshotPresentationConformance', + 'RecordingSupport', '.build', '.swiftpm', 'UnitTests', diff --git a/scripts/print-alert-surface-tree.ts b/scripts/print-alert-surface-tree.ts deleted file mode 100644 index 2ec9338af6..0000000000 --- a/scripts/print-alert-surface-tree.ts +++ /dev/null @@ -1,203 +0,0 @@ -// Prints what ModalSurface reads from an alert surface corpus recording, then one of its trees, one -// node per line, so a contributor can write its `expectModalScope` by hand. -// See apple/snapshot-presentation/Tests/AlertSurfaceCorpus/README.md. -import fs from 'node:fs'; - -type Rect = { - infinite?: boolean; - nonFinite?: boolean; - x: number; - y: number; - width: number; - height: number; -}; -type RecordedNode = { - index: number; - parentIndex?: number; - element: string; - type: string; - label: string; - rect: Rect; -}; - -function fail(message: string): never { - console.error(message); - process.exit(1); -} - -const [file, treeName = 'honorModal'] = process.argv.slice(2); -if (!file || (treeName !== 'honorModal' && treeName !== 'plain')) { - fail('Usage: pnpm print:alert-surface [honorModal|plain]'); -} -let recording: Record; -try { - recording = JSON.parse(fs.readFileSync(file, 'utf8')); -} catch (error) { - fail(`${file}: ${(error as Error).message}`); -} -if (recording.format !== 2) { - fail(`${file}: format ${JSON.stringify(recording.format)} is not 2. Capture it again.`); -} -const plain = recordedTree('plain'); -const honorModal = recordedTree('honorModal'); - -// The checks RecordedAlertSurface.load makes: each node decodes, its index is its position, and its -// parent comes before it. An empty honor-modal tree is left to the reading, which names it. -function recordedTree(name: string): RecordedNode[] { - const tree = recording[name]; - if (!Array.isArray(tree) || (tree.length === 0 && name === 'plain')) { - fail(`${file}: "${name}" is not a tree`); - } - tree.forEach((node, position) => { - if (node.parentIndex === null) delete node.parentIndex; - const parent = node.parentIndex; - const isValid = - node.index === position && - (parent === undefined - ? position === 0 - : Number.isInteger(parent) && parent >= 0 && parent < position) && - ['element', 'type', 'identifier', 'label'].every((key) => typeof node[key] === 'string') && - isRect(node.rect); - if (!isValid) fail(`${file}: "${name}" node ${position} does not load. Capture it again.`); - }); - return tree; -} - -function isRect(rect: Record | null): boolean { - if (typeof rect !== 'object' || rect === null) return false; - const flags = [rect.infinite, rect.nonFinite]; - if (flags.some((flag) => flag != null && typeof flag !== 'boolean')) return false; - return ( - flags.includes(true) || - ['x', 'y', 'width', 'height'].every((key) => typeof rect[key] === 'number') - ); -} - -// CGRect equality compares rects after it makes their sizes positive. -function frameKey({ infinite, nonFinite, x, y, width, height }: Rect): string { - if (infinite) return 'infinite'; - if (nonFinite) return 'nonFinite'; - const origin = [width < 0 ? x + width : x, height < 0 ? y + height : y]; - return [...origin, Math.abs(width), Math.abs(height)].join(); -} - -// The rest ports ModalScopePair.pair, ModalSurface.read and its children(of:) in the same order, -// so the printed reading is the one the replay checks. The replay passes the honor-modal tree as its -// own confirming read and states that no read was truncated. -function pairInstability(): string | undefined { - const keyOf = (tree: RecordedNode[], node: RecordedNode) => - JSON.stringify([ - node.element, - node.parentIndex === undefined ? null : tree[node.parentIndex].element, - ]); - const unmatched = new Map(); - for (const node of plain) { - const key = keyOf(plain, node); - unmatched.set(key, { frame: frameKey(node.rect), count: (unmatched.get(key)?.count ?? 0) + 1 }); - } - const plainElements = new Set(plain.map((node) => node.element)); - for (const node of honorModal) { - const match = unmatched.get(keyOf(honorModal, node)); - if (!match || match.count === 0) { - const reason = plainElements.has(node.element) ? 'reparentedElement' : 'unmatchedElement'; - return `unknown(unstable(${reason})): node ${node.index}`; - } - if (match.frame !== frameKey(node.rect)) - return `unknown(unstable(movedElement)): node ${node.index}`; - match.count -= 1; - } - return undefined; -} - -// A node's parent is its nearest listed ancestor with the parent element. -function childrenOf(tree: RecordedNode[]): number[][] | undefined { - const children = tree.map((): number[] => []); - const ancestors: number[] = []; - for (const node of tree) { - if (node.parentIndex !== undefined) { - const parentElement = tree[node.parentIndex].element; - while (ancestors.length > 0 && tree[ancestors.at(-1)!].element !== parentElement) { - ancestors.pop(); - } - if (ancestors.length === 0) return undefined; - children[ancestors.at(-1)!].push(node.index); - } else if (node.index !== 0) { - return undefined; - } - ancestors.push(node.index); - } - return children; -} - -function countElements(tree: RecordedNode[], positions: number[]): Map { - const counts = new Map(); - for (const position of positions) { - counts.set(tree[position].element, (counts.get(tree[position].element) ?? 0) + 1); - } - return counts; -} - -const markers = new Map(); -function readModalSurface(): string { - const instability = pairInstability(); - if (instability) return instability; - if (plain.length === honorModal.length) return 'noExclusion'; - if (honorModal.length === 0) return 'unknown(rootMismatch): the honor-modal tree is empty'; - if (plain[0].element !== honorModal[0].element) return 'unknown(rootMismatch)'; - const plainChildren = childrenOf(plain); - const keptChildren = childrenOf(honorModal); - if (!plainChildren || !keptChildren) return 'unknown(unorderedRead)'; - let failure = ''; - - // The number of surfaces under the node, or undefined when the walk fails. - function surfaces(honorModalNode: number, plainNode: number): number | undefined { - const removed = [...plainChildren![plainNode]]; - const kept: Array<[number, number]> = []; - const listed = countElements(plain, plainChildren![plainNode]); - const keptListed = countElements(honorModal, keptChildren![honorModalNode]); - for (const child of keptChildren![honorModalNode]) { - const element = honorModal[child].element; - const listedCount = listed.get(element) ?? 0; - const keptCount = keptListed.get(element) ?? 0; - if (listedCount >= 2 && keptCount < listedCount) { - failure = `unknown(duplicatedChild): node ${honorModalNode} kept ${keptCount} of ${listedCount} children with element id ${element}`; - return undefined; - } - const match = removed.findIndex((position) => plain[position].element === element); - if (match < 0) { - failure = `unknown(unstable(reparentedElement)): node ${child}`; - return undefined; - } - kept.push([child, removed.splice(match, 1)[0]]); - } - let nested = 0; - for (const [keptChild, plainChild] of kept) { - const found = surfaces(keptChild, plainChild); - if (found === undefined) return undefined; - nested += found; - } - if (removed.length === 0 || kept.length === 0) return nested; - markers.set( - honorModalNode, - `[kept ${kept.length} of ${plainChildren![plainNode].length} children]`, - ); - return nested === 0 ? 1 : nested; - } - - const found = surfaces(0, 0); - if (found === undefined) return failure; - return found === 0 ? 'unknown(noSurvivingSurface)' : 'modal'; -} - -const reading = readModalSurface(); -console.log(`ModalSurface reads (the rule's answer, not ground truth): ${reading}`); -if (reading !== 'modal' || treeName === 'plain') markers.clear(); - -const depths: number[] = []; -for (const node of treeName === 'plain' ? plain : honorModal) { - depths[node.index] = node.parentIndex === undefined ? 0 : depths[node.parentIndex] + 1; - const marker = markers.has(node.index) ? ` ${markers.get(node.index)}` : ''; - console.log( - `${String(node.index).padStart(4)} ${' '.repeat(depths[node.index])}${node.type} ${JSON.stringify(node.label)}${marker}`, - ); -} diff --git a/test/repo-guards/apple-runner-package-source.test.ts b/test/repo-guards/apple-runner-package-source.test.ts index a15b085615..eba36376e5 100644 --- a/test/repo-guards/apple-runner-package-source.test.ts +++ b/test/repo-guards/apple-runner-package-source.test.ts @@ -77,6 +77,10 @@ test('package apple runner source strips unit-test blocks without mutating check false, ); assert.equal(fs.existsSync(path.join(root, 'dist/apple/snapshot-presentation/Tests')), false); + assert.equal( + fs.existsSync(path.join(root, 'dist/apple/snapshot-presentation/Sources/RecordingSupport')), + false, + ); assert.equal(fs.existsSync(path.join(root, 'dist/apple/runner/README.md')), false); assert.equal(fs.existsSync(path.join(root, 'dist/apple/runner/.build/cache.txt')), false); assert.equal( @@ -448,6 +452,11 @@ function writeStripFixtureTree(root: string): void { 'apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift', 'development harness\n', ); + writeFixtureFile( + root, + 'apple/snapshot-presentation/Sources/RecordingSupport/RawAlertRecording.swift', + 'development recording support\n', + ); writeFixtureFile( root, 'apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ConformanceTests.swift',