diff --git a/Sources/ParcelApp/AppTourIntegration.swift b/Sources/ParcelApp/AppTourIntegration.swift index 8fe4f9bd..4005b000 100644 --- a/Sources/ParcelApp/AppTourIntegration.swift +++ b/Sources/ParcelApp/AppTourIntegration.swift @@ -17,6 +17,7 @@ enum AppTourIntegration { defaults: UserDefaults = .standard, targetDisplay: (() -> DisplayID?)? = nil, openShortcuts: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, + openConfigurationSettings: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, effectiveBindings: @escaping () throws -> [ConfigCommand: KeyChord]? = { nil }, readFrames: @escaping (State, WorkspaceKey) async throws -> [WindowID: Rect] = nativeFrames, loginStatus: @escaping () throws -> TourLoginStatus = { try AppTourIntegration.systemLoginStatus() }, @@ -91,6 +92,7 @@ enum AppTourIntegration { }, currentIntent: { services.selectedTourIntent }, openShortcuts: openShortcuts, + openConfigurationSettings: openConfigurationSettings, openSystemSettings: { guard let url = URL(string: "x-apple.systempreferences:com.apple.Desktop-Settings.extension"), NSWorkspace.shared.open(url) @@ -190,6 +192,45 @@ enum AppTourIntegration { } } + static func verifyArrangement( + state: State, workspace: WorkspaceKey, before: [WindowID: Rect], native: [WindowID: Rect], + receipts: [WindowID: Rect], constrained: Set, exhausted: Set + ) throws -> [WindowID] { + let windows = state.workspaces[workspace]?.visibleWindows ?? [] + guard let display = state.displays[workspace.display] else { throw TourSetupFailure.workspaceUnavailable } + var refused: [WindowID] = [] + for id in windows { + guard let frame = native[id], let original = before[id], let target = state.frames[id], + frame.isValid, frame.size.width > 0, frame.size.height > 0 + else { throw EngineWorkspaceFailure.unsettled([id]) } + let acknowledged = receipts[id].map { TourFrameReadback.matches($0, frame) } == true + guard acknowledged || TourFrameReadback.matches(original, frame) else { + throw EngineWorkspaceFailure.unsettled([id]) + } + if TourFrameReadback.matches(frame, target) { continue } + if acknowledged, constrained.contains(id), contains(target, frame) { continue } + guard acknowledged, exhausted.contains(id), TourFrameReadback.matches(original, frame), + contains(display.frame, frame), + windows.allSatisfy({ other in + guard other != id, let otherFrame = native[other] else { return other == id } + return !overlaps(frame, otherFrame) + }) + else { throw EngineWorkspaceFailure.unsettled([id]) } + refused.append(id) + } + return refused + } + + private static func contains(_ bounds: Rect, _ frame: Rect) -> Bool { + frame.minX >= bounds.minX && frame.minY >= bounds.minY + && frame.maxX <= bounds.maxX && frame.maxY <= bounds.maxY + } + + private static func overlaps(_ first: Rect, _ second: Rect) -> Bool { + first.minX < second.maxX && second.minX < first.maxX + && first.minY < second.maxY && second.minY < first.maxY + } + private static func terminalName(_ result: TourStartResult?) -> String { switch result { case nil: "none" @@ -352,6 +393,7 @@ private final class TourActivation { private let readFrames: (State, WorkspaceKey) async throws -> [WindowID: Rect] private let systemCheck: () throws -> TourSystemCheck private let injectFailure: () throws -> Void + private let manualPermission = TourCheckOperation() private var target: WorkspaceKey? private var attempt: UUID? @@ -405,7 +447,17 @@ private final class TourActivation { services.holdForTour() try services.persistTourOff() } catch { return intent == .manual ? .manualSaveFailed : .progressSaveFailed } - await permissions.refreshPermission() + let epoch = services.tourEpoch + if intent == .manual { + do { + _ = try await manualPermission.run( + operation: { + await self.permissions.refreshPermission() + return self.permissions.status + }, waitForDeadline: { try await Task.sleep(for: $0) }) + } catch { return .manualSaveFailed } + } + guard services.tourEpoch == epoch else { return .failedBeforeWrite(details: []) } guard permissions.status == .granted, !Task.isCancelled else { return finishFailure(previous, details: [TourSetupFailure.accessibilityRequired.localizedDescription]) } @@ -421,50 +473,63 @@ private final class TourActivation { guard let engine = services.engine, engine.isRunning, let key = target, currentTarget(engine) == key else { return finishFailure(previous, details: [TourSetupFailure.workspaceUnavailable.localizedDescription]) } - let configuration = await settings.store.snapshot - guard validConfiguration(configuration, engine: engine) else { - return finishFailure(previous, details: [TourSetupFailure.configurationChanged.localizedDescription]) - } - let identity = TourConfigurationIdentity(fileURL: settings.store.fileURL, snapshot: configuration) + var configurationIdentity: TourConfigurationIdentity? var point: EngineWorkspaceRestorePoint? var baseline: [WindowID: Rect] = [:] + var capturedApplications: [WindowID: AppID] = [:] + let tidyLog = TourTidyLog() let transaction = TourTidyTransaction( operations: .init( checkpoint: { + guard self.services.tourEpoch == epoch else { throw CancellationError() } guard try self.progress.load() == previous else { throw TourProgressFailure.saveFailed } }, arrange: { + let configuration = await self.settings.store.snapshot + guard self.validConfiguration(configuration, engine: engine) else { + throw TourSetupFailure.configurationChanged + } + let identity = TourConfigurationIdentity( + fileURL: self.settings.store.fileURL, snapshot: configuration) + configurationIdentity = identity + try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) try await self.services.awaitTourDiscovery() try await engine.drainTourWriters() let skipped = self.services.tourSkippedApplications() + for app in skipped { + tidyLog.skippedApplication( + pid: app.app.pid, bundleID: app.app.bundleID, name: app.name, reason: app.reason.rawValue) + } + tidyLog.phase("discovery-drained", skipped: skipped.count) guard skipped.isEmpty else { throw TourSetupFailure.unresponsiveApplications(skipped.map(\.name)) } - try await self.revalidate(engine, key: key, identity: identity) + try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) baseline = try await self.readFrames(engine.snapshot.state, key) - try await self.revalidate(engine, key: key, identity: identity) + try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) let captured = try engine.captureTourRestorePoint(in: key, freshFrames: baseline) point = captured + capturedApplications = engine.snapshot.state.windows.mapValues(\.app) + tidyLog.phase("capture", windows: baseline.count) let result = try await engine.performTourRetile(captured) try self.injectFailure() guard result.isAccepted else { throw TourSetupFailure.tidyFailed } try await engine.awaitWorkspaceSettled(in: key) - try await self.revalidate(engine, key: key, identity: identity) + try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) let final = try await self.readFrames(engine.snapshot.state, key) - let windows = engine.snapshot.state.workspaces[key]?.visibleWindows ?? [] - guard - windows.allSatisfy({ id in - guard let frame = final[id], let expected = engine.snapshot.state.frames[id] else { - return false - } - return TourFrameReadback.matches(frame, expected) - || engine.frameWriteDiagnostics[id] != nil - && engine.snapshot.readbackFrames[id].map { TourFrameReadback.matches($0, frame) } - == true - }) - else { throw EngineWorkspaceFailure.unsettled(windows) } - return [] + let refused = try AppTourIntegration.verifyArrangement( + state: engine.snapshot.state, workspace: key, before: baseline, native: final, + receipts: engine.snapshot.readbackFrames, + constrained: Set(engine.frameWriteDiagnostics.keys), + exhausted: Set(engine.frameWriteDiagnostics.filter { $0.value.limitReached }.keys)) + return refused.map { id in + TourSetupFailure.unsettledWindows( + [id], titles: engine.snapshot.state.windows.mapValues(\.title) + ) + .localizedDescription + } }, commit: { - try await self.revalidate(engine, key: key, identity: identity) + guard let identity = configurationIdentity else { throw TourSetupFailure.configurationChanged } + try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) try self.commit(previous, automatic: true) }, release: { @@ -474,11 +539,15 @@ private final class TourActivation { }, drain: { try await engine.drainTourWriters() }, restoreWorkspace: { + guard self.services.tourEpoch == epoch else { throw CancellationError() } guard let point else { throw TourSetupFailure.workspaceUnavailable } try await engine.restoreWorkspace( - point, restoringModel: engine.configuration == identity.configuration) + point, restoringModel: engine.configuration == configurationIdentity?.configuration) let restored = try await self.readFrames(engine.snapshot.state, key) - for (id, frame) in baseline where engine.snapshot.state.workspace(containing: id) == key { + for (id, frame) in baseline + where engine.snapshot.state.workspace(containing: id) == key + && engine.snapshot.state.windows[id]?.app == capturedApplications[id] + { guard restored[id].map({ TourFrameReadback.matches($0, frame) }) == true else { throw EngineWorkspaceFailure.unsettled([id]) } @@ -486,14 +555,18 @@ private final class TourActivation { }, hasPotentialWindowMovement: { point.map { engine.workspaceNeedsFrameRestoration($0) } ?? false }, recordRecovery: { required in + guard self.services.tourEpoch == epoch else { throw CancellationError() } try self.services.persistTourOff() var saved = previous saved.recovery = required ? .recoveryRequired : .none try self.progress.save(saved) self.services.setTourRecoveryNotice(saved.recoveryNotice) - })) + }, + describeFailure: { + AppTourIntegration.describe($0, state: engine.snapshot.state).localizedDescription + }), log: tidyLog) let result = await transaction.run() - if case .recoveryRequired = result { + if case .recoveryRequired = result, services.tourEpoch == epoch { services.composition?.report(AppFailure(message: result.title)) } return result @@ -539,8 +612,10 @@ private final class TourActivation { && engine.configuration == snapshot.activeConfiguration } - private func revalidate(_ engine: ParcelEngine, key: WorkspaceKey, identity: TourConfigurationIdentity) async throws - { + private func revalidate( + _ engine: ParcelEngine, key: WorkspaceKey, identity: TourConfigurationIdentity, epoch: UUID + ) async throws { + guard services.tourEpoch == epoch else { throw CancellationError() } try Task.checkCancellation() await permissions.refreshPermission() guard permissions.status == .granted else { throw TourSetupFailure.accessibilityRequired } @@ -550,6 +625,7 @@ private final class TourActivation { else { throw TourSetupFailure.configurationChanged } try await identity.validate() try Task.checkCancellation() + guard services.tourEpoch == epoch else { throw CancellationError() } guard currentTarget(engine) == key, engine.snapshot.state.isActive(key) else { throw TourSetupFailure.workspaceUnavailable } diff --git a/Sources/ParcelApp/TourTidyTransaction.swift b/Sources/ParcelApp/TourTidyTransaction.swift index 5d9c5b08..05cb0f6b 100644 --- a/Sources/ParcelApp/TourTidyTransaction.swift +++ b/Sources/ParcelApp/TourTidyTransaction.swift @@ -12,9 +12,11 @@ final class TourTidyTransaction { let restoreWorkspace: @MainActor () async throws -> Void let hasPotentialWindowMovement: @MainActor () -> Bool let recordRecovery: @MainActor (Bool) throws -> Void + var describeFailure: @MainActor (any Error) -> String = { $0.localizedDescription } } private let operations: Operations + private let log: TourTidyLog private let deadline: Duration private let waitForDeadline: @MainActor (Duration) async throws -> Void private var isBusy = false @@ -23,10 +25,11 @@ final class TourTidyTransaction { private var deadlineFailure: (any Error)? init( - operations: Operations, deadline: Duration = .seconds(20), + operations: Operations, deadline: Duration = .seconds(20), log: TourTidyLog = TourTidyLog(), waitForDeadline: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) { self.operations = operations + self.log = log self.deadline = deadline self.waitForDeadline = waitForDeadline } @@ -37,7 +40,8 @@ final class TourTidyTransaction { committed = false deadlineExpired = false deadlineFailure = nil - defer { isBusy = false } + let interval = log.begin() + defer { isBusy = false; log.end(interval) } let operation = Task { @MainActor in await self.runAttempt() } let timer = Task { @MainActor in do { @@ -65,39 +69,52 @@ final class TourTidyTransaction { private func runAttempt() async -> TourStartResult { do { try Task.checkCancellation() + log.phase("checkpoint") try operations.checkpoint() } catch is CancellationError { return await recover(from: CancellationError()) - } catch { return .progressSaveFailed } + } catch { log.failure(error); return .progressSaveFailed } do { + log.phase("arrange") let partial = try await operations.arrange() try Task.checkCancellation() + log.phase("commit") try await operations.commit() try Task.checkCancellation() // The deadline cannot interleave with this commitment and global release. committed = true operations.release() + log.phase(partial.isEmpty ? "completed" : "completed-partial") return partial.isEmpty ? .success : .partial(details: partial) } catch { return await recover(from: error) } } private func recover(from failure: any Error) async -> TourStartResult { - let original = (deadlineFailure ?? (deadlineExpired ? TourSetupFailure.tidyFailed : failure)) - .localizedDescription + let originalFailure = deadlineFailure ?? (deadlineExpired ? TourSetupFailure.tidyFailed : failure) + log.failure(originalFailure) + let original = operations.describeFailure(originalFailure) // This owned recovery task is deliberately independent of action cancellation. return await Task { @MainActor in var details = [original] do { + self.log.phase("drain") try await self.operations.drain() let moved = self.operations.hasPotentialWindowMovement() - if moved { try await self.operations.restoreWorkspace() } + if moved { + self.log.phase("restore") + try await self.operations.restoreWorkspace() + } try self.operations.recordRecovery(false) + self.log.phase(moved ? "restored" : "failed-before-write") return moved ? .restored(details: details) : .failedBeforeWrite(details: details) } catch { - details.append(error.localizedDescription) + self.log.failure(error) + details.append(self.operations.describeFailure(error)) do { try self.operations.recordRecovery(true) } catch { - details.append(error.localizedDescription) + self.log.failure(error) + details.append(self.operations.describeFailure(error)) } + self.log.phase("recovery-required") return .recoveryRequired(details: details) } }.value diff --git a/Tests/ParcelAppTests/TourLifecycleTests.swift b/Tests/ParcelAppTests/TourLifecycleTests.swift index aa8367e5..32effb5f 100644 --- a/Tests/ParcelAppTests/TourLifecycleTests.swift +++ b/Tests/ParcelAppTests/TourLifecycleTests.swift @@ -450,6 +450,36 @@ struct TourLifecycleTests { await engine.stop() } + @Test func retiredCaptureCannotCommitOrOverwriteANewerHeldDraft() async throws { + let fixture = try TourLifecycleFixture() + defer { fixture.remove() } + try Data("[motion]\nenabled = false\n".utf8).write(to: fixture.fileURL) + let model = fixture.settings + await model.reload() + let services = EngineShellServices(defaults: fixture.defaults, tourUnresolved: true) + let engine = try fixture.engine(services: services, configuration: model.configuration) + try await engine.start() + let permissions = SystemPermissionProvider( + appCenter: NotificationCenter(), workspaceCenter: NotificationCenter(), readTrust: { true }) + defer { permissions.stop() } + let newer = TourSetupProgress(step: .allow, intent: .manual) + let actions = fixture.actions( + services: services, permissions: permissions, + readFrames: { _, _ in + services.holdForTour() + try fixture.progress.save(newer) + return [:] + }) + #expect(await actions.checkReady(.automatic) == .ready) + try fixture.progress.save(TourSetupProgress(step: .ready, recovery: .interrupted)) + let result = await actions.start(.automatic, UUID()) + #expect(!result.completed) + #expect(try fixture.progress.load() == newer) + #expect(fixture.world.writes.isEmpty) + #expect(services.isTourUnresolved && engine.isWaitingForTour && !services.isAutomaticTilingEnabled) + await engine.stop() + } + @Test func explicitCommandsStayBlockedUntilManualOrAutomaticCompletion() async throws { let services = EngineShellServices(tourUnresolved: true) let layoutResult: Result diff --git a/Tests/ParcelAppTests/TourTidyTransactionTests.swift b/Tests/ParcelAppTests/TourTidyTransactionTests.swift index 440afbc4..c8a0bb71 100644 --- a/Tests/ParcelAppTests/TourTidyTransactionTests.swift +++ b/Tests/ParcelAppTests/TourTidyTransactionTests.swift @@ -170,6 +170,71 @@ struct TourTidyTransactionTests { #expect(!clock.isWaiting) } + @Test(arguments: TourReadbackCase.allCases) + private func independentReadbackRequiresBoundedAcknowledgedEvidence(_ scenario: TourReadbackCase) throws { + let key = WorkspaceKey(display: DisplayID(rawValue: "test.readback"), space: SpaceID(rawValue: 1)) + var state = State( + displays: [Display(id: key.display, frame: Rect(width: 1000, height: 800))], + activeSpaces: [key.display: key.space]) + let first = WindowID(rawValue: 1) + let second = WindowID(rawValue: 2) + let original = Rect(x: 10, y: 500, width: 300, height: 100) + for id in [first, second] { + state = + reduce( + state, + .windowAppeared( + ManagedWindow(id: id, app: AppID(pid: 100, bundleID: "test.readback"), title: "Document"), + workspace: key, frame: original) + ).0 + } + state.frames = [first: Rect(width: 400, height: 400), second: Rect(x: 400, width: 400, height: 400)] + var native = state.frames + var receipts = native + var constrained: Set = [] + var exhausted: Set = [] + switch scenario { + case .success: break + case .empty: + state = State(displays: [Display(id: key.display, frame: Rect(width: 1000, height: 800))]) + native = [:]; receipts = [:] + case .alreadyArranged: break + case .constrained: + native[first] = Rect(width: 395, height: 395) + receipts = native; constrained.insert(first) + case .stacked: + state.frames[second] = state.frames[first] + native = state.frames; receipts = native + case .partial: + native[first] = original; receipts = native; exhausted.insert(first) + case .missingNative: native[first] = nil + case .missingReceipt: receipts[first] = nil + case .unacknowledgedRefusal: + native[first] = original; receipts[first] = nil; exhausted.insert(first) + case .unknown: + native[first] = original; receipts = native + case .escaped: + native[first] = Rect(x: -20, width: 395, height: 395) + receipts = native; constrained.insert(first); exhausted.insert(first) + case .overlappingRefusal: + native[first] = Rect(x: 450, y: 50, width: 300, height: 100) + receipts = native; exhausted.insert(first) + } + var before = [first: original, second: Rect(x: 10, y: 650, width: 300, height: 100)] + if scenario == .alreadyArranged { before = native; receipts = [:] } + if scenario == .overlappingRefusal { before[first] = native[first] } + let verification = { + try AppTourIntegration.verifyArrangement( + state: state, workspace: key, before: before, native: native, + receipts: receipts, constrained: constrained, exhausted: exhausted) + } + if scenario.isSafe { + #expect(try verification() == (scenario == .partial ? [first] : [])) + } else { + #expect(throws: EngineWorkspaceFailure.self) { try verification() } + } + } + @Test func engineSettleFailureNamesOnlyAffectedWindows() { let known = WindowID(rawValue: 1) let unnamed = WindowID(rawValue: 2) @@ -255,6 +320,18 @@ private final class TourOperationGate { } } +private enum TourReadbackCase: CaseIterable, Sendable { + case success, empty, alreadyArranged, constrained, stacked, partial + case missingNative, missingReceipt, unacknowledgedRefusal, unknown, escaped, overlappingRefusal + + var isSafe: Bool { + switch self { + case .success, .empty, .alreadyArranged, .constrained, .stacked, .partial: true + default: false + } + } +} + private enum TourFailurePoint: Sendable { case checkpoint, arrange, commit, drain, restore, record } @MainActor