import Foundation import ParcelCore import RealityDriverSupport import Testing @testable import ParcelRealityTests extension RealityOracleTests { @Test(arguments: [nil, "0", "true", "yes"]) func desktopRequiresExactOptIn(_ flag: String?) { var environment: [String: String] = [:] environment["PARCEL_REAL_DESKTOP"] = flag #expect(throws: RealityError.self) { try RealDesktopOptions(environment: environment, fixtureSentinel: true) } } @Test(arguments: [false, true]) func desktopNoticeAuditAcceptsSilenceAndOnlyOnePostConsentCompletion(_ beforeTidy: Bool) { let completion = DesktopFeedbackEvidence.Notice( kind: "message", message: "Automatic tiling is on.", messageKind: nil) #expect(RealDesktopOracle.firstRunNotices([], beforeTidy: beforeTidy).isEmpty) #expect(RealDesktopOracle.firstRunNotices([completion], beforeTidy: beforeTidy).isEmpty == !beforeTidy) #expect(!RealDesktopOracle.firstRunNotices([completion, completion], beforeTidy: beforeTidy).isEmpty) for notice in [ DesktopFeedbackEvidence.Notice(kind: "tilesMerged", message: nil, messageKind: nil), .init(kind: "retiled", message: nil, messageKind: nil), .init(kind: "message", message: "Shortcut conflicts", messageKind: nil), .init(kind: "message", message: completion.message, messageKind: "failure"), ] { #expect(!RealDesktopOracle.firstRunNotices([notice], beforeTidy: beforeTidy).isEmpty) } } @Test func desktopIsNeverSelectedByDefault() throws { #expect(!RealityScenario.selected(named: nil).contains { $0.name == "real-desktop-first-run" }) #expect(RealityScenario.selected(named: "real-desktop-first-run").count == 1) let options = try RealDesktopOptions(environment: ["PARCEL_REAL_DESKTOP": "1"], fixtureSentinel: false) #expect(!options.fixtures && !options.keepState) #expect(options.tidyInput == .ax && options.tidyDelaySeconds == 0) } @Test(arguments: [0, 1, 300]) func desktopMouseTidyAndBoundedDwellAreExplicit(_ seconds: Int) throws { let options = try RealDesktopOptions( environment: [ "PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_TIDY_INPUT": "mouse", "PARCEL_REAL_DESKTOP_TIDY_DELAY_SECONDS": String(seconds), ], fixtureSentinel: false) #expect(options.tidyInput == .mouse && options.tidyDelaySeconds == seconds) } @Test(arguments: ["", "-1", "301", "1.5", "nan", "inf", " 1", "1", "99999999999999999999"]) func desktopRejectsUnboundedOrMalformedDwell(_ value: String) { #expect(throws: RealityError.self) { try RealDesktopOptions( environment: ["PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_TIDY_DELAY_SECONDS": value], fixtureSentinel: false) } } @Test(arguments: ["", "AX", "click", "keyboard"]) func desktopRejectsUnknownTidyInput(_ value: String) { #expect(throws: RealityError.self) { try RealDesktopOptions( environment: ["PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_TIDY_INPUT": value], fixtureSentinel: false) } } @Test func desktopFixtureProofRequiresSentinel() throws { let environment = [ "PARCEL_REAL_DESKTOP": "1", "PARCEL_REAL_DESKTOP_FIXTURES": "1", "PARCEL_REAL_DESKTOP_KEEP_STATE": "1", ] #expect(throws: RealityError.self) { try RealDesktopOptions(environment: environment, fixtureSentinel: false) } let options = try RealDesktopOptions(environment: environment, fixtureSentinel: true) #expect(options.fixtures && options.keepState) } private func desktopWindow(_ id: UInt32 = 1, frame: ScreenRect? = nil, spaces: [UInt64] = [7], pid: Int32 = 42) -> DesktopWindow { DesktopWindow( id: id, owner: "Example | App", title: "Document\nTitle", pid: pid, frame: frame ?? ScreenRect(x: 0, y: 0, width: 400, height: 500), layer: 0, spaces: spaces) } @Test func desktopDetectsSpaceLossDisappearanceAndPIDReuse() { let original = desktopWindow() #expect(RealDesktopOracle.changes(before: [original], after: [original], frames: true).isEmpty) for current in [desktopWindow(spaces: [8]), desktopWindow(spaces: []), desktopWindow(pid: 99)] { #expect(!RealDesktopOracle.changes(before: [original], after: [current], frames: false).isEmpty) } #expect(!RealDesktopOracle.changes(before: [original], after: [], frames: false).isEmpty) } @Test func desktopRollbackMeasuresAllFourFrameComponents() { let original = desktopWindow() for frame in [ ScreenRect(x: 2, y: 0, width: 400, height: 500), ScreenRect(x: 0, y: 2, width: 400, height: 500), ScreenRect(x: 0, y: 0, width: 402, height: 500), ScreenRect(x: 0, y: 0, width: 400, height: 502), ] { #expect( !RealDesktopOracle.changes(before: [original], after: [desktopWindow(frame: frame)], frames: true) .isEmpty) #expect( RealDesktopOracle.changes(before: [original], after: [desktopWindow(frame: frame)], frames: false) .isEmpty) } } @Test(arguments: ["Window Server", "Example App"], [0, 2_147_483_630]) func desktopCaptureIndicatorMayExpireWithoutExemptingAppWindows(owner: String, layer: Int) { let indicator = DesktopWindow( id: 9, owner: owner, title: "StatusIndicator", pid: 378, frame: ScreenRect(x: 1355, y: 9, width: 10, height: 19), layer: layer, spaces: []) let failures = RealDesktopOracle.changes(before: [indicator], after: [], frames: true) #expect(failures.isEmpty == (owner == "Window Server" && layer > 0)) let other = DesktopWindow( id: 10, owner: owner, title: "Other", pid: 378, frame: indicator.frame, layer: layer, spaces: []) #expect(!RealDesktopOracle.changes(before: [other], after: [], frames: true).isEmpty) } @Test func desktopSeparatesTilesByIdentityRatherThanEqualFrames() { let managed = [1, 2].map { DesktopManagedWindow(id: UInt32($0), pid: 42, floating: false, target_frame: nil, minimum: nil) } let visible = [ScreenRect(x: 0, y: 0, width: 900, height: 600)] let separate = DesktopWorkspace( active: true, tiles: .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(WindowID(rawValue: 1))), second: .tile(WindowStack(WindowID(rawValue: 2))))) let windows = [desktopWindow(), desktopWindow(2)] let stacked = DesktopWorkspace( active: true, tiles: .tile(WindowStack(WindowID(rawValue: 1), others: [WindowID(rawValue: 2)]))) #expect( RealDesktopOracle.layout(windows: windows, managed: managed, workspaces: [stacked], visible: visible) .isEmpty) #expect( !RealDesktopOracle.layout(windows: windows, managed: managed, workspaces: [separate], visible: visible) .isEmpty) let apart = [desktopWindow(), desktopWindow(2, frame: ScreenRect(x: 410, y: 0, width: 400, height: 500))] #expect( RealDesktopOracle.layout(windows: apart, managed: managed, workspaces: [separate], visible: visible).isEmpty ) #expect( !RealDesktopOracle.layout( windows: apart, managed: managed, workspaces: [separate], visible: [visible[0].inset(20)] ).isEmpty) #expect( !RealDesktopOracle.layout(windows: [], managed: managed, workspaces: [separate], visible: visible).isEmpty) #expect(!RealDesktopOracle.layout(windows: apart, managed: managed, workspaces: [], visible: visible).isEmpty) } @Test func desktopReportsRequestedAndActualMinimumSizes() throws { let model = try JSONDecoder().decode( DesktopManagedWindow.self, from: Data( """ {"id":1,"pid":42,"floating":false, "target_frame":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"width":200,"height":300}}, "minimum":{"schemaVersion":1,"size":{"width":400,"height":500}}} """.utf8)) let rows = RealDesktopOracle.sizeReadbacks(windows: [desktopWindow()], managed: [model]) #expect(rows.count == 1) #expect(rows.first?.requested.width == 200) #expect(rows.first?.actual.width == 400) #expect(rows.first?.minimum?.height == 500) #expect(RealDesktopOracle.sizeReadbacks(windows: [desktopWindow(pid: 99)], managed: [model]).isEmpty) } @Test func desktopReportEscapesPrivateWindowTextAndRoundTrips() throws { var report = RealDesktopReport() report.before = [desktopWindow()] report.failures = ["Tidy failed"] #expect(report.markdown.contains("IN PROGRESS")) report.completed = true let decoded = try JSONDecoder().decode(RealDesktopReport.self, from: JSONEncoder().encode(report)) #expect(decoded.before == report.before) #expect(decoded.markdown.contains("Example | App / Document Title")) #expect(decoded.markdown.contains("FAIL")) #expect(decoded.markdown.contains("Tidy failed")) } @Test func desktopCaptureRequiresOptInAndAbsoluteDestination() throws { #expect(throws: DriverError.self) { try DriverCommand.captureDesktop(directory: "/private/evidence", optedIn: false).validate() } #expect(throws: DriverError.self) { try DriverCommand.captureDesktop(directory: "relative", optedIn: true).validate() } let request = DriverRequest(id: 1, command: .captureDesktop(directory: "/private/evidence", optedIn: true)) #expect(try DriverWire.decodeRequest(JSONEncoder().encode(request)) == request) } @Test @MainActor func desktopBackupRestoresDefaultsFilesAndAbsence() throws { try withDesktopBackup { home, evidence, domain, defaults in let state = home.appendingPathComponent("Library/Application Support/dev.vinnymac.parcel") try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) try Data("original".utf8).write(to: state.appendingPathComponent("memory.json")) defaults.setPersistentDomain(["onboardingCompleted": true, "languages": ["de"]], forName: domain) let backup = try RealDesktopStateBackup(home: home, directory: evidence, domain: domain) try backup.reset() #expect(defaults.persistentDomain(forName: domain) == nil) #expect(!FileManager.default.fileExists(atPath: state.path)) let config = home.appendingPathComponent(".config/parcel") try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) try Data("generated".utf8).write(to: config.appendingPathComponent("parcel.toml")) defaults.set("changed", forKey: "languages") try backup.restore(keepState: false) #expect(try String(contentsOf: state.appendingPathComponent("memory.json"), encoding: .utf8) == "original") #expect(!FileManager.default.fileExists(atPath: config.path)) #expect(defaults.stringArray(forKey: "languages") == ["de"]) #expect(defaults.bool(forKey: "onboardingCompleted")) try backup.restore(keepState: false) } } @Test @MainActor func desktopBackupKeepsOnlyExplicitlyRequestedState() throws { try withDesktopBackup { home, evidence, domain, defaults in let backup = try RealDesktopStateBackup(home: home, directory: evidence, domain: domain) try backup.reset() defaults.set(true, forKey: "generated") try backup.restore(keepState: true) #expect(defaults.bool(forKey: "generated")) try backup.restore(keepState: false) #expect(defaults.persistentDomain(forName: domain) == nil) } } @Test @MainActor func desktopBackupRejectsRedirectedStateWithoutChangingIt() throws { try withDesktopBackup { home, evidence, domain, defaults in let outside = home.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) let config = home.appendingPathComponent(".config") try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) try FileManager.default.createSymbolicLink( at: config.appendingPathComponent("parcel"), withDestinationURL: outside) defaults.set(true, forKey: "keep") #expect(throws: RealityError.self) { try RealDesktopStateBackup(home: home, directory: evidence, domain: domain) } #expect(defaults.bool(forKey: "keep")) #expect(FileManager.default.fileExists(atPath: outside.path)) } } @Test @MainActor func desktopReportsResolveFromCheckoutAndWorktree() throws { try withDesktopBackup { root, _, _, _ in let checkout = root.appendingPathComponent("checkout") let worktree = root.appendingPathComponent("worktrees/task") #expect(throws: RealityError.self) { try RealDesktopPaths.notesDirectory(repository: checkout) } let notes = root.appendingPathComponent("tessera-notes") try FileManager.default.createDirectory(at: notes, withIntermediateDirectories: true) #expect(try RealDesktopPaths.notesDirectory(repository: checkout).path == notes.path) #expect(try RealDesktopPaths.notesDirectory(repository: worktree).path == notes.path) } } @Test @MainActor func desktopBackupRestoresOtherStateWhenOnePathIsRedirected() throws { try withDesktopBackup { home, evidence, domain, defaults in let state = home.appendingPathComponent("Library/Application Support/dev.vinnymac.parcel") let config = home.appendingPathComponent(".config/parcel") let outside = home.appendingPathComponent("outside") for path in [state, config, outside] { try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) } try Data("saved".utf8).write(to: state.appendingPathComponent("memory.json")) defaults.set(true, forKey: "saved") let backup = try RealDesktopStateBackup(home: home, directory: evidence, domain: domain) try backup.reset() try FileManager.default.createSymbolicLink(at: config, withDestinationURL: outside) #expect(throws: RealityError.self) { try backup.restore(keepState: false) } #expect(defaults.bool(forKey: "saved")) #expect(try String(contentsOf: state.appendingPathComponent("memory.json"), encoding: .utf8) == "saved") #expect(FileManager.default.fileExists(atPath: evidence.appendingPathComponent("manifest.json").path)) try FileManager.default.removeItem(at: config) try backup.restore(keepState: false) #expect(FileManager.default.fileExists(atPath: config.path)) } } @Test func desktopRetainsExactAdjustmentRequestsFromWhy() throws { let data = Data( """ {"id":1,"frame_adjustment":{"requested":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"width":200,"height":300}},"accepted":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"width":400,"height":500}}}} """.utf8) let inspection = try JSONDecoder().decode(DesktopInspection.self, from: data) #expect(inspection.frame_adjustment?.requested.size.width == 200) #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 == .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, 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( 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(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)) 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 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( 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 | "] 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 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")? .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() try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) let domain = "dev.vinnymac.parcel.reality-unit-\(UUID())" let defaults = try #require(UserDefaults(suiteName: domain)) do { try body(root, root.appendingPathComponent("backup"), domain, defaults) } catch { defaults.removePersistentDomain(forName: domain) try FileManager.default.removeItem(at: root) throw error } defaults.removePersistentDomain(forName: domain) try FileManager.default.removeItem(at: root) } }