Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341import AppKitimport Foundation
struct SetupLaunchReceipt: Codable, Sendable { let requestedBundleID: String let applicationURL: URL let preexistingPIDs: [Int32] let pid: Int32 let bundleID: String? let bundleURL: URL? let launchDate: Double? let isTerminated: Bool
func notesReceipt( applicationURL expectedURL: URL, preexistingPIDs baseline: Set<Int32>, requestedAt: Date, respondedAt: Date, liveLaunchDate: Date? ) throws -> RealAppLaunchReceipt { guard requestedBundleID == RealApp.notes.bundleID, applicationURL.isFileURL, expectedURL.isFileURL, applicationURL.resolvingSymlinksInPath().standardizedFileURL == expectedURL.resolvingSymlinksInPath().standardizedFileURL, let launchDate, launchDate.isFinite, requestedAt <= respondedAt, launchDate >= requestedAt.timeIntervalSince1970, launchDate <= respondedAt.timeIntervalSince1970, let liveLaunchDate, liveLaunchDate.timeIntervalSince1970 == launchDate else { throw RealityError("Setup receipt does not prove a fresh requested Notes launch") } // Preserve the live Date's exact representation after checking the wire timestamp. let receipt = RealAppLaunchReceipt( app: .notes, applicationURL: expectedURL, preexistingPIDs: baseline.union(preexistingPIDs).sorted(), pid: pid, bundleID: bundleID, bundleURL: bundleURL, isTerminated: isTerminated, launchDate: liveLaunchDate) _ = try receipt.validatedPID() return receipt }}
struct SetupOpenReceipt: Decodable, Sendable { let accepted: Bool let launches: [SetupLaunchReceipt]
func notesLaunch() throws -> SetupLaunchReceipt { guard accepted, launches.count == 1, let launch = launches.first, launch.requestedBundleID == RealApp.notes.bundleID else { throw RealityError("Safety stop: setup open did not return exactly one requested Notes launch receipt") } return launch }}
enum SetupRealitySafety { static let calculatorIgnoreRule = """
[[rules]] bundle-id = "\(RealApp.calculator.bundleID)" action = "ignore"
"""
private struct Storage: Decodable { struct Setup: Decodable { struct Memory: Decodable { struct Record: Decodable { struct Window: Decodable { let bundleID: String } let windows: [Window] } let records: [Record] } let name: String let hideOtherApps: Bool let memory: Memory? } let version: Int let setups: [Setup] }
static func requireHideSetting(_ data: Data, name: String, hideOtherApps: Bool) throws { let storage = try JSONDecoder().decode(Storage.self, from: data) guard storage.version == 1, storage.setups.count == 1, let setup = storage.setups.first, setup.name == name, setup.hideOtherApps == hideOtherApps else { throw RealityError( "Safety stop: isolated setup was not saved with hideOtherApps=\(hideOtherApps); refusing open") } }
static func requireOwnedApplications(_ data: Data, name: String) throws { let storage = try JSONDecoder().decode(Storage.self, from: data) guard storage.version == 1, storage.setups.count == 1, let setup = storage.setups.first, setup.name == name, let memory = setup.memory, Set(memory.records.flatMap { $0.windows.map(\.bundleID) }) == Set([RealApp.textEdit.bundleID, RealApp.notes.bundleID]) else { throw RealityError("Safety stop: setup contains unexpected applications; refusing unowned unhide or launch") } }
static func focusedWindow( _ rows: [RealWindow], window: OwnedWindow, foregroundPID: Int32? ) -> Bool { guard foregroundPID == window.pid, let front = rows.first(where: { $0.pid == foregroundPID && $0.layer == 0 && $0.onscreen }) else { return false } // CG order is front-to-back, but another application's inactive window can remain above the active app. return front.id == window.id }
static func restoredFrames( _ rows: [RealWindow], textEdit: OwnedWindow, notes: OwnedWindow, saved: [ScreenRect] ) throws -> Bool { guard saved.count == 2, rows.contains(where: { $0.id == textEdit.id && $0.pid == textEdit.pid && $0.onscreen }), rows.contains(where: { $0.id == notes.id && $0.pid == notes.pid && $0.onscreen }) else { return false } let frames = try FrameOracle.frames(rows, ids: [textEdit.id, notes.id]) return frames[0].matches(saved[0]) && frames[1].matches(saved[1]) }}
struct SetupApplicationVisibility: Codable { let pid: Int32 let bundleID: String? let launchDate: Date? let hidden: Bool
@MainActor init(_ application: NSRunningApplication) { pid = application.processIdentifier bundleID = application.bundleIdentifier launchDate = application.launchDate hidden = application.isHidden }
@MainActor func requireUnchanged() throws { guard let current = NSRunningApplication(processIdentifier: pid), !current.isTerminated, current.bundleIdentifier == bundleID, current.launchDate == launchDate else { return } guard current.isHidden == hidden else { throw RealityError("Safety stop: setup changed unrelated application visibility for PID \(pid)") } }}
@MainActorextension RealityScenario { func checkSetups(_ session: RealitySession, hideOtherApps: Bool = false) async throws { if hideOtherApps { guard NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.calculator.bundleID).isEmpty else { throw RealitySkip( "Calculator is already running; hide checks require an exclusively owned throwaway app") } } guard NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.notes.bundleID).isEmpty else { throw RealitySkip("Notes is already running; Setups cannot own or reopen shared native state safely") } guard !NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.textEdit.bundleID).contains( where: \.isHidden) else { throw RealitySkip("TextEdit has a hidden existing instance; opening the setup could unhide unowned windows") } guard let notesURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: RealApp.notes.bundleID) else { throw RealitySkip("Notes is not installed") } try session.configure(layout: "columns") if hideOtherApps { // Default-floating apps are still captured by setups; ignore only this exclusive throwaway. var configuration = try Data(contentsOf: session.config) configuration.append(Data(SetupRealitySafety.calculatorIgnoreRule.utf8)) try configuration.write(to: session.config, options: .atomic) } let owned = try await session.startingWindows( hideOtherApps ? [.textEdit, .notes, .calculator] : [.textEdit, .notes]) let textEdit = owned[0] let originalNotes = owned[1] let savedWindows = [textEdit, originalNotes] let hideTarget = owned.first(where: { $0.app == .calculator }) let visibility = NSWorkspace.shared.runningApplications .filter { !session.apps.ownedProcessIDs.contains($0.processIdentifier) } .map(SetupApplicationVisibility.init) session.setupUnrelatedVisibility = visibility try encodeJSON( visibility, to: session.directory.appendingPathComponent("setup-unrelated-visibility-before.json")) try await session.start(setupHideTarget: hideTarget) try await session.expect("Owned TextEdit and Notes occupy two full-height saved columns") { FrameOracle.stripeShape( try FrameOracle.frames($0, ids: savedWindows.map(\.id)), visible: session.visible, vertical: true) } if let target = session.setupOwnedVisibility { try await session.expect("Owned Calculator stays visible at its native CG frame, outside saved tiles") { try SetupOwnedVisibility.visibleReadback( $0, window: target.window, hidden: target.isHidden(apps: session.apps), startingFrame: target.startingFrame) } } let saved = try session.readFrames(savedWindows) try encodeJSON(saved, to: session.directory.appendingPathComponent("setup-saved-cg-frames.json")) let name = "\(session.apps.token)-columns" let save = try await session.cli(["setup", "--json", "save", name] + (hideOtherApps ? [] : ["--no-hide"])) try encodeJSON(save, to: session.directory.appendingPathComponent("setup-save-response.json")) guard save.status == 0 else { throw RealityError("Setup save failed: \(save.output) \(save.errors)") } let storage = session.storage.directory.appendingPathComponent("setups.json") try SetupRealitySafety.requireHideSetting(Data(contentsOf: storage), name: name, hideOtherApps: hideOtherApps) try SetupRealitySafety.requireOwnedApplications(Data(contentsOf: storage), name: name) for application in visibility { try application.requireUnchanged() }
// Discard only the original ledger-owned Notes process, without save sheets. try await session.apps.close(originalNotes) guard NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.notes.bundleID).isEmpty else { throw RealityError("Safety stop: Notes appeared after owned discard; refusing setup open") } try await session.command("layout", "rows") try await session.expect("Rows layout leaves TextEdit expanded and different from its saved column") { guard !$0.contains(where: { $0.pid == originalNotes.pid }), let frame = $0.first(where: { $0.id == textEdit.id && $0.pid == textEdit.pid })?.frame else { return false } return frame.matches(session.visible.inset(16)) && !frame.matches(saved[0]) } try encodeJSON( try session.readFrames([textEdit]), to: session.directory.appendingPathComponent("setup-disturbed-cg-frames.json")) try session.requireProtectedFrames() try SetupRealitySafety.requireHideSetting(Data(contentsOf: storage), name: name, hideOtherApps: hideOtherApps) try SetupRealitySafety.requireOwnedApplications(Data(contentsOf: storage), name: name) guard NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.notes.bundleID).isEmpty else { throw RealityError("Safety stop: unowned Notes appeared before setup open; no reopen attempted") } guard !NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.textEdit.bundleID).contains(where: { !session.apps.ownedProcessIDs.contains($0.processIdentifier) && $0.isHidden }) else { throw RealityError("Safety stop: an unowned TextEdit instance became hidden before setup open") } if let target = session.setupOwnedVisibility { guard try !target.isHidden(apps: session.apps), SetupOwnedVisibility.visibleReadback( try FrameOracle.read(), window: target.window, hidden: false, startingFrame: target.startingFrame) else { throw RealityError("Safety stop: owned hide target was not visible immediately before setup open") } } for application in visibility { try application.requireUnchanged() } let before = try FrameOracle.read() let preexistingPIDs = Set(NSWorkspace.shared.runningApplications.map(\.processIdentifier)) .union(before.map(\.pid)).union(session.apps.ownedProcessIDs) try encodeJSON( preexistingPIDs.sorted(), to: session.directory.appendingPathComponent("setup-open-preexisting-pids.json")) let requestedAt = Date() let open: CommandOutput do { open = try await session.cli(["setup", "--json", "open", name], timeout: .seconds(25)) } catch { throw RealityError( "Safety stop: setup open returned no launch provenance; no process was adopted: \(error)") } let respondedAt = Date() try encodeJSON( ["requestedAt": requestedAt, "respondedAt": respondedAt], to: session.directory.appendingPathComponent("setup-open-request-interval.json")) try encodeJSON(open, to: session.directory.appendingPathComponent("setup-open-response.json")) guard open.status == 0 else { throw RealityError( "Safety stop: setup open failed without usable launch provenance: \(open.output) \(open.errors)") } let response: SetupOpenReceipt do { response = try JSONDecoder().decode(SetupOpenReceipt.self, from: Data(open.output.utf8)) } catch { throw RealityError( "Safety stop: setup open launch provenance is malformed; no process was adopted: \(error)") } let reopened = try await session.apps.claimReopenedNotes( response.notesLaunch(), applicationURL: notesURL, preexistingPIDs: preexistingPIDs, requestedAt: requestedAt, respondedAt: respondedAt, before: before) for application in visibility { try application.requireUnchanged() } try await session.expect("Reopened Notes and existing TextEdit regain their respective saved CG tile positions") { for application in visibility { try application.requireUnchanged() } return try SetupRealitySafety.restoredFrames($0, textEdit: textEdit, notes: reopened, saved: saved) } if let target = session.setupOwnedVisibility { try await session.expect("Only the receipt-allowlisted Calculator is hidden, independently confirmed by CG") { for application in visibility { try application.requireUnchanged() } return try SetupOwnedVisibility.hiddenReadback( $0, window: target.window, hidden: target.isHidden(apps: session.apps)) && SetupRealitySafety.restoredFrames($0, textEdit: textEdit, notes: reopened, saved: saved) } try encodeJSON( try FrameOracle.read().filter { $0.pid == target.window.pid }, to: session.directory.appendingPathComponent("setup-hidden-cg-windows.json")) try encodeJSON( ["hidden": try target.isHidden(apps: session.apps)], to: session.directory.appendingPathComponent("setup-owned-hidden-readback.json")) } for application in visibility { try application.requireUnchanged() } try encodeJSON( try session.readFrames([textEdit, reopened]), to: session.directory.appendingPathComponent("setup-restored-cg-frames.json")) if let target = session.setupOwnedVisibility { _ = try session.apps.validatedLaunchReceipt(for: textEdit) try await session.apps.focus(textEdit) try await session.expect( "Owned TextEdit has native foreground focus before setup Undo without changing the setup" ) { rows in for application in visibility { try application.requireUnchanged() } return try SetupRealitySafety.focusedWindow( rows, window: textEdit, foregroundPID: NSWorkspace.shared.frontmostApplication?.processIdentifier) && SetupOwnedVisibility.hiddenReadback( rows, window: target.window, hidden: target.isHidden(apps: session.apps)) && SetupRealitySafety.restoredFrames(rows, textEdit: textEdit, notes: reopened, saved: saved) } try encodeJSON( try FrameOracle.read(), to: session.directory.appendingPathComponent("setup-undo-focus-cg-windows.json")) _ = try await session.command("undo") try await session.expect( "Undo restores owned Calculator visibility and moves TextEdit out of its saved column" ) { rows in for application in visibility { try application.requireUnchanged() } guard let frame = rows.first(where: { $0.id == textEdit.id && $0.pid == textEdit.pid && $0.onscreen })? .frame else { return false } return try SetupOwnedVisibility.visibleReadback( rows, window: target.window, hidden: target.isHidden(apps: session.apps), startingFrame: target.startingFrame) && frame.width > saved[0].width + 1 } try encodeJSON( try session.readFrames([textEdit, reopened, target.window]), to: session.directory.appendingPathComponent("setup-undo-cg-frames.json")) } session.recordExpectation( "Setups used isolated setups.json with hideOtherApps=\(hideOtherApps); unrelated application visibility stayed unchanged" ) }}