From 3309307ca2dcac498ba5ddefef9b0bac1181c34e Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sun, 15 Nov 2026 08:46:28 -0500 Subject: [PATCH 1/2] A sheet's dismissal answers on iOS are kept in a trace file the app can share A sheet that refuses its swipe down and a tap behind it after the app comes back from the background was reported on phones and could not be reproduced on iOS 27.0 simulators. ModalHost now writes each decision with the terms it read to app:/cache/exact-sheet-trace.log and to the unified log (exact-sheet): the presentation and its isModalInPresentation, every change updatePermissions makes to it, UIKit's presentationControllerShouldDismiss (a line only when what it read changes, since UIKit asks every frame of a drag), a refused attempt, the dismissal, closeTop, a navigation sync deferred while a sheet is up, and each sheet's state at every lifecycle edge and one turn after it. The file opens each launch with the system version and build, and keeps its last 200 to 400 KB. An app shares it with share(files=[...]) and the fs.read grant. --- host/apple/Sources/ExactKit/IOS/BackIOS.swift | 6 ++ .../apple/Sources/ExactKit/IOS/ModalIOS.swift | 42 +++++++++++-- .../Sources/ExactKit/IOS/NavigationIOS.swift | 1 + .../Sources/ExactKit/IOS/SheetTraceIOS.swift | 59 +++++++++++++++++++ .../ExactKitTests/ModalStackIOSTests.swift | 26 ++++++++ 5 files changed, 130 insertions(+), 4 deletions(-) create mode 100644 host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift diff --git a/host/apple/Sources/ExactKit/IOS/BackIOS.swift b/host/apple/Sources/ExactKit/IOS/BackIOS.swift index 6e1f6958c..6d629a0d3 100644 --- a/host/apple/Sources/ExactKit/IOS/BackIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/BackIOS.swift @@ -93,6 +93,12 @@ extension NavigationHost { return presenter.carrying("id").contains { $0.props["id"] == name && ($0 === route || $0.isDescendant(of: route)) } } + var traceBack: String { + let route = selectedRoute + let beneath = route?.props["navigationKey"].flatMap { presenter.session?.runtime.locationBeneath($0) } + return "selected=\(selectedKey ?? "nil") selectedRoute=\(route.map { "#\($0.id)" } ?? "nil") control=\(backControl.map { "#\($0.id)" } ?? "nil") declared=\(route.map(declaresBack) ?? false) beneath=\(beneath ?? "nil") servingMain=\(Owner.shared.isServingMain) window=\(presenter.session?.view?.window != nil)" + } + /// Why Back does not go from the selected route, for the journal. var backRefusal: String { if let route = selectedRoute, declaresBack(route) { return "its navigationBack control is disabled or has no press handler" } diff --git a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift index 14009a3b7..dd506551f 100644 --- a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift @@ -377,7 +377,12 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } #endif - init(presenter: Presenter) { self.presenter = presenter } + private var traceObservers: [NSObjectProtocol] = [] + init(presenter: Presenter) { + self.presenter = presenter + super.init() + traceObservers = SheetTrace.watch(self) + } #if os(iOS) /// Why a word of a bound `navigationDetent` is dropped. @@ -532,7 +537,9 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { func updatePermissions() { for layer in layers { - layer.controller.isModalInPresentation = refusesDismissal(of: layer.route) + let refuses = refusesDismissal(of: layer.route) + if refuses != layer.controller.isModalInPresentation { SheetTrace.note("updatePermissions modal \(layer.controller.isModalInPresentation)->\(refuses) \(traceState(layer))") } + layer.controller.isModalInPresentation = refuses layer.controller.updateSheet(detent: layer.route.props["navigationDetent"], cornerRadius: ModalController.cornerRadius(of: layer.route), grabber: layer.route.props["navigationGrabber"]) #if os(iOS) layer.controller.paintSurface() @@ -690,6 +697,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } layers.append(layer) controller.isModalInPresentation = refusesDismissal(of: route) + SheetTrace.note("present \(traceState(layer))") controller.loadViewIfNeeded() // What it inherits, from its first frame: a sheet a deferred sync // presents (the second of two, after the first is up) waits for the next batch otherwise. @@ -753,6 +761,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { func closeTop(animated: Bool = !ExactEnv.agentFreezes, refit: Bool = true) { guard let layer = layers.last else { return } + SheetTrace.note("closeTop route=#\(layer.route.id) key=\(layer.route.props["navigationKey"] ?? "?") alreadyDismissed=\(layer.alreadyDismissed)") closing = true if !layer.alreadyDismissed { presenter.cancelPendingFocus() } presenter.elementScrolls.cancel(inside: layer.controller.view) @@ -826,11 +835,34 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool { - guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return false } - return !refusesDismissal(of: layer.route) + guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { + SheetTrace.note("shouldDismiss false: not the top layer (layers \(layers.count), retiring \(retiring.count))") + return false + } + let refuses = refusesDismissal(of: layer.route) + // UIKit asks every frame of a drag: a line only when the answer or what it read changes. + let line = "shouldDismiss \(!refuses) \(traceState(layer))" + if line != lastAsked { SheetTrace.note(line) } + lastAsked = line + return !refuses + } + private var lastAsked: String? + + private func traceState(_ layer: Presentation) -> String { + let route = layer.route, nav = presenter.navigation + let replaced = presenter.views[route.id] !== route + let inactive = nav.isInactiveRoute(containing: route) + let dismissal = nav.sheetDismissal(route) != nil + return "route=#\(route.id) key=\(route.props["navigationKey"] ?? "?") modal=\(layer.controller.isModalInPresentation) refuses=\(refusesDismissal(of: route)) replaced=\(replaced) closedby=\(route.props["closedby"] ?? "-") inactive=\(inactive) sheetDismissal=\(dismissal) canBack=\(nav.canInvokeBack) \(nav.traceBack) presenting=\(layer.presenting) closing=\(closing) layers=\(layers.count) retiring=\(retiring.count) dismissing=\(dismissing != nil) inTransition=\(inTransition) beingPresented=\(layer.controller.isBeingPresented) beingDismissed=\(layer.controller.isBeingDismissed) pendingSync=\(nav.pendingSync) changing=\(nav.changing) app=\(UIApplication.shared.applicationState.rawValue)" + } + + func traceLayers(_ edge: String) { + guard !layers.isEmpty || !retiring.isEmpty else { return } + SheetTrace.note("\(edge): " + (layers.map(traceState).joined(separator: " | ")) + (retiring.isEmpty ? "" : " retiring=\(retiring.count)")) } func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("didAttemptToDismiss top=\(layers.last?.controller === presentationController.presentedViewController) \(layers.last.map(traceState) ?? "no layer")") guard layers.last?.controller === presentationController.presentedViewController, !presenter.navigation.canInvokeBack else { return } presenter.session?.log("modal dismissal refused: \(presenter.navigation.backRefusal)") @@ -840,6 +872,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { /// dismissal's first frame, not when the app hears of it after (Observe's /// render mark); a swipe let go cancels it. func presentationControllerWillDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("willDismiss") guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return } NavigationMarks.shared.platformBeganShowing() presentationController.presentedViewController.transitionCoordinator?.animate(alongsideTransition: nil) { context in @@ -848,6 +881,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("didDismiss top=\(layers.last?.controller === presentationController.presentedViewController)") guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return } HostLog.note(presenter.session, "presentation: the person dismissed the \(layer.kind) \(layer.route.props["navigationKey"] ?? "?")") closing = true diff --git a/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift b/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift index d37d38143..bbe9f14b8 100644 --- a/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift @@ -445,6 +445,7 @@ final class NavigationHost: NSObject, UINavigationControllerDelegate, UIGestureR // Initial content draws before a presentation covers it. if parts.count > 1, let session = presenter.session, session.firstDrawMs == nil { return } guard !changing, !presenter.modals.inTransition else { + if !pendingSync { presenter.modals.traceLayers("sync deferred (changing=\(changing))") } pendingSync = true owePress() reportCovers() diff --git a/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift b/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift new file mode 100644 index 000000000..1aad991bb --- /dev/null +++ b/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift @@ -0,0 +1,59 @@ +#if os(iOS) || os(tvOS) +import UIKit + +/// Each sheet dismissal decision and what it read, for a refused swipe seen +/// on a phone: lines in the unified log (`exact-sheet`) and in +/// `app:/cache/exact-sheet-trace.log`, which an app shares with the `fs.read` +/// grant. The file keeps its last 200 to 400 KB. +enum SheetTrace { + static let path = "app:/cache/exact-sheet-trace.log" + private static let limit = 400_000 + private static var opened = false + private static let stamp: ISO8601DateFormatter = { + let f = ISO8601DateFormatter() + f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return f + }() + + static func note(_ line: String) { + NSLog("exact-sheet %@", line) + guard let url = AppFiles.url(path) else { return } + var text = "" + if !opened { + opened = true + let info = Bundle.main.infoDictionary + text += "\(stamp.string(from: Date())) launch \(UIDevice.current.systemName) \(UIDevice.current.systemVersion) build \(info?["CFBundleVersion"] as? String ?? "?")\n" + } + text += "\(stamp.string(from: Date())) \(line)\n" + let data = Data(text.utf8) + guard let handle = try? FileHandle(forWritingTo: url) else { + try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try? data.write(to: url) + return + } + defer { try? handle.close() } + if (try? handle.seekToEnd()) ?? 0 > limit, let all = try? Data(contentsOf: url) { + try? (all.suffix(limit / 2) + data).write(to: url) + return + } + try? handle.write(contentsOf: data) + } + + /// The presentations' state at each edge of the app's lifecycle, and a turn after it. + static func watch(_ host: ModalHost) -> [NSObjectProtocol] { + let edges: [(Notification.Name, String)] = [ + (UIApplication.willResignActiveNotification, "willResignActive"), + (UIApplication.didEnterBackgroundNotification, "didEnterBackground"), + (UIApplication.willEnterForegroundNotification, "willEnterForeground"), + (UIApplication.didBecomeActiveNotification, "didBecomeActive"), + (UIApplication.didReceiveMemoryWarningNotification, "memoryWarning"), + ] + return edges.map { name, edge in + NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak host] _ in + host?.traceLayers(edge) + DispatchQueue.main.async { [weak host] in host?.traceLayers(edge + " +1 turn") } + } + } + } +} +#endif diff --git a/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift b/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift index f9918a6db..b52ba255b 100644 --- a/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift +++ b/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift @@ -152,6 +152,32 @@ final class ModalStackIOSTests: XCTestCase { XCTAssertEqual(primary.viewControllers, background) } + /// Each answer to UIKit's swipe down goes to the sheet trace with the terms it read. + func testTheSheetTraceRecordsEachDismissalAnswerAndWhatItRead() throws { + guard UIApplication.shared.connectedScenes.contains(where: { $0 is UIWindowScene }) else { + throw missing("scene", "the trace answers UIKit's presented sheet") + } + let session = try fixture("sheet-trace", plan: "EXACT_PUSHED_TITLE_PLAN", fullScreen: true) + let p = session.presenter, agent = Agent(session: session) + let file = try XCTUnwrap(AppFiles.url(SheetTrace.path)) + try? FileManager.default.removeItem(at: file) + try press(session, "home-open-inline") + until("the background stack settles") { !agent.nativeInFlight() } + try press(session, "inline-open-sheet") + until("the sheet's own navigation settles") { p.navigation.modalNavigation != nil && !agent.nativeInFlight() } + let sheet = try XCTUnwrap(presented().last?.presentationController) + XCTAssertTrue(p.modals.presentationControllerShouldDismiss(sheet)) + try press(session, "sheet-open-long") + until("the push inside the sheet settles") { p.navigation.modalNavigation?.viewControllers.count == 2 && !agent.nativeInFlight() } + XCTAssertTrue(p.modals.presentationControllerShouldDismiss(sheet)) + let lines = try String(contentsOf: file, encoding: .utf8).split(separator: "\n").map(String.init) + XCTAssertTrue(lines.contains { $0.contains(" present route=#") && $0.contains("modal=false") }, "the presentation and its flag") + let answers = lines.filter { $0.contains(" shouldDismiss true ") } + XCTAssertEqual(answers.count, 2, "a line only when what the answer read changes: \(answers)") + XCTAssertTrue(answers.first?.contains("inactive=false") == true) + XCTAssertTrue(answers.last?.contains("inactive=true sheetDismissal=true") == true, "the push inside the sheet: \(answers)") + } + func testBackHistoryUsesTheChosenDestinationInThePrimaryStack() throws { guard UIApplication.shared.connectedScenes.contains(where: { $0 is UIWindowScene }) else { throw missing("scene", "native Back history uses UIKit's completed transition") From 68347bfa0b701fa7ae552507578f2df1ab640f56 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sun, 15 Nov 2026 09:08:04 -0500 Subject: [PATCH 2/2] The sheet trace reads the runtime only when a swipe's answer changes, forgets its observers, and keeps no locations --- host/apple/Sources/ExactKit/IOS/BackIOS.swift | 2 +- host/apple/Sources/ExactKit/IOS/ModalIOS.swift | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/host/apple/Sources/ExactKit/IOS/BackIOS.swift b/host/apple/Sources/ExactKit/IOS/BackIOS.swift index 6d629a0d3..106d3b882 100644 --- a/host/apple/Sources/ExactKit/IOS/BackIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/BackIOS.swift @@ -96,7 +96,7 @@ extension NavigationHost { var traceBack: String { let route = selectedRoute let beneath = route?.props["navigationKey"].flatMap { presenter.session?.runtime.locationBeneath($0) } - return "selected=\(selectedKey ?? "nil") selectedRoute=\(route.map { "#\($0.id)" } ?? "nil") control=\(backControl.map { "#\($0.id)" } ?? "nil") declared=\(route.map(declaresBack) ?? false) beneath=\(beneath ?? "nil") servingMain=\(Owner.shared.isServingMain) window=\(presenter.session?.view?.window != nil)" + return "selected=\(selectedKey ?? "nil") selectedRoute=\(route.map { "#\($0.id)" } ?? "nil") control=\(backControl.map { "#\($0.id)" } ?? "nil") declared=\(route.map(declaresBack) ?? false) beneath=\(beneath.map { $0.isEmpty ? "empty" : "some" } ?? "nil") servingMain=\(Owner.shared.isServingMain) window=\(presenter.session?.view?.window != nil)" } /// Why Back does not go from the selected route, for the journal. diff --git a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift index dd506551f..823b8d44c 100644 --- a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift @@ -383,6 +383,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { super.init() traceObservers = SheetTrace.watch(self) } + deinit { traceObservers.forEach(NotificationCenter.default.removeObserver) } #if os(iOS) /// Why a word of a bound `navigationDetent` is dropped. @@ -840,10 +841,10 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { return false } let refuses = refusesDismissal(of: layer.route) - // UIKit asks every frame of a drag: a line only when the answer or what it read changes. - let line = "shouldDismiss \(!refuses) \(traceState(layer))" - if line != lastAsked { SheetTrace.note(line) } - lastAsked = line + // UIKit asks every frame of a drag: the line, which reads the runtime, only when this key changes. + let asked = "\(refuses) \(layer.controller.isModalInPresentation) \(layer.route.id) \(presenter.navigation.selectedKey ?? "") \(presenter.navigation.isInactiveRoute(containing: layer.route))" + if asked != lastAsked { SheetTrace.note("shouldDismiss \(!refuses) \(traceState(layer))") } + lastAsked = asked return !refuses } private var lastAsked: String?