diff --git a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift index 1baefeb8..99965b91 100644 --- a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift +++ b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift @@ -231,6 +231,162 @@ extension RealityOracleTests { #expect(inspection.frame_adjustment?.accepted.size.width == 400) } + @Test func desktopUnseenWindowCannotEscapeMembershipOrOverlap() { + let one = desktopWindow() + let two = desktopWindow(2) + let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) + let audits = [ + RealDesktopOracle.audit(window: one, tiledIDs: [1], inspection: nil, skipped: [], why: "standard"), + RealDesktopOracle.audit(window: two, tiledIDs: [1], inspection: nil, skipped: [], why: "unmanaged"), + ] + let failures = RealDesktopOracle.layout( + windows: [one, two], + managed: [DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil)], + workspaces: [workspace], visible: [ScreenRect(x: 0, y: 0, width: 1000, height: 800)], audits: audits) + #expect(failures.contains { $0.contains("unmanaged") }) + #expect(failures.contains { $0.contains("overlap") }) + } + + @Test func desktopExplicitTidySkipDoesNotExcuseAnOverlap() { + let one = desktopWindow() + let two = desktopWindow(2) + let audit = RealDesktopOracle.audit( + window: two, tiledIDs: [1], inspection: nil, + skipped: [DesktopSkippedApplication(pid: 42, bundleID: "dev.example.app", reason: "unresponsive")], + why: "unmanaged") + #expect(audit.tidyException == "dev.example.app: unresponsive") + let managed = [DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil)] + let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) + let visible = [ScreenRect(x: 0, y: 0, width: 1000, height: 800)] + let failures = RealDesktopOracle.layout( + windows: [one, two], managed: managed, workspaces: [workspace], visible: visible, audits: [audit]) + #expect(failures.count == 1 && failures[0].contains("overlap")) + let apart = desktopWindow(2, frame: ScreenRect(x: 500, y: 0, width: 400, height: 500)) + #expect( + RealDesktopOracle.layout( + windows: [one, apart], managed: managed, workspaces: [workspace], visible: visible, audits: [audit] + ).isEmpty) + } + + @Test(arguments: [ + ClassificationReason.panel, .fixedSize, .defaultFloatApp(bundleID: "dev.example.float"), + .rule(index: 0, bundleID: "dev.example.float"), + ]) + func desktopKnownFloatingExemptionsNeedWhyEvidence(_ reason: ClassificationReason) { + let inspection = DesktopInspection( + id: 2, frame_adjustment: nil, disposition: .float, classification_reason: reason) + #expect(inspection.knownFloating) + #expect( + RealDesktopOracle.audit( + window: desktopWindow(2), tiledIDs: [1], inspection: inspection, skipped: [], why: "float" + ).membership == .floating) + } + + @Test(arguments: [ClassificationReason.standardWindow, .whenFull, .manual, .nativeTab]) + func desktopOrdinaryFloatsAreNotKnownFloatingClasses(_ reason: ClassificationReason) { + let inspection = DesktopInspection( + id: 2, frame_adjustment: nil, disposition: .float, classification_reason: reason) + #expect(!inspection.knownFloating) + #expect( + RealDesktopOracle.audit( + window: desktopWindow(2), tiledIDs: [1], inspection: inspection, skipped: [], why: "float" + ).membership == .unmanaged) + } + + @Test func desktopKnownFloatDoesNotParticipateInOverlap() { + let audit = DesktopWindowAudit(id: 2, pid: 42, membership: .floating, why: "fixed", tidyException: nil) + let model = DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil) + let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) + #expect( + RealDesktopOracle.layout( + windows: [desktopWindow(), desktopWindow(2)], managed: [model], workspaces: [workspace], + visible: [ScreenRect(x: 0, y: 0, width: 1000, height: 800)], audits: [audit] + ).isEmpty) + } + + @Test func desktopCGScopeRequiresRegularNormalActiveOnscreenWindows() { + let row = desktopWindow() + #expect(RealDesktopOracle.candidate(row, activeSpaces: [7], regularPIDs: [42])) + #expect(!RealDesktopOracle.candidate(row, activeSpaces: [8], regularPIDs: [42])) + #expect(!RealDesktopOracle.candidate(row, activeSpaces: [7], regularPIDs: [43])) + var offscreen = row + offscreen.onscreen = false + #expect(!RealDesktopOracle.candidate(offscreen, activeSpaces: [7], regularPIDs: [42])) + let tiny = desktopWindow(frame: ScreenRect(x: 0, y: 0, width: 100, height: 500)) + #expect(!RealDesktopOracle.candidate(tiny, activeSpaces: [7], regularPIDs: [42])) + let elevated = DesktopWindow( + id: 2, owner: "Example", title: nil, pid: 42, frame: row.frame, layer: 1, spaces: [7]) + #expect(!RealDesktopOracle.candidate(elevated, activeSpaces: [7], regularPIDs: [42])) + } + + @Test func desktopAbsentAXIdentityStaysInAuditAndProbeMetadataRoundTrips() throws { + #expect( + RealDesktopOracle.probeCandidates(candidates: [1, 2, 3], standard: [1], identified: [1, 2]) == [1, 3]) + let response = DriverResponse(id: 1, windowIDs: [1], identifiedWindowIDs: [1, 2]) + #expect(try JSONDecoder().decode(DriverResponse.self, from: JSONEncoder().encode(response)) == response) + } + + @Test func desktopWhyNotFoundIsUnmanagedButOtherErrorsAreFailures() { + #expect( + RealDesktopOracle.unknownWindow( + CommandOutput(status: 1, output: "", errors: "window_not_found: Window not found."))) + #expect(!RealDesktopOracle.unknownWindow(CommandOutput(status: 1, output: "", errors: "timed_out"))) + #expect(!RealDesktopOracle.unknownWindow(CommandOutput(status: 0, output: "", errors: "window_not_found"))) + } + + @Test func desktopPlatformFailuresAreScopedToOwnedParcelPIDs() { + let log = """ + Parcel[100:abc] EnginePlatformFailure.appThread(AppID(pid: 42), cause: alreadyOwned(42)) + Parcel[100:abc] EnginePlatformFailure.appUnavailable(AppID(pid: 42)) + Parcel[101:abc] EnginePlatformFailure.appThread(AppID(pid: 42)) + Parcel[100:abc] Tidy skipped-app pid=42 reason=unresponsive + """ + #expect(RealDesktopOracle.platformFailures(log: log, pids: [100]).count == 2) + #expect(RealDesktopOracle.platformFailures(log: log, pids: []).isEmpty) + } + + @Test func desktopInjectionCannotRunAgainstRealApps() throws { + #expect(throws: RealityError.self) { + try RealDesktopOptions( + environment: ["PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_INJECT_UNMANAGED": "1"], + fixtureSentinel: true) + } + let options = try RealDesktopOptions( + environment: [ + "PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_FIXTURES": "1", + "PARCEL_REAL_DESKTOP_INJECT_UNMANAGED": "1", + ], fixtureSentinel: true) + #expect(options.injectUnmanagedFixture) + } + + @Test func desktopPrivateManagerListRejectsMalformedData() throws { + #expect( + try RealDesktopOracle.managerBundleIDs(Data("[\"dev.example.manager\"]".utf8)) == ["dev.example.manager"]) + for json in ["[]", "[\"\"]", "[\"not-an-id\"]", "[\"dev.example. bad\"]", "{}"] { + #expect(throws: (any Error).self) { try RealDesktopOracle.managerBundleIDs(Data(json.utf8)) } + } + } + + @Test func desktopSummaryShowsMembershipStacksExceptionsAndPromptLimitations() { + var report = RealDesktopReport() + report.audits = [ + DesktopWindowAudit(id: 1, pid: 42, membership: .tiled, why: "standard", tidyException: nil), + DesktopWindowAudit(id: 2, pid: 42, membership: .floating, why: "fixed", tidyException: nil), + DesktopWindowAudit(id: 3, pid: 43, membership: .unmanaged, why: "unmanaged", tidyException: "unresponsive"), + ] + report.stacks = [DesktopStack(tile: 1, members: [1, 4])] + report.prompts = ["Notice | "] + let markdown = report.markdown + #expect(markdown.contains("1 tiled / 1 known-floating / 1 unmanaged")) + #expect(markdown.contains("1 → [1, 4]")) + #expect(markdown.contains("Notice | <example>")) + #expect(markdown.contains("manual review")) + #expect(markdown.contains("Incomplete: no private")) + #expect( + markdown.range(of: "## Summary")?.lowerBound ?? markdown.endIndex < markdown.range(of: "| ID / PID")? + .lowerBound ?? markdown.startIndex) + } + @MainActor private func withDesktopBackup(_ body: (URL, URL, String, UserDefaults) throws -> Void) throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("parcel-desktop-test-\(UUID())") .resolvingSymlinksInPath() diff --git a/Tests/Reality/RealDesktopEvidence.swift b/Tests/Reality/RealDesktopEvidence.swift index 20fffdef..580b8ec4 100644 --- a/Tests/Reality/RealDesktopEvidence.swift +++ b/Tests/Reality/RealDesktopEvidence.swift @@ -79,6 +79,44 @@ struct DesktopInspection: Codable { } let id: UInt32 let frame_adjustment: Adjustment? + var disposition: WindowDisposition? + var classification_reason: ClassificationReason? + var reason: String? + + var knownFloating: Bool { + guard disposition == .float, let classification_reason else { return false } + switch classification_reason { + case .standardWindow, .manual, .whenFull, .nativeTab: return false + default: return true + } + } +} + +struct DesktopWindowAudit: Codable, Equatable { + enum Membership: String, Codable { case tiled, floating, unmanaged } + let id: UInt32 + let pid: Int32 + let membership: Membership + let why: String + let tidyException: String? +} + +struct DesktopSkippedApplication: Codable { + let pid: Int32 + let bundleID: String + let reason: String +} + +struct DesktopTourEvidence: Decodable { + let skippedApplications: [DesktopSkippedApplication] + let noticeTitle: String? + let noticeIsVisible: Bool + let visibleSetupText: [String] +} + +struct DesktopStack: Codable { + let tile: Int + let members: [UInt32] } enum RealDesktopOracle { @@ -106,7 +144,7 @@ enum RealDesktopOracle { static func layout( windows: [DesktopWindow], managed: [DesktopManagedWindow], - workspaces: [DesktopWorkspace], visible: [ScreenRect] + workspaces: [DesktopWorkspace], visible: [ScreenRect], audits: [DesktopWindowAudit]? = nil ) -> [String] { let stacks = workspaces.filter(\.active).flatMap { $0.tiles?.stacks ?? [] } let tiledIDs = Set(stacks.flatMap { $0.windows.map(\.rawValue) }) @@ -125,18 +163,77 @@ enum RealDesktopOracle { } observed.append(row) } + let auditedIDs = Set( + audits?.filter { $0.membership != .floating }.map(\.id) + ?? windows.filter { + $0.layer == 0 && $0.onscreen && $0.frame.width > 100 && $0.frame.height > 100 + }.map(\.id)) + for audit in audits ?? [] + where audit.membership != .floating && !tiledIDs.contains(audit.id) + && audit.tidyException == nil + { + failures.append( + "Standard window \(audit.id) (pid \(audit.pid)) is unmanaged and absent from the Tidy outcome: \(audit.why)" + ) + } + for row in windows where auditedIDs.contains(row.id) && !observed.contains(where: { $0.id == row.id }) { + observed.append(row) + } for (index, row) in observed.enumerated() { for other in observed.dropFirst(index + 1) where !row.frame.separated(from: other.frame, gap: 0, tolerance: tolerance) { let sameStack = stacks.contains { $0.windows.contains(WindowID(rawValue: row.id)) && $0.windows.contains(WindowID(rawValue: other.id)) } - if !sameStack { failures.append("Distinct tiles \(row.id) and \(other.id) overlap") } + if !sameStack { + failures.append("Standard windows \(row.id) and \(other.id) overlap outside a shared tile") + } } } return failures } + static func audit( + window: DesktopWindow, tiledIDs: Set, inspection: DesktopInspection?, + skipped: [DesktopSkippedApplication], why: String + ) -> DesktopWindowAudit { + let membership: DesktopWindowAudit.Membership = + tiledIDs.contains(window.id) ? .tiled : inspection?.knownFloating == true ? .floating : .unmanaged + return DesktopWindowAudit( + id: window.id, pid: window.pid, membership: membership, why: why, + tidyException: skipped.first { $0.pid == window.pid }.map { "\($0.bundleID): \($0.reason)" }) + } + + static func platformFailures(log: String, pids: Set) -> [String] { + log.components(separatedBy: .newlines).filter { line in + (line.contains("appUnavailable(") || line.contains("appThread(")) + && pids.contains { line.contains("Parcel[\($0):") } + } + } + + static func candidate(_ row: DesktopWindow, activeSpaces: Set, regularPIDs: Set) -> Bool { + row.layer == 0 && row.onscreen && row.frame.isValid && row.frame.width > 100 && row.frame.height > 100 + && regularPIDs.contains(row.pid) && !activeSpaces.isDisjoint(with: row.spaces) + } + + static func probeCandidates(candidates: [UInt32], standard: [UInt32], identified: [UInt32]) -> Set { + // An absent AX identity is unknown, not proof that a normal CG window is auxiliary. + Set(standard).union(Set(candidates).subtracting(identified)) + } + + static func unknownWindow(_ output: CommandOutput) -> Bool { + output.status != 0 && output.errors.contains("window_not_found") + } + + static func managerBundleIDs(_ data: Data) throws -> Set { + let ids = try JSONDecoder().decode([String].self, from: data) + guard !ids.isEmpty, ids.allSatisfy({ !$0.isEmpty && $0.contains(".") && !$0.contains(where: \.isWhitespace) }) + else { + throw RealityError("Window-manager watch list must contain nonempty bundle IDs") + } + return Set(ids) + } + static func sizeReadbacks(windows: [DesktopWindow], managed: [DesktopManagedWindow]) -> [DesktopSizeReadback] { managed.compactMap { model in guard let target = model.target_frame, @@ -160,6 +257,16 @@ struct RealDesktopReport: Codable { var restored: [DesktopWindow] = [] var sizeReadbacks: [DesktopSizeReadback] = [] var inspections: [DesktopInspection] = [] + var audits: [DesktopWindowAudit] = [] + var stacks: [DesktopStack] = [] + var skippedApplications: [DesktopSkippedApplication] = [] + var prompts: [String] = [] + var promptCheckpoints: [String] = [] + var runningBundleIDs: [String] = [] + var competingManagers: [String] = [] + var managerDetection = "Incomplete: no private bundle-ID watch list configured" + var platformFailures: [String] = [] + var injectedUnmanagedWindow: UInt32? var completed = false var screenshots: [String] = [] var failures: [String] = [] @@ -181,8 +288,43 @@ struct RealDesktopReport: Codable { "Result: \(!completed ? "IN PROGRESS" : failures.isEmpty ? "PASS" : "FAIL"). Fixtures: \(fixtures). Tidy: \(tidyOutcome ?? "unobserved"). " text += "Automatic tiling: \(automaticTiling.map(String.init) ?? "unobserved"). State restored: \(stateRestored). Keep state: \(keepState).\n\n" + text += "## Summary\n\n" + text += + "Windows: \(audits.filter { $0.membership == .tiled }.count) tiled / \(audits.filter { $0.membership == .floating }.count) known-floating / \(audits.filter { $0.membership == .unmanaged }.count) unmanaged. Counts cover independently identified regular standard windows.\n\n" + text += + "Stacks (tile → member windows): " + + (stacks.isEmpty ? "unobserved" : stacks.map { "\($0.tile) → \($0.members)" }.joined(separator: "; ")) + + ".\n\n" + let refusals = inspections.filter { inspection in + guard let adjustment = inspection.frame_adjustment else { return false } + return abs(adjustment.requested.size.width - adjustment.accepted.size.width) > RealDesktopOracle.tolerance + || abs(adjustment.requested.size.height - adjustment.accepted.size.height) > RealDesktopOracle.tolerance + } + text += "Size refusal receipts: \(refusals.count). " + text += + refusals.map { inspection in + guard let adjustment = inspection.frame_adjustment else { return "Unknown receipt" } + let actual = after.first { $0.id == inspection.id }.map { String(describing: $0.frame) } ?? "unobserved" + return + "\(inspection.id): requested \(adjustment.requested); accepted \(adjustment.accepted); final CG \(actual)" + }.joined(separator: "; ") + "\n\n" + text += + "Parcel prompts/notifications observed: " + + (prompts.isEmpty ? "none at sampled checkpoints" : prompts.map(escape).joined(separator: "; ")) + ". " + text += + "Sampled tour/notice text and available CG titles at \(promptCheckpoints.map(escape).joined(separator: ", ")). Screenshots need manual review for untitled system prompts; this is not continuous notification coverage.\n\n" + text += + "Competing managers: " + + (competingManagers.isEmpty ? "none matched" : competingManagers.map(escape).joined(separator: ", ")) + + ". \(escape(managerDetection)). [Running bundle IDs](running-applications.json).\n\n" + text += "Platform failure lines: \(platformFailures.count).\n\n" + text += "| Window / PID | Membership | prcl why | Tidy exception |\n| --- | --- | --- | --- |\n" + for audit in audits { + text += + "| \(audit.id) / \(audit.pid) | \(audit.membership.rawValue) | [\(escape(audit.why))](why-\(audit.id).json) | \(escape(audit.tidyException ?? "none")) |\n" + } text += - "Rollback: \(rollback). Missing titles mean CG withheld them. All geometry is in points; tolerance is 1 point.\n\n" + "\nRollback: \(rollback). Missing titles mean CG withheld them. All geometry is in points; tolerance is 1 point.\n\n" text += "| ID / PID | Owner / title | Layer | Before / Spaces | After / Spaces | Rollback / Spaces |\n| --- | --- | --- | --- | --- | --- |\n" for row in before { diff --git a/Tests/Reality/RealDesktopState.swift b/Tests/Reality/RealDesktopState.swift index b13c59de..2fa810ba 100644 --- a/Tests/Reality/RealDesktopState.swift +++ b/Tests/Reality/RealDesktopState.swift @@ -18,6 +18,7 @@ enum RealDesktopPaths { struct RealDesktopOptions: Equatable { let fixtures: Bool let keepState: Bool + let injectUnmanagedFixture: Bool init(environment: [String: String], fixtureSentinel: Bool) throws { guard environment["PARCEL_REAL_DESKTOP"] == "1" else { @@ -25,6 +26,10 @@ struct RealDesktopOptions: Equatable { } fixtures = environment["PARCEL_REAL_DESKTOP_FIXTURES"] == "1" keepState = environment["PARCEL_REAL_DESKTOP_KEEP_STATE"] == "1" + injectUnmanagedFixture = environment["PARCEL_REAL_DESKTOP_INJECT_UNMANAGED"] == "1" + guard !injectUnmanagedFixture || fixtures else { + throw RealityError("Unmanaged-window injection is permitted only in the fixture variant") + } guard !fixtures || fixtureSentinel else { throw RealityError("Fixture proof requires /tmp/parcel-m3-free and an unlocked console") } diff --git a/Tests/RealityDriver/DriverAX.swift b/Tests/RealityDriver/DriverAX.swift index 5323c2c0..e9d1af65 100644 --- a/Tests/RealityDriver/DriverAX.swift +++ b/Tests/RealityDriver/DriverAX.swift @@ -96,8 +96,10 @@ final class DriverAXApplication { self.element = try DriverAXElement(AXUIElementCreateApplication(pid)) } - func standardWindowIDs(candidates: Set) throws -> (ids: [UInt32], warnings: [String]) { + func standardWindowIDs(candidates: Set) throws -> (ids: [UInt32], identified: [UInt32], warnings: [String]) + { var roles: [DriverWindowRole] = [] + var identified: [UInt32] = [] var warnings: [String] = [] for window in try element.elements(kAXWindowsAttribute) { let id: UInt32 @@ -110,12 +112,13 @@ final class DriverAXApplication { } guard candidates.contains(id) else { continue } let role = try window.string(kAXRoleAttribute) + identified.append(id) guard role == kAXWindowRole else { continue } let subrole = try window.string(kAXSubroleAttribute) if subrole == kAXStandardWindowSubrole { try DriverWindowMetadata.requireOwner(pid: pid, windowID: id) } roles.append(DriverWindowRole(windowID: id, role: role, subrole: subrole)) } - return (try DriverWindowSelection.standardWindowIDs(roles), warnings) + return (try DriverWindowSelection.standardWindowIDs(roles), identified.sorted(), warnings) } func register(windowID: UInt32) throws -> [String] { diff --git a/Tests/RealityDriver/DriverServer.swift b/Tests/RealityDriver/DriverServer.swift index b08ddb1e..e7b9c54f 100644 --- a/Tests/RealityDriver/DriverServer.swift +++ b/Tests/RealityDriver/DriverServer.swift @@ -128,7 +128,9 @@ final class DriverPipeServer { let worker = workers[pid] ?? DriverAppThread(pid: pid) workers[pid] = worker let result = try worker.perform { try $0.standardWindowIDs(candidates: Set(candidates)) } - return DriverResponse(id: id, identificationWarnings: result.warnings, windowIDs: result.ids) + return DriverResponse( + id: id, identificationWarnings: result.warnings, windowIDs: result.ids, + identifiedWindowIDs: result.identified) case .key(let key, let flags, let expectation): let target = try inputTarget() inputReceipts = [DriverInputReceipt(target: target, outcome: "attempted", virtualKey: key)] diff --git a/Tests/RealityDriverSupport/DriverProtocol.swift b/Tests/RealityDriverSupport/DriverProtocol.swift index 65669d52..5f151f6d 100644 --- a/Tests/RealityDriverSupport/DriverProtocol.swift +++ b/Tests/RealityDriverSupport/DriverProtocol.swift @@ -53,6 +53,7 @@ public struct DriverResponse: Codable, Sendable, Equatable { public let identificationWarnings: [String]? public let dragFrames: [DriverFrame]? public let windowIDs: [UInt32]? + public let identifiedWindowIDs: [UInt32]? public let input: [DriverInputReceipt]? public let inputState: DriverInputState? public let tourPress: DriverTourPressReceipt? @@ -62,7 +63,8 @@ public struct DriverResponse: Codable, Sendable, Equatable { increments: DriverIncrements? = nil, chords: [DriverChord]? = nil, captures: [DriverCapture]? = nil, frame: DriverFrame? = nil, nodes: [DriverAXNode]? = nil, identificationWarnings: [String]? = nil, dragFrames: [DriverFrame]? = nil, windowIDs: [UInt32]? = nil, input: [DriverInputReceipt]? = nil, - inputState: DriverInputState? = nil, tourPress: DriverTourPressReceipt? = nil + inputState: DriverInputState? = nil, tourPress: DriverTourPressReceipt? = nil, + identifiedWindowIDs: [UInt32]? = nil ) { self.id = id self.error = error @@ -75,6 +77,7 @@ public struct DriverResponse: Codable, Sendable, Equatable { self.identificationWarnings = identificationWarnings self.dragFrames = dragFrames self.windowIDs = windowIDs + self.identifiedWindowIDs = identifiedWindowIDs self.input = input self.inputState = inputState self.tourPress = tourPress -- knotmirror 0.0.1 From c7aef35d361d40690c370ff07d34d6baaf990c52 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 6 Nov 2026 22:34:20 -0500 Subject: [PATCH 2/3] Capture and verify final desktop evidence Signed-off-by: Vincent Taverna --- .../RealDesktopTests.swift | 24 ++++ Tests/Reality/README.md | 32 ++++- Tests/Reality/RealDesktopAudit.swift | 122 ++++++++++++++++++ Tests/Reality/RealDesktopEvidence.swift | 11 ++ Tests/Reality/RealDesktopFirstRun.swift | 113 ++++++++++++---- Tests/Reality/RealityFixture.swift | 11 ++ 6 files changed, 282 insertions(+), 31 deletions(-) create mode 100644 Tests/Reality/RealDesktopAudit.swift diff --git a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift index 99965b91..1647d46a 100644 --- a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift +++ b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift @@ -345,6 +345,30 @@ extension RealityOracleTests { #expect(RealDesktopOracle.platformFailures(log: log, pids: []).isEmpty) } + @Test func desktopLogCaptureDoesNotTruncateTheFinalFractionalSecond() { + let arguments = RealDesktopOracle.logArguments(started: Date(timeIntervalSince1970: 100.75)) + #expect(arguments.contains("--start")) + #expect(arguments.contains("--debug")) + #expect(!arguments.contains("--end")) + } + + @Test func desktopFinalSnapshotCatchesAWindowArrivingAfterSettling() { + let model = DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil) + let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) + let first = desktopWindow() + let visible = [ScreenRect(x: 0, y: 0, width: 1000, height: 800)] + #expect( + RealDesktopOracle.layout(windows: [first], managed: [model], workspaces: [workspace], visible: visible) + .isEmpty) + let newcomer = desktopWindow(2, pid: 99) + let audit = RealDesktopOracle.audit( + window: newcomer, tiledIDs: [1], inspection: nil, skipped: [], why: "window_not_found") + let failures = RealDesktopOracle.layout( + windows: [first, newcomer], managed: [model], workspaces: [workspace], visible: visible, audits: [audit]) + #expect(failures.contains { $0.contains("unmanaged") }) + #expect(failures.contains { $0.contains("overlap") }) + } + @Test func desktopInjectionCannotRunAgainstRealApps() throws { #expect(throws: RealityError.self) { try RealDesktopOptions( diff --git a/Tests/Reality/README.md b/Tests/Reality/README.md index 3f05532d..44f638cb 100644 --- a/Tests/Reality/README.md +++ b/Tests/Reality/README.md @@ -463,8 +463,9 @@ PARCEL_REAL_DESKTOP=1 mise run reality -- --scenario real-desktop-first-run It is excluded from default runs, even with the opt-in set. Quit Parcel first; keep the console unlocked. The wrapper takes the shared screen lock. Accessibility -and Screen Recording must already be granted to `build/Parcel.app`; the scenario -never opens a permission prompt. It presses only Parcel's AX tour controls: +must already be granted to `build/Parcel.app`; Screen Recording belongs to the +terminal harness. Screenshots use `/usr/sbin/screencapture -x`, never the +Parcel-hosted driver, so this scenario cannot request direct-capture consent for Parcel. It presses only Parcel's AX tour controls: Automatic, Continue, Tidy. It never posts input to, quits, or closes other apps. Before launching the product, it records every on-screen CG window, including @@ -477,7 +478,15 @@ is left alone. Only read-only tour status is exposed by the additional IPC guard Full-screen `screencapture` images follow each tour step, settling and rollback. CG frames and native Space reads verify bounds, distinct tile separation and -restoration within one point. Members of the same model stack may overlap. +restoration within one point. Every regular, normal-size, onscreen layer-0 window +on an active Space receives an independent AX role probe and `prcl why` receipt. +Unknown AX identities remain candidates; `window_not_found` is recorded as +unmanaged, not skipped. Except for known-floating classes identified by `why`, +each candidate must be tiled or have an explicit application skip in the Tidy +outcome. All candidate overlaps fail, including explicitly skipped windows; +only members of the same tile may overlap. Any owned Parcel `appUnavailable` or +`appThread` failure line within the run fails, even if the final frames fit. +Fixture mode audits only owned fixture windows while protecting existing apps. The harness samples requested frames, actual CG frames and learned minimum sizes; a transient mismatch is reported as a readback, not asserted to be a refusal. Vanished windows, changed ownership, Space changes and off-screen transitions fail. @@ -508,4 +517,21 @@ PARCEL_REAL_DESKTOP=1 PARCEL_REAL_DESKTOP_FIXTURES=1 \ mise run reality -- --scenario real-desktop-first-run ``` +Add `PARCEL_REAL_DESKTOP_INJECT_UNMANAGED=1` for negative proof. It creates a +seventh standard fixture window outside the isolated title rule; ordinary +membership/overlap assertions must make that run fail. Injection is refused +without fixture mode and the sentinel. It never targets a real app. + +The report starts with tiled/floating/unmanaged counts, tile member IDs, size +refusal receipts with final CG frames, and sampled Parcel notices/prompts. +Untitled system prompts still need manual screenshot review; the report does not +claim continuous notification observation. + +A private JSON array of competing utility bundle IDs can live at +`qa/real-desktop/window-manager-bundle-ids.json` in the private notes directory, +or set `PARCEL_REAL_DESKTOP_MANAGER_BUNDLE_IDS` to an absolute JSON file path. +Matches are noted without changing or quitting those apps. Without a list, +detection is explicitly incomplete; all running bundle IDs are retained privately. +Never put that list or utility names in this repository. + The fixture variant proves the harness, not success on the user's actual desktop. diff --git a/Tests/Reality/RealDesktopAudit.swift b/Tests/Reality/RealDesktopAudit.swift new file mode 100644 index 00000000..26d96eb4 --- /dev/null +++ b/Tests/Reality/RealDesktopAudit.swift @@ -0,0 +1,122 @@ +import AppKit +import CoreGraphics +import Foundation +import ParcelCore +import ParcelPlatform +import RealityDriverSupport + +@MainActor +func desktopStandardWindows( + _ session: RealitySession, rows: [DesktopWindow], fixturePIDs: Set?, directory: URL +) async throws -> [DesktopWindow] { + let active = Set(try await NativeSpaceReader().snapshot().map(\.currentSpace)) + let regular = Set( + NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular }.map(\.processIdentifier)) + let candidates = rows.filter { + $0.pid != session.parcel?.processIdentifier + && RealDesktopOracle.candidate($0, activeSpaces: active, regularPIDs: regular) + && (fixturePIDs == nil || fixturePIDs?.contains($0.pid) == true) + } + var standard: Set = [] + for pid in Set(candidates.map(\.pid)).sorted() { + let response = try await session.driver.send( + .standardWindows(pid: pid, candidates: candidates.filter { $0.pid == pid }.map(\.id))) + try encodeJSON(response, to: directory.appendingPathComponent("standard-windows-\(pid).json")) + guard let ids = response.windowIDs, let identified = response.identifiedWindowIDs else { + throw RealityError("Missing independent standard-window probe for pid \(pid)") + } + standard.formUnion( + RealDesktopOracle.probeCandidates( + candidates: candidates.filter { $0.pid == pid }.map(\.id), standard: ids, identified: identified)) + } + return candidates.filter { standard.contains($0.id) } +} + +@MainActor +func desktopAudit( + _ session: RealitySession, windows: [DesktopWindow], workspaces: [DesktopWorkspace], + skipped: [DesktopSkippedApplication], directory: URL +) async throws -> (audits: [DesktopWindowAudit], inspections: [DesktopInspection]) { + let tiled = Set( + workspaces.filter(\.active).flatMap { $0.tiles?.stacks ?? [] }.flatMap { $0.windows.map(\.rawValue) }) + var audits: [DesktopWindowAudit] = [] + var inspections: [DesktopInspection] = [] + for window in windows { + let result = try await session.cli(["why", "--json", String(window.id)]) + try encodeJSON(result, to: directory.appendingPathComponent("why-\(window.id).json")) + let inspection: DesktopInspection? + let why: String + if result.status == 0 { + let value = try JSONDecoder().decode(DesktopInspection.self, from: Data(result.output.utf8)) + guard value.id == window.id else { + throw RealityError("Window \(window.id) returned a different diagnostic identity") + } + inspection = value + inspections.append(value) + why = value.reason ?? "No classification explanation" + } else if RealDesktopOracle.unknownWindow(result) { + inspection = nil + why = "unmanaged: Parcel has not observed this window (window_not_found)" + } else { + throw RealityError("Window \(window.id) diagnostic failed: \(result.errors)") + } + audits.append( + RealDesktopOracle.audit(window: window, tiledIDs: tiled, inspection: inspection, skipped: skipped, why: why) + ) + } + return (audits, inspections) +} + +@MainActor +func desktopTourEvidence(_ session: RealitySession, stage: String, directory: URL) async throws -> DesktopTourEvidence { + let result = try await session.cli(["run", "--json", "e2e-tour", "status"]) + try encodeJSON(result, to: directory.appendingPathComponent("tour-\(stage).json")) + guard result.status == 0 else { throw RealityError("Desktop tour evidence failed: \(result.errors)") } + return try JSONDecoder().decode(DesktopTourEvidence.self, from: Data(result.output.utf8)) +} + +@MainActor +func desktopScreenshot(directory: URL) async throws -> [String] { + // Preflight never requests access; capture remains the terminal harness's responsibility. + guard CGPreflightScreenCaptureAccess() else { + throw RealityError( + "Desktop screenshots need an existing Screen Recording grant for the terminal harness, not Parcel") + } + let count = NSScreen.screens.count + guard count > 0 else { throw RealityError("No displays available for desktop screenshots") } + var paths: [String] = [] + for display in 1...count { + let file = "display-\(display).png" + let target = directory.appendingPathComponent(file) + let result = try await RealityProcess.run( + "/usr/sbin/screencapture", ["-x", "-D", String(display), target.path], directory: directory) + try encodeJSON(result, to: directory.appendingPathComponent("receipt-\(display).json")) + guard result.status == 0 else { throw RealityError("Harness screenshot failed: \(result.errors)") } + let data = try Data(contentsOf: target) + guard data.count > 8, Array(data.prefix(8)) == [137, 80, 78, 71, 13, 10, 26, 10] else { + throw RealityError("Harness screenshot did not produce a PNG for display \(display)") + } + paths.append(file) + } + return paths +} + +@MainActor +func desktopManagerEvidence(environment: [String: String], notes: URL, report: inout RealDesktopReport) throws { + report.runningBundleIDs = Array(Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier))).sorted() + let path = environment["PARCEL_REAL_DESKTOP_MANAGER_BUNDLE_IDS"] + guard path == nil || path?.hasPrefix("/") == true else { + throw RealityError("Private window-manager watch list requires an absolute path") + } + let file = + path.map { URL(fileURLWithPath: $0) } + ?? notes.appendingPathComponent("qa/real-desktop/window-manager-bundle-ids.json") + if path == nil && !FileManager.default.fileExists(atPath: file.path) { return } + guard file.path.hasPrefix("/"), file.standardizedFileURL == file.resolvingSymlinksInPath().standardizedFileURL + else { + throw RealityError("Private window-manager watch list must be an unredirected absolute path") + } + let watched = try RealDesktopOracle.managerBundleIDs(Data(contentsOf: file)) + report.competingManagers = report.runningBundleIDs.filter { watched.contains($0) } + report.managerDetection = "Matched a private bundle-ID watch list; running utilities may fight Parcel" +} diff --git a/Tests/Reality/RealDesktopEvidence.swift b/Tests/Reality/RealDesktopEvidence.swift index 580b8ec4..c23dc06f 100644 --- a/Tests/Reality/RealDesktopEvidence.swift +++ b/Tests/Reality/RealDesktopEvidence.swift @@ -204,6 +204,17 @@ enum RealDesktopOracle { tidyException: skipped.first { $0.pid == window.pid }.map { "\($0.bundleID): \($0.reason)" }) } + static func logArguments(started: Date) -> [String] { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + // Parcel is stopped before capture; omitting --end includes its entire final fractional second. + return [ + "show", "--start", formatter.string(from: started), "--style", "compact", "--info", "--debug", + "--predicate", "subsystem == \"dev.vinnymac.parcel\"", + ] + } + static func platformFailures(log: String, pids: Set) -> [String] { log.components(separatedBy: .newlines).filter { line in (line.contains("appUnavailable(") || line.contains("appThread(")) diff --git a/Tests/Reality/RealDesktopFirstRun.swift b/Tests/Reality/RealDesktopFirstRun.swift index df21e816..82f1c2f9 100644 --- a/Tests/Reality/RealDesktopFirstRun.swift +++ b/Tests/Reality/RealDesktopFirstRun.swift @@ -26,6 +26,25 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool var backup: RealDesktopStateBackup? var resetCompleted = false var fixtures: [OwnedWindow] = [] + var parcelPIDs: Set = [] + + func observePrompts(_ stage: String) async throws { + guard session.parcel != nil else { return } + let evidence = try await desktopTourEvidence(session, stage: stage, directory: directory) + report.skippedApplications = evidence.skippedApplications + if !report.promptCheckpoints.contains(stage) { report.promptCheckpoints.append(stage) } + if evidence.noticeIsVisible, let title = evidence.noticeTitle { + let prompt = "\(stage): Parcel notice: \(title)" + if !report.prompts.contains(prompt) { report.prompts.append(prompt) } + } + for row in try await DesktopWindow.read() where !report.before.contains(where: { $0.id == row.id }) { + if let title = row.title, title.localizedCaseInsensitiveContains("Parcel"), + row.pid != session.parcel?.processIdentifier + { + report.prompts.append("\(stage): \(row.owner): \(title)") + } + } + } func checkCancellation() throws { guard !interrupted() else { throw RealityError("Interrupted; rolling back Parcel and restoring state") } @@ -37,20 +56,19 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool try FileManager.default.createDirectory( at: target, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) - let response = try await session.driver.send(.captureDesktop(directory: target.path, optedIn: true)) - guard let captures = response.captures, !captures.isEmpty else { - throw RealityError("Missing full-screen screenshot") - } - report.screenshots += captures.map { "\(stage)/\(URL(fileURLWithPath: $0.path).lastPathComponent)" } - try encodeJSON(response, to: target.appendingPathComponent("receipt.json")) + report.screenshots += try await desktopScreenshot(directory: target).map { "\(stage)/\($0)" } + try await observePrompts(stage) try report.write(to: directory) } do { try checkCancellation() - let permission = try await session.driver.preflight() - guard permission.screenRecording else { - throw RealityError("Full-desktop screenshots need an existing Screen Recording grant for build/Parcel.app") + _ = try await session.driver.preflight() + guard CGPreflightScreenCaptureAccess() else { + throw RealityError( + "Full-desktop screenshots need an existing Screen Recording grant for the terminal harness, not Parcel") } + try desktopManagerEvidence(environment: environment, notes: notes, report: &report) + try encodeJSON(report.runningBundleIDs, to: directory.appendingPathComponent("running-applications.json")) if options.fixtures { try session.configure(layout: "grid", cap: 4) fixtures = try await session.startingWindows(Array(repeating: .fixture, count: 6)) @@ -60,6 +78,15 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool frame: ScreenRect( x: session.visible.x + 20, y: session.visible.y + 20, width: 600, height: height + 40)) try await session.apps.fixture(for: fixtures[0]).configureTidy(clampHeight: height) + if options.injectUnmanagedFixture { + guard let injected = try await session.startingWindows([.fixture]).first else { + throw RealityError("Missing owned unmanaged fixture launch") + } + fixtures.append(injected) + try await session.apps.fixture(for: injected).setTitle("UnmanagedFixture-\(UUID())") + report.injectedUnmanagedWindow = injected.id + try encodeJSON(injected, to: directory.appendingPathComponent("injected-unmanaged.json")) + } } report.before = try await DesktopWindow.read() try encodeJSON(report.before, to: directory.appendingPathComponent("before.json")) @@ -77,6 +104,7 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool } else { try await session.startRealDesktop() } + if let pid = session.parcel?.processIdentifier { parcelPIDs.insert(pid) } try await waitNativeTour(session, step: "welcome") try await capture("00-welcome") for (control, step, stage) in [ @@ -110,8 +138,34 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool let workspaces: [DesktopWorkspace] = try await desktopQuery(session, "workspaces", directory: directory) for readback in RealDesktopOracle.sizeReadbacks(windows: report.after, managed: managed) where !report.sizeReadbacks.contains(readback) { report.sizeReadbacks.append(readback) } + try await observePrompts("settling") + let standard = try await desktopStandardWindows( + session, rows: report.after, fixturePIDs: options.fixtures ? Set(fixtures.map(\.pid)) : nil, + directory: directory) + let evidence = try await desktopAudit( + session, windows: standard, workspaces: workspaces, skipped: report.skippedApplications, + directory: directory) + report.audits = evidence.audits + report.inspections = evidence.inspections + report.stacks = workspaces.filter(\.active).flatMap { $0.tiles?.stacks ?? [] }.enumerated().map { + DesktopStack(tile: $0.offset + 1, members: $0.element.windows.map(\.rawValue)) + } layoutFailures = RealDesktopOracle.layout( - windows: report.after, managed: managed, workspaces: workspaces, visible: visible) + windows: report.after, managed: managed, workspaces: workspaces, visible: visible, audits: report.audits + ) + if options.injectUnmanagedFixture, !status.isBusy, status.terminal == "success" { + guard + report.audits.contains(where: { + $0.id == report.injectedUnmanagedWindow && $0.membership == .unmanaged + }) + else { + throw RealityError("Injected unmanaged fixture was not independently observed as unmanaged") + } + if !layoutFailures.isEmpty { + report.failures += layoutFailures + throw RealityError("Tidy failed the standard-window assertions: \(layoutFailures)") + } + } if !status.isBusy, let terminal = status.terminal, terminal != "none", terminal != "success" { throw RealityError("Tidy outcome: \(terminal); \(status.visibleSetupText)") } @@ -143,17 +197,25 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool if let parcel = session.parcel, !parcel.isTerminated { do { + let workspaces: [DesktopWorkspace] = try await desktopQuery(session, "workspaces", directory: directory) let managed: [DesktopManagedWindow] = try await desktopQuery(session, "windows", directory: directory) - for window in managed { - let result = try await session.cli(["why", "--json", String(window.id)]) - try encodeJSON(result, to: directory.appendingPathComponent("why-\(window.id).json")) - guard result.status == 0 else { - throw RealityError("Window \(window.id) diagnostic failed: \(result.errors)") - } - report.inspections.append( - try JSONDecoder().decode(DesktopInspection.self, from: Data(result.output.utf8))) + report.after = try await DesktopWindow.read(tracking: Set(report.before.map(\.id))) + let standard = try await desktopStandardWindows( + session, rows: report.after, + fixturePIDs: options.fixtures ? Set(fixtures.map(\.pid)) : nil, directory: directory) + let evidence = try await desktopAudit( + session, windows: standard, workspaces: workspaces, skipped: report.skippedApplications, + directory: directory) + report.audits = evidence.audits + report.inspections = evidence.inspections + report.stacks = workspaces.filter(\.active).flatMap { $0.tiles?.stacks ?? [] }.enumerated().map { + DesktopStack(tile: $0.offset + 1, members: $0.element.windows.map(\.rawValue)) } - } catch { report.failures.append("Size diagnostics: \(error)") } + report.failures += RealDesktopOracle.layout( + windows: report.after, managed: managed, workspaces: workspaces, visible: desktopVisibleFrames(), + audits: report.audits) + report.failures += RealDesktopOracle.changes(before: report.before, after: report.after, frames: false) + } catch { report.failures.append("Window diagnostics: \(error)") } } if !report.failures.isEmpty, let parcel = session.parcel, !parcel.isTerminated { @@ -189,18 +251,13 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool "Safety stop: Parcel is still running; saved state retained in state-backup for manual recovery") } do { - let formatter = DateFormatter() - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let logs = try await RealityProcess.run( - "/usr/bin/log", - [ - "show", "--start", formatter.string(from: started), - "--end", formatter.string(from: Date()), "--style", "compact", "--info", "--debug", "--predicate", - "subsystem == \"dev.vinnymac.parcel\"", - ], directory: directory, timeout: .seconds(30)) + "/usr/bin/log", RealDesktopOracle.logArguments(started: started), directory: directory, + timeout: .seconds(30)) try Data(logs.output.utf8).write(to: directory.appendingPathComponent("parcel.log"), options: .atomic) guard logs.status == 0 else { throw RealityError("log show failed: \(logs.errors)") } + report.platformFailures = RealDesktopOracle.platformFailures(log: logs.output, pids: parcelPIDs) + report.failures += report.platformFailures.map { "Parcel platform failure during run: \($0)" } } catch { report.failures.append("Log capture: \(error)") } report.completed = true try report.write(to: directory) diff --git a/Tests/Reality/RealityFixture.swift b/Tests/Reality/RealityFixture.swift index b556ecb2..c312f27a 100644 --- a/Tests/Reality/RealityFixture.swift +++ b/Tests/Reality/RealityFixture.swift @@ -59,6 +59,17 @@ final class RealityFixture { return try await send(["id": id, "action": action], id: id) } + func setTitle(_ title: String) async throws { + struct Request: Encodable { + let id: String + let action = "title" + let window = 1 + let title: String + } + let id = UUID().uuidString + _ = try await send(Request(id: id, title: title), id: id) + } + func configureTidy(clampHeight: Double? = nil, adjustNextFrame: Bool = false) async throws { struct Request: Encodable { let id: String -- knotmirror 0.0.1 From 960605e276f3665360db35e4b986b3a0d8c01dc1 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 6 Nov 2026 23:08:43 -0500 Subject: [PATCH 3/3] Separate window states and report existing dialogs Signed-off-by: Vincent Taverna --- .../RealDesktopTests.swift | 62 ++++++++++++++++++- Tests/Reality/RealDesktopEvidence.swift | 37 +++++++++-- Tests/Reality/RealDesktopFirstRun.swift | 16 +++-- 3 files changed, 101 insertions(+), 14 deletions(-) diff --git a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift index 1647d46a..de86a2ec 100644 --- a/Tests/ParcelRealitySupportTests/RealDesktopTests.swift +++ b/Tests/ParcelRealitySupportTests/RealDesktopTests.swift @@ -290,11 +290,32 @@ extension RealityOracleTests { #expect( RealDesktopOracle.audit( window: desktopWindow(2), tiledIDs: [1], inspection: inspection, skipped: [], why: "float" - ).membership == .unmanaged) + ).membership == .floating) + #expect( + !RealDesktopOracle.audit( + window: desktopWindow(2), tiledIDs: [1], inspection: inspection, skipped: [], why: "float" + ).knownFloating) + } + + @Test func desktopOverflowFloatIsCountedAsFloatingButStillNeedsATidyException() { + let one = desktopWindow() + let two = desktopWindow(2, frame: ScreenRect(x: 500, y: 0, width: 400, height: 500), pid: 99) + let inspection = DesktopInspection( + id: 2, frame_adjustment: nil, disposition: .float, classification_reason: .whenFull) + let audit = RealDesktopOracle.audit( + window: two, tiledIDs: [1], inspection: inspection, skipped: [], why: "workspace full") + let model = DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil) + let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) + let failures = RealDesktopOracle.layout( + windows: [one, two], managed: [model], workspaces: [workspace], + visible: [ScreenRect(x: 0, y: 0, width: 1000, height: 800)], audits: [audit]) + #expect(audit.membership == .floating && !audit.knownFloating) + #expect(failures.count == 1 && failures[0].contains("absent from the Tidy outcome")) } @Test func desktopKnownFloatDoesNotParticipateInOverlap() { - let audit = DesktopWindowAudit(id: 2, pid: 42, membership: .floating, why: "fixed", tidyException: nil) + let audit = DesktopWindowAudit( + id: 2, pid: 42, membership: .floating, why: "fixed", tidyException: nil, knownFloating: true) let model = DesktopManagedWindow(id: 1, pid: 42, floating: false, target_frame: nil, minimum: nil) let workspace = DesktopWorkspace(active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1)))) #expect( @@ -334,6 +355,34 @@ extension RealityOracleTests { #expect(!RealDesktopOracle.unknownWindow(CommandOutput(status: 0, output: "", errors: "window_not_found"))) } + @Test(arguments: [true, false]) + func desktopUntitledSystemDialogsRecordWhetherTheyPredateTheProduct(_ preexisting: Bool) throws { + let row = DesktopWindow( + id: 9, owner: "UserNotificationCenter", title: "", pid: 100, frame: desktopWindow().frame, layer: 8, + spaces: [7]) + let observation = try #require(RealDesktopOracle.promptObservation(row, baselineIDs: preexisting ? [9] : [])) + #expect(observation.contains(preexisting ? "present before product launch" : "appeared during run")) + #expect(observation.contains("untitled system surface")) + #expect(observation.contains("window 9, pid 100")) + } + + @Test func desktopPromptObservationDoesNotInventAnUnseenDialog() { + #expect(RealDesktopOracle.promptObservation(desktopWindow(), baselineIDs: []) == nil) + let document = DesktopWindow( + id: 10, owner: "Example", title: "Parcel document", pid: 100, frame: desktopWindow().frame, layer: 0, + spaces: [7]) + #expect(RealDesktopOracle.promptObservation(document, baselineIDs: [10]) == nil) + let overlay = DesktopWindow( + id: 11, owner: "Example", title: "Parcel notice", pid: 100, frame: desktopWindow().frame, layer: 8, + spaces: [7]) + #expect(RealDesktopOracle.promptObservation(overlay, baselineIDs: [])?.contains("appeared during run") == true) + var offscreen = DesktopWindow( + id: 9, owner: "UserNotificationCenter", title: "Parcel", pid: 100, frame: desktopWindow().frame, layer: 8, + spaces: [7]) + offscreen.onscreen = false + #expect(RealDesktopOracle.promptObservation(offscreen, baselineIDs: []) == nil) + } + @Test func desktopPlatformFailuresAreScopedToOwnedParcelPIDs() { let log = """ Parcel[100:abc] EnginePlatformFailure.appThread(AppID(pid: 42), cause: alreadyOwned(42)) @@ -400,11 +449,18 @@ extension RealityOracleTests { ] report.stacks = [DesktopStack(tile: 1, members: [1, 4])] report.prompts = ["Notice | "] + report.sizeReadbacks = [ + DesktopSizeReadback( + id: 7, requested: ScreenRect(x: 0, y: 0, width: 200, height: 300), + actual: ScreenRect(x: 0, y: 0, width: 400, height: 500), minimum: nil) + ] let markdown = report.markdown - #expect(markdown.contains("1 tiled / 1 known-floating / 1 unmanaged")) + #expect(markdown.contains("1 tiled / 1 floating / 1 unmanaged")) #expect(markdown.contains("1 → [1, 4]")) #expect(markdown.contains("Notice | <example>")) #expect(markdown.contains("manual review")) + #expect(markdown.contains("7: 200.0 × 300.0 → 400.0 × 500.0")) + #expect(markdown.contains("not confirmed refusals")) #expect(markdown.contains("Incomplete: no private")) #expect( markdown.range(of: "## Summary")?.lowerBound ?? markdown.endIndex < markdown.range(of: "| ID / PID")? diff --git a/Tests/Reality/RealDesktopEvidence.swift b/Tests/Reality/RealDesktopEvidence.swift index c23dc06f..5d67fb42 100644 --- a/Tests/Reality/RealDesktopEvidence.swift +++ b/Tests/Reality/RealDesktopEvidence.swift @@ -99,6 +99,7 @@ struct DesktopWindowAudit: Codable, Equatable { let membership: Membership let why: String let tidyException: String? + var knownFloating = false } struct DesktopSkippedApplication: Codable { @@ -164,16 +165,16 @@ enum RealDesktopOracle { observed.append(row) } let auditedIDs = Set( - audits?.filter { $0.membership != .floating }.map(\.id) + audits?.filter { !$0.knownFloating }.map(\.id) ?? windows.filter { $0.layer == 0 && $0.onscreen && $0.frame.width > 100 && $0.frame.height > 100 }.map(\.id)) for audit in audits ?? [] - where audit.membership != .floating && !tiledIDs.contains(audit.id) + where !audit.knownFloating && !tiledIDs.contains(audit.id) && audit.tidyException == nil { failures.append( - "Standard window \(audit.id) (pid \(audit.pid)) is unmanaged and absent from the Tidy outcome: \(audit.why)" + "Standard window \(audit.id) (pid \(audit.pid)) is \(audit.membership.rawValue), not tiled and absent from the Tidy outcome: \(audit.why)" ) } for row in windows where auditedIDs.contains(row.id) && !observed.contains(where: { $0.id == row.id }) { @@ -198,10 +199,22 @@ enum RealDesktopOracle { skipped: [DesktopSkippedApplication], why: String ) -> DesktopWindowAudit { let membership: DesktopWindowAudit.Membership = - tiledIDs.contains(window.id) ? .tiled : inspection?.knownFloating == true ? .floating : .unmanaged + tiledIDs.contains(window.id) ? .tiled : inspection?.disposition == .float ? .floating : .unmanaged return DesktopWindowAudit( id: window.id, pid: window.pid, membership: membership, why: why, - tidyException: skipped.first { $0.pid == window.pid }.map { "\($0.bundleID): \($0.reason)" }) + tidyException: skipped.first { $0.pid == window.pid }.map { "\($0.bundleID): \($0.reason)" }, + knownFloating: inspection?.knownFloating == true) + } + + static func promptObservation(_ row: DesktopWindow, baselineIDs: Set) -> String? { + let systemDialog = row.owner == "UserNotificationCenter" || row.owner == "NotificationCenter" + let titledOverlay = row.layer > 0 && row.title?.localizedCaseInsensitiveContains("Parcel") == true + guard row.onscreen, systemDialog || titledOverlay else { + return nil + } + let origin = baselineIDs.contains(row.id) ? "present before product launch" : "appeared during run" + let title = row.title.flatMap { $0.isEmpty ? nil : $0 } ?? "untitled system surface; inspect screenshot" + return "\(row.owner) window \(row.id), pid \(row.pid), \(origin): \(title)" } static func logArguments(started: Date) -> [String] { @@ -301,7 +314,7 @@ struct RealDesktopReport: Codable { "Automatic tiling: \(automaticTiling.map(String.init) ?? "unobserved"). State restored: \(stateRestored). Keep state: \(keepState).\n\n" text += "## Summary\n\n" text += - "Windows: \(audits.filter { $0.membership == .tiled }.count) tiled / \(audits.filter { $0.membership == .floating }.count) known-floating / \(audits.filter { $0.membership == .unmanaged }.count) unmanaged. Counts cover independently identified regular standard windows.\n\n" + "Windows: \(audits.filter { $0.membership == .tiled }.count) tiled / \(audits.filter { $0.membership == .floating }.count) floating / \(audits.filter { $0.membership == .unmanaged }.count) unmanaged. Counts cover regular standard-window candidates, including unknown AX identities. Known-floating exclusions: \(audits.filter(\.knownFloating).count).\n\n" text += "Stacks (tile → member windows): " + (stacks.isEmpty ? "unobserved" : stacks.map { "\($0.tile) → \($0.members)" }.joined(separator: "; ")) @@ -319,6 +332,18 @@ struct RealDesktopReport: Codable { return "\(inspection.id): requested \(adjustment.requested); accepted \(adjustment.accepted); final CG \(actual)" }.joined(separator: "; ") + "\n\n" + let mismatches = sizeReadbacks.filter { + abs($0.requested.width - $0.actual.width) > RealDesktopOracle.tolerance + || abs($0.requested.height - $0.actual.height) > RealDesktopOracle.tolerance + } + let mismatchIDs = Set(mismatches.map(\.id)).sorted() + text += "Sampled size mismatches (requested → actual; may be in-flight, not confirmed refusals): " + text += + mismatchIDs.compactMap { id in + mismatches.first { $0.id == id }.map { + "\(id): \($0.requested.width) × \($0.requested.height) → \($0.actual.width) × \($0.actual.height)" + } + }.joined(separator: "; ") + "\n\n" text += "Parcel prompts/notifications observed: " + (prompts.isEmpty ? "none at sampled checkpoints" : prompts.map(escape).joined(separator: "; ")) + ". " diff --git a/Tests/Reality/RealDesktopFirstRun.swift b/Tests/Reality/RealDesktopFirstRun.swift index 82f1c2f9..a2f998db 100644 --- a/Tests/Reality/RealDesktopFirstRun.swift +++ b/Tests/Reality/RealDesktopFirstRun.swift @@ -27,6 +27,7 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool var resetCompleted = false var fixtures: [OwnedWindow] = [] var parcelPIDs: Set = [] + var observedPromptWindows: Set = [] func observePrompts(_ stage: String) async throws { guard session.parcel != nil else { return } @@ -37,11 +38,12 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool let prompt = "\(stage): Parcel notice: \(title)" if !report.prompts.contains(prompt) { report.prompts.append(prompt) } } - for row in try await DesktopWindow.read() where !report.before.contains(where: { $0.id == row.id }) { - if let title = row.title, title.localizedCaseInsensitiveContains("Parcel"), - row.pid != session.parcel?.processIdentifier + let baselineIDs = Set(report.before.map(\.id)) + for row in try await DesktopWindow.read() where row.pid != session.parcel?.processIdentifier { + if let prompt = RealDesktopOracle.promptObservation(row, baselineIDs: baselineIDs), + observedPromptWindows.insert(row.id).inserted { - report.prompts.append("\(stage): \(row.owner): \(title)") + report.prompts.append("\(stage): \(prompt)") } } } @@ -257,7 +259,11 @@ func checkRealDesktopFirstRun(_ session: RealitySession, interrupted: () -> Bool try Data(logs.output.utf8).write(to: directory.appendingPathComponent("parcel.log"), options: .atomic) guard logs.status == 0 else { throw RealityError("log show failed: \(logs.errors)") } report.platformFailures = RealDesktopOracle.platformFailures(log: logs.output, pids: parcelPIDs) - report.failures += report.platformFailures.map { "Parcel platform failure during run: \($0)" } + if let first = report.platformFailures.first { + report.failures.append( + "Parcel logged \(report.platformFailures.count) appThread/appUnavailable failures during the run; first: \(first). See parcel.log for all lines" + ) + } } catch { report.failures.append("Log capture: \(error)") } report.completed = true try report.write(to: directory)