Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479import AppKitimport Darwinimport Foundationimport ParcelConfigimport ParcelUI
@MainActorfunc checkTourBusyDesktop(_ session: RealitySession) async throws { try session.configure(layout: "grid", cap: 4) let owned = try await session.startingWindows([.fixture, .fixture, .finder, .textEdit, .terminal, .finder]) guard let terminal = owned.first(where: { $0.app == .terminal }) else { throw RealityError("Busy-desktop Tidy requires its owned Terminal window") } for window in owned where window.app == .finder { try session.apps.populateOwnedFinderFolder(window) } let increment = try await measureResizeIncrement(session, window: terminal) let minimumHeight = (session.visible.height * 0.6).rounded(.down) let clampIndex = 1 let clamping = try session.apps.fixture(for: owned[clampIndex]) let adjusting = try session.apps.fixture(for: owned[0]) try await session.apps.arrange( owned[clampIndex], frame: ScreenRect( x: session.visible.x + 20, y: session.visible.y + 20, width: 600, height: minimumHeight + 40)) try await clamping.configureTidy(clampHeight: minimumHeight) let original = try session.readFrames(owned) let configuration = try Data(contentsOf: session.config) try encodeJSON(original, to: session.directory.appendingPathComponent("tour-busy-original-cg-frames.json")) let hooks = try RealityRecoveryHooks(kind: .tourRollback, token: UUID().uuidString) try await session.start(recoveryHooks: hooks, firstRun: true) try await waitForFirstRunWorkspace(session, healthy: owned) try await waitNativeTour(session, step: "welcome") for step in ["allow", "ready"] { try await pressNativeTour(session, step == "allow" ? .automatic : .continue) try await waitNativeTour(session, step: step) try await session.expect("Busy desktop keeps its original CG frames before Tidy") { try TourFirstRunOracle.unchanged($0, owned: owned, original: original) } } try await adjusting.configureTidy(adjustNextFrame: true) try await pressNativeTour(session, .tidy) try await waitNativeTour(session, terminal: "success") let gaps = try session.configuredLayout().gaps try await session.expect("First-run Tidy fits unknown clamps and frame adjustments into native tiles") { let frames = try TourFirstRunOracle.frames($0, owned: owned) guard frames[clampIndex].height >= minimumHeight, frames.allSatisfy({ session.visible.contains($0, tolerance: 0) }) else { return false } for (index, frame) in frames.enumerated() { for otherIndex in frames.indices where otherIndex > index { let other = frames[otherIndex] let hasResizeGrid = owned[index].id == terminal.id || owned[otherIndex].id == terminal.id let sameSlot = frame.matches(other, tolerance: 1) || (hasResizeGrid && abs(frame.x - other.x) <= 1 && abs(frame.y - other.y) <= 1 && abs(frame.width - other.width) < increment.width + 1 && abs(frame.height - other.height) < increment.height + 1) guard frame.separated(from: other, gap: gaps.inner, tolerance: 1) || sameSlot else { return false } } } return frames.contains { $0.separated(from: frames[0], gap: gaps.inner, tolerance: 1) } } let clamped = try await clamping.control("snapshot") let adjusted = try await adjusting.control("snapshot") try encodeJSON(clamped, to: session.directory.appendingPathComponent("tour-clamp-receipt.json")) try encodeJSON(adjusted, to: session.directory.appendingPathComponent("tour-adjustment-receipt.json")) guard clamped.windows?.contains(where: { $0.clampedWrites > 0 }) == true, adjusted.windows?.contains(where: { $0.adjustedWrites == 1 }) == true else { throw RealityError("First-run Tidy did not exercise both native frame constraints") } let config = try await session.cli(["query", "--json", "config"]) guard config.status == 0, try JSONDecoder().decode(FirstRunConfigStatus.self, from: Data(config.output.utf8)).automaticTiling, try Data(contentsOf: session.config) == configuration else { throw RealityError("Busy-desktop Tidy did not enable Automatic tiling with unchanged configuration") } try encodeJSON( try session.readFrames(owned), to: session.directory.appendingPathComponent("tour-busy-final-cg-frames.json"))}
@MainActorfunc checkTourFirstRunUnresponsive(_ session: RealitySession) async throws { let hooks = try RealityRecoveryHooks(kind: .tourRollback, token: UUID().uuidString) try session.configure(layout: "grid", cap: 4) let owned = try await session.startingWindows([.finder, .finder, .textEdit, .terminal, .fixture]) let healthy = Array(owned.prefix(4)) guard let terminal = healthy.first(where: { $0.app == .terminal }), let blocked = owned.last, blocked.app == .fixture else { throw RealityError("First-run tour requires its four native windows and exact fixture child") } for window in healthy where window.app == .finder { try session.apps.populateOwnedFinderFolder(window) } let increment = try await measureResizeIncrement(session, window: terminal) let original = try session.readFrames(owned) let configuration = try Data(contentsOf: session.config) try encodeJSON(original, to: session.directory.appendingPathComponent("tour-first-run-original-cg-frames.json")) let fixture = try session.apps.fixture(for: blocked) try encodeJSON( try await fixture.stopAXReplies(), to: session.directory.appendingPathComponent("tour-ax-stopped-before.json")) // Only explicit recovery resumes this retained child; failure cleanup still discards it. try await session.start(recoveryHooks: hooks, firstRun: true) let initialIPC = try await session.cli(["query", "--json", "config"], timeout: .seconds(2)) try encodeJSON(initialIPC, to: session.directory.appendingPathComponent("tour-first-run-startup-ipc.json")) guard initialIPC.status == 0 else { throw RealityError("Startup config IPC did not answer before Tidy: \(initialIPC.errors)") } session.recordExpectation("Config IPC answered before Tidy while the owned fixture could not answer AX") try await waitForFirstRunWorkspace(session, healthy: healthy) guard let launch = session.parcel, !launch.isTerminated, let launchDate = launch.launchDate, let current = NSRunningApplication(processIdentifier: launch.processIdentifier), !current.isTerminated, current.launchDate == launchDate, current.bundleURL?.resolvingSymlinksInPath() == session.appURL.resolvingSymlinksInPath(), current.activate() else { throw RealityError("Cannot activate the exact owned first-run Parcel launch") } var first = try await firstRunStatus(session, stage: "before-tidy", retryUnavailable: true) let welcomeDeadline = ContinuousClock.now.advanced(by: .seconds(5)) while !first.isVisibleWelcome, ContinuousClock.now < welcomeDeadline { try await Task.sleep(for: .milliseconds(40)) first = try await firstRunStatus(session, stage: "waiting-welcome") } guard first.isVisibleWelcome else { throw RealityError("The actual first-run welcome was not presented; replaying a tour cannot certify this row") } let config = try await session.cli(["query", "--json", "config"], timeout: .seconds(2)) try encodeJSON(config, to: session.directory.appendingPathComponent("tour-first-run-paused-config.json")) guard config.status == 0, try !JSONDecoder().decode(FirstRunConfigStatus.self, from: Data(config.output.utf8)).automaticTiling else { throw RealityError("First-run discovery did not leave Automatic tiling off before Tidy") } let holdUntil = ContinuousClock.now.advanced(by: .milliseconds(500)) try await session.expect("First-run discovery preserves all five original CG frames before consent") { rows in _ = try fixture.requireStoppedAXReplies() guard try TourFirstRunOracle.unchanged(rows, owned: owned, original: original) else { throw RealityError("First-run tour wrote a real window before the Tidy button was pressed") } return ContinuousClock.now >= holdUntil } var status = first for (transition, expected) in ["allow", "ready"].enumerated() { try await pressNativeTour(session, expected == "allow" ? .automatic : .continue) try await waitNativeTour(session, step: expected) status = try await firstRunStatus(session, stage: "advance-\(transition)") guard status.step == expected, !status.didTidy, !status.isBusy else { throw RealityError("First-run tour did not follow Welcome → Allow → Ready without arranging windows") } } status = try await firstRunStatus(session, stage: "ready-to-press") guard status.presented, status.step == "ready", status.canContinue, !status.isBusy, !status.didTidy, !status.visibleSetupText.isEmpty else { throw RealityError("The real first-run Ready action was not enabled or visibly rendered") } guard try TourFirstRunOracle.unchanged(FrameOracle.read(), owned: owned, original: original), try Data(contentsOf: session.config) == configuration else { throw RealityError("First-run navigation changed real windows or current configuration before Tidy") } _ = try fixture.requireStoppedAXReplies() guard let parcel = session.parcel, let launchDate = parcel.launchDate, let windowID = status.visibleTourWindowNumber else { throw RealityError("The owned first-run tour launch or visible CG window identity is unavailable") } let press = try await session.driver.send( .pressTourTidy(pid: parcel.processIdentifier, windowID: windowID, launchDate: launchDate.timeIntervalSince1970)) try encodeJSON(press, to: session.directory.appendingPathComponent("tour-first-run-external-ax-press.json")) guard let receipt = press.tourPress else { throw RealityError("Driver omitted its external Tidy AX press receipt") } try receipt.requireMatch( pid: parcel.processIdentifier, windowID: windowID, launchDate: launchDate.timeIntervalSince1970) let deadline = ContinuousClock.now.advanced(by: .seconds(15)) repeat { _ = try fixture.requireStoppedAXReplies() guard try TourFirstRunOracle.unchanged(FrameOracle.read(), owned: owned, original: original) else { throw RealityError("Unknown discovery allowed Tidy to write an owned native window") } status = try await firstRunStatus(session, stage: "after-press") if let terminal = status.terminal, terminal != "none", !status.isBusy { break } try await Task.sleep(for: .milliseconds(40)) } while ContinuousClock.now < deadline try status.requireFailedBeforeWrite() let failedHoldUntil = ContinuousClock.now.advanced(by: .milliseconds(500)) try await session.expect("Unknown discovery fails before write and retains all five original CG frames") { rows in _ = try fixture.requireStoppedAXReplies() guard try TourFirstRunOracle.unchanged(rows, owned: owned, original: original) else { throw RealityError("A late write changed a window after the safe first-run failure") } return ContinuousClock.now >= failedHoldUntil } let failedConfig = try await session.cli(["query", "--json", "config"], timeout: .seconds(2)) guard failedConfig.status == 0, try !JSONDecoder().decode(FirstRunConfigStatus.self, from: Data(failedConfig.output.utf8)).automaticTiling, try Data(contentsOf: session.config) == configuration else { throw RealityError("Unknown discovery enabled Automatic tiling or changed current configuration") } try encodeJSON( try fixture.requireStoppedAXReplies(), to: session.directory.appendingPathComponent("tour-ax-stopped-after.json")) try encodeJSON( try session.readFrames(owned), to: session.directory.appendingPathComponent("tour-first-run-failed-before-write-cg-frames.json")) session.recordExpectation("Actual Tidy reports unchanged windows and Automatic off for unknown discovery") try await captureNativeTour(session, stage: "failed-before-write")
try encodeJSON( try await resumeOwnedAXReplies(fixture, window: blocked), to: session.directory.appendingPathComponent("tour-ax-resumed.json")) try await firstRunTourAction(session, "refresh-checks") status = try await firstRunStatus(session, stage: "recovery-ready") guard status.canContinue, status.presented, status.step == "ready", !status.isBusy else { throw RealityError("Healthy-child recovery did not offer an explicit scoped retry") } guard try TourFirstRunOracle.unchanged(FrameOracle.read(), owned: owned, original: original) else { throw RealityError("Resuming the child or checking setup moved windows without retry consent") } try await pressNativeTour(session, .tidy) let gaps = try session.configuredLayout().gaps try await session.expect( "Explicit healthy-child retry fills four CG slots with one safe stack", timeout: .seconds(15) ) { try TourFirstRunOracle.cappedGrid( $0, owned: owned, visible: session.visible, gaps: gaps, terminal: terminal, increment: increment) } try await waitNativeTour(session, terminal: "success") status = try await firstRunStatus(session, stage: "recovered") guard !status.presented, status.didTidy, !status.isBusy, status.terminal == "success", try Data(contentsOf: session.config) == configuration else { throw RealityError("Explicit recovery did not complete without changing current configuration") } let recoveredConfig = try await session.cli(["query", "--json", "config"], timeout: .seconds(2)) guard recoveredConfig.status == 0, try JSONDecoder().decode(FirstRunConfigStatus.self, from: Data(recoveredConfig.output.utf8)).automaticTiling else { throw RealityError("Verified recovery did not enable Automatic tiling") } try encodeJSON( try session.readFrames(owned), to: session.directory.appendingPathComponent("tour-first-run-recovered-cg-frames.json"))}
@MainActorprivate func resumeOwnedAXReplies( _ fixture: RealityFixture, window: OwnedWindow) async throws -> RealityFixture.StoppedAXReceipt { let stopped = try fixture.requireStoppedAXReplies() guard window.pid == stopped.pid, stopped.parentPID == getpid(), fixture.process.processIdentifier == stopped.pid, fixture.process.isRunning, fixture.process.executableURL?.resolvingSymlinksInPath().path == stopped.executable else { throw RealityError("Safety stop: stopped fixture does not match its retained child launch") } _ = try TourFirstRunOracle.frames(FrameOracle.read(), owned: [window]) guard kill(stopped.pid, SIGCONT) == 0 else { throw RealityError("Cannot resume the exact owned fixture child: errno \(errno)") } let deadline = ContinuousClock.now.advanced(by: .milliseconds(500)) repeat { var info = proc_bsdinfo() let size = Int32(MemoryLayout<proc_bsdinfo>.size) var path = [UInt8](repeating: 0, count: 4 * Int(MAXPATHLEN)) guard fixture.process.isRunning, proc_pidinfo(stopped.pid, PROC_PIDTBSDINFO, 0, &info, size) == size, proc_pidpath(stopped.pid, &path, UInt32(path.count)) > 0, info.pbi_pid == UInt32(stopped.pid), info.pbi_ppid == UInt32(stopped.parentPID), String(decoding: path.prefix(while: { $0 != 0 }), as: UTF8.self) == stopped.executable else { throw RealityError("Safety stop: resumed fixture child identity could not be revalidated") } _ = try TourFirstRunOracle.frames(FrameOracle.read(), owned: [window]) if info.pbi_status != UInt32(SSTOP), info.pbi_status != UInt32(SZOMB) { let reply = try await fixture.control("snapshot") guard reply.pid == stopped.pid else { throw RealityError("Resumed fixture acknowledged the wrong child PID") } return RealityFixture.StoppedAXReceipt( pid: stopped.pid, parentPID: stopped.parentPID, executable: stopped.executable, state: info.pbi_status) } try await Task.sleep(for: .milliseconds(10)) } while ContinuousClock.now < deadline throw RealityError("Owned fixture did not leave the kernel stopped state after explicit recovery")}
private struct FirstRunConfigStatus: Decodable { let automaticTiling: Bool let running: Bool enum CodingKeys: String, CodingKey { case automaticTiling = "automatic_tiling" case running }}
struct TourFirstRunStatus: Decodable { let presented: Bool let step: String let intent: String let canContinue: Bool let isBusy: Bool let didTidy: Bool let terminal: String? let visibleSetupText: [String] let noticeTitle: String? let noticeIsVisible: Bool let keyWindowNumber: UInt32? let nativeWindows: [NativeWindow]?
struct NativeWindow: Decodable { let number: UInt32 let visible: Bool let canBecomeKey: Bool let canBecomeMain: Bool let width: Double let height: Double }
var visibleTourWindowNumber: UInt32? { let candidates = (nativeWindows ?? []).filter { $0.visible && $0.canBecomeKey && $0.canBecomeMain && $0.number > 0 && $0.width.isFinite && $0.height.isFinite && $0.width > 0 && $0.height > 0 } return candidates.count == 1 ? candidates.first?.number : nil }
var isVisibleWelcome: Bool { presented && step == "welcome" && !isBusy && !didTidy && visibleTourWindowNumber != nil && !visibleSetupText.isEmpty }
func requireFailedBeforeWrite() throws { guard presented, step == "ready", !isBusy, !didTidy, terminal == "failed-before-write" else { throw RealityError("Unknown discovery did not retain an incomplete Ready failure before writing") } guard visibleSetupText.contains("Parcel couldn’t arrange your windows."), visibleSetupText.contains("Your windows haven’t moved. Automatic tiling is off.") else { throw RealityError("Unknown discovery omitted visible unchanged-windows and Automatic-off safety copy") } }}
enum TourFirstRunReadiness { static func isUnavailable(_ result: CommandOutput) -> Bool { guard result.status == 1, result.output.isEmpty else { return false } let lines = result.errors.split(whereSeparator: \.isNewline) guard lines.count == 1, let line = lines.first, let code = line.range(of: "(tour_unavailable)") else { return false } return line[code.upperBound...].hasPrefix(": ") }}
@MainActorprivate func firstRunStatus( _ session: RealitySession, stage: String, retryUnavailable: Bool = false) async throws -> TourFirstRunStatus { let deadline = ContinuousClock.now.advanced(by: .seconds(5)) repeat { let start = ContinuousClock.now let result = try await session.cli(["run", "--json", "e2e-tour", "status"], timeout: .seconds(2)) let components = start.duration(to: .now).components let seconds = Double(components.seconds) + Double(components.attoseconds) / 1e18 try encodeJSON( result, to: session.directory.appendingPathComponent("tour-first-run-status-\(stage)-\(UUID().uuidString).json")) try encodeJSON( ["elapsedSeconds": seconds], to: session.directory.appendingPathComponent("tour-first-run-ipc-\(stage).json")) if result.status == 0 { return try JSONDecoder().decode(TourFirstRunStatus.self, from: Data(result.output.utf8)) } guard retryUnavailable, TourFirstRunReadiness.isUnavailable(result), ContinuousClock.now < deadline else { throw RealityError("First-run tour status IPC failed: \(result.errors)") } try await Task.sleep(for: .milliseconds(40)) } while ContinuousClock.now < deadline throw RealityError("First-run learning controller remained explicitly unavailable through its readiness deadline")}
@MainActorprivate func firstRunTourAction(_ session: RealitySession, _ arguments: String...) async throws { let result = try await session.cli(["run", "--json", "e2e-tour"] + arguments, timeout: .seconds(15)) try encodeJSON( result, to: session.directory.appendingPathComponent("tour-first-run-action-\(arguments[0])-\(UUID().uuidString).json")) guard result.status == 0, try JSONDecoder().decode(RealitySession.CommandAcceptance.self, from: Data(result.output.utf8)).accepted else { throw RealityError("First-run tour action failed: \(result.output) \(result.errors)") }}
@MainActorprivate func waitForFirstRunWorkspace(_ session: RealitySession, healthy: [OwnedWindow]) async throws { struct Workspace: Decodable { let active: Bool let windows: [UInt32] } let deadline = ContinuousClock.now.advanced(by: .seconds(15)) repeat { let config = try await session.cli(["query", "--json", "config"], timeout: .seconds(2)) try encodeJSON( config, to: session.directory.appendingPathComponent("tour-first-run-engine-\(UUID().uuidString).json")) guard config.status == 0 else { throw RealityError("First-run engine readiness IPC failed: \(config.errors)") } let ready = try JSONDecoder().decode(FirstRunConfigStatus.self, from: Data(config.output.utf8)) if ready.running { let result = try await session.cli(["query", "--json", "workspaces"], timeout: .seconds(2)) try encodeJSON( result, to: session.directory.appendingPathComponent("tour-first-run-workspaces-\(UUID().uuidString).json")) guard result.status == 0 else { throw RealityError("First-run active workspace query failed: \(result.errors)") } let workspaces = try JSONDecoder().decode([Workspace].self, from: Data(result.output.utf8)) if workspaces.contains(where: { $0.active && Set(healthy.map(\.id)).isSubset(of: Set($0.windows)) }) { session.recordExpectation( "Engine active workspace contains every healthy owned native window before final consent") return } } try await Task.sleep(for: .milliseconds(40)) } while ContinuousClock.now < deadline throw RealityError("Bounded first-run discovery did not provide an active workspace for all healthy native windows")}
enum TourFirstRunOracle { static func frames(_ rows: [RealWindow], owned: [OwnedWindow]) throws -> [ScreenRect] { try owned.map { window in let matches = rows.filter { $0.id == window.id } guard matches.count == 1, let match = matches.first, match.pid == window.pid, match.layer == 0, match.onscreen else { throw RealityError("Safety stop: first-run CG window \(window.id) vanished or changed ownership") } return match.frame } }
static func unchanged(_ rows: [RealWindow], owned: [OwnedWindow], original: [ScreenRect]) throws -> Bool { guard owned.count == original.count else { throw RealityError("First-run original CG frame count mismatch") } return try zip(frames(rows, owned: owned), original).allSatisfy { $0.matches($1, tolerance: 1) } }
static func gridSlots(visible: ScreenRect, gaps: LayoutGaps) -> [ScreenRect] { let usable = visible.inset(gaps.outer) let width = (usable.width - gaps.inner) / 2 let height = (usable.height - gaps.inner) / 2 return (0..<4).map { index in let x = (usable.x + Double(index % 2) * (width + gaps.inner)).rounded() let y = (usable.y + Double(index / 2) * (height + gaps.inner)).rounded() let maxX = (usable.x + Double(index % 2) * (width + gaps.inner) + width).rounded() let maxY = (usable.y + Double(index / 2) * (height + gaps.inner) + height).rounded() return ScreenRect(x: x, y: y, width: maxX - x, height: maxY - y) } }
static func cappedGrid( _ rows: [RealWindow], owned: [OwnedWindow], visible: ScreenRect, gaps: LayoutGaps, terminal: OwnedWindow, increment: ResizeIncrement ) throws -> Bool { guard owned.count == 5, Set(owned.map(\.id)).count == 5 else { throw RealityError("Recovery grid requires five distinct owned windows in four slots") } let slots = gridSlots(visible: visible, gaps: gaps) var occupancy = Array(repeating: 0, count: slots.count) for (window, frame) in try zip(owned, frames(rows, owned: owned)) { guard let index = slots.firstIndex(where: { tile in window.id == terminal.id ? FrameOracle.incrementFit(frame, tile: tile, increment: increment) : tile.contains(frame, tolerance: 0) && frame.matches(tile, tolerance: 1) }) else { return false } occupancy[index] += 1 } return occupancy.sorted() == [1, 1, 1, 2] }
static func grid( _ rows: [RealWindow], owned: [OwnedWindow], visible: ScreenRect, gaps: LayoutGaps, terminal: OwnedWindow, increment: ResizeIncrement ) throws -> Bool { guard owned.count == 4, Set(owned.map(\.id)).count == 4 else { throw RealityError("First-run grid requires four distinct healthy native windows") } var slots = gridSlots(visible: visible, gaps: gaps) for (window, frame) in try zip(owned, frames(rows, owned: owned)) { guard let index = slots.firstIndex(where: { tile in window.id == terminal.id ? FrameOracle.incrementFit(frame, tile: tile, increment: increment) : tile.contains(frame, tolerance: 0) && frame.matches(tile, tolerance: 1) }) else { return false } slots.remove(at: index) } return slots.isEmpty }}