diff --git a/AppTests/LiveDocumentTests.swift b/AppTests/LiveDocumentTests.swift index df04a34..febda85 100644 --- a/AppTests/LiveDocumentTests.swift +++ b/AppTests/LiveDocumentTests.swift @@ -5,7 +5,7 @@ // LiveDocument carrying out LiveSessionState's decisions against // FakeServers: the banners for a lost channel and an app in the // background, which channel's events count, the background probe, the -// reconnect to the same app, and the retried refresh after it returns. +// reconnect to the same app, and refreshing only when requested on iOS. // import AppKit @@ -24,6 +24,30 @@ extension HostAppTests { return app } + private func makeIOSServer(bundleIdentifier: String) -> FakeServer { + let server = FakeServer(bundleIdentifier: bundleIdentifier) + server.appInfo.deviceDescription = "Test iPhone" + server.appInfo.osDescription = "iOS 27.0" + server.appInfo.deviceType = .others + server.appInfo.appInfoIdentifier = 1 + server.appInfo.screenScale = 2 + return server + } + + private func makeHierarchy(for appInfo: InspectedAppInfo?) -> HierarchyInfo { + let hierarchy = HierarchyInfo() + hierarchy.appInfo = appInfo + hierarchy.displayItems = [] + return hierarchy + } + + private func closeInspector(_ document: LiveDocument) { + document.close() + // Closing the window schedules reopening Launch on the main queue. + // Its scans would reach the other tests' ports. + DispatchQueue.main.async { NavigationManager.shared.closeLaunch() } + } + /// Lets events already queued on the main queue reach the document. private func drainMainQueue() async { try? await Task.sleep(for: .milliseconds(200)) @@ -44,7 +68,7 @@ extension HostAppTests { let endedChannelDocument = LiveDocument(inspectableApp: makeApp(server, channel: endedChannel)) defer { endedChannelDocument.close() } #expect(endedChannelDocument.connectionLossBannerMessage != nil) - #expect(endedChannelDocument.applicationInBackgroundBannerMessage == nil) + #expect(endedChannelDocument.applicationStatusBannerMessage == nil) } /// Entering an app that is already open — from the launch window, the @@ -123,14 +147,14 @@ extension HostAppTests { otherServer.pushApplicationState(isActive: false) #expect(await waitUntil { reports.elements.contains { $0.channel === otherChannel } }) await drainMainQueue() - #expect(document.applicationInBackgroundBannerMessage == nil) + #expect(document.applicationStatusBannerMessage == nil) watchedServer.pushApplicationState(isActive: false) - #expect(await waitUntil { document.applicationInBackgroundBannerMessage != nil }) + #expect(await waitUntil { document.applicationStatusBannerMessage != nil }) #expect(document.connectionLossBannerMessage == nil) watchedServer.pushApplicationState(isActive: true) - #expect(await waitUntil { document.applicationInBackgroundBannerMessage == nil }) + #expect(await waitUntil { document.applicationStatusBannerMessage == nil }) } /// A Server that does not push its state: a refused request shows @@ -138,39 +162,45 @@ extension HostAppTests { /// the app is back. @Test(.timeLimit(.minutes(1))) func backgroundProbeClearsTheBannerOnceAPingIsAnswered() async throws { - let server = FakeServer() + let server = makeIOSServer(bundleIdentifier: "com.lookinside.apptests.background-probe") server.behavior = .inBackground defer { server.shutDown() } let channel = server.connectChannel() let document = LiveDocument(inspectableApp: makeApp(server, channel: channel)) - defer { document.close() } + defer { closeInspector(document) } + document.makeWindowControllers() await #expect(throws: (any Error).self) { try await ConnectionManager.shared.ping(channel: channel) } - #expect(await waitUntil { document.applicationInBackgroundBannerMessage != nil }) + #expect(await waitUntil { document.applicationStatusBannerMessage != nil }) let pingsBeforeProbe = server.receivedRequestTypes.count server.behavior = .answering let probeWindow = LiveSessionState.backgroundProbeInterval + .seconds(3) - #expect(await waitUntil(timeout: probeWindow) { document.applicationInBackgroundBannerMessage == nil }) + #expect(await waitUntil(timeout: probeWindow) { document.applicationStatusBannerMessage == nil }) + await drainMainQueue() #expect(server.receivedRequestTypes.count > pingsBeforeProbe) #expect(server.receivedRequestTypes.dropFirst(pingsBeforeProbe).allSatisfy { $0 == UInt32(RequestType.ping) }) } /// The app's process went away and came back on a new channel: the /// scan every 3 seconds finds it by identity, and the document - /// switches to it and clears the banner. + /// switches to it and refreshes the hierarchy on macOS. @Test(.timeLimit(.minutes(1))) - func reconnectAdoptsTheSameAppOnItsNewChannel() async throws { + func reconnectAdoptsAndRefreshesTheSameMacAppOnItsNewChannel() async throws { let server = FakeServer(appName: "Reconnect Target", bundleIdentifier: "com.lookinside.apptests.reconnect") + server.appInfo.screenScale = 2 + let hierarchy = makeHierarchy(for: server.appInfo) + server.responders[UInt32(RequestType.hierarchy)] = { _ in hierarchy } defer { server.shutDown() } let port = try server.listen() let apps = await AppsManager.shared.fetchAppInfos(needImages: false, localInfos: nil) let originalApp = try #require(apps.first { $0.origin?.port == port }) let originalChannel = try #require(originalApp.channel) let document = LiveDocument(inspectableApp: originalApp) - defer { document.close() } + defer { closeInspector(document) } + document.makeWindowControllers() server.disconnectAll() #expect(await waitUntil { document.connectionLossBannerMessage != nil }) @@ -182,49 +212,104 @@ extension HostAppTests { #expect(adoptedChannel.port == port) #expect(document.inspectableApp.appInfo?.appBundleIdentifier == "com.lookinside.apptests.reconnect") #expect(document.connectionLossBannerMessage == nil) + #expect(await waitUntil { document.hierarchyDataSource?.rawHierarchyInfo?.appInfo?.appName == "Reconnect Target" }) // The new channel is watched: its end shows the banner again. server.disconnectAll() #expect(await waitUntil { document.connectionLossBannerMessage != nil }) } - /// The refresh after the app returns is refused while the window - /// still fetches; it is tried again until that fetch is over. @Test(.timeLimit(.minutes(1))) - func refreshAfterReturnWaitsForTheRunningFetch() async throws { - let server = FakeServer() - server.heldRequestTypes = [UInt32(RequestType.hierarchy)] + func foregroundPushWaitsForExplicitRefresh() async throws { + let server = makeIOSServer(bundleIdentifier: "com.lookinside.apptests.foreground") + let hierarchy = makeHierarchy(for: server.appInfo) + let hierarchyRequest = UInt32(RequestType.hierarchy) + server.responders[hierarchyRequest] = { _ in hierarchy } defer { server.shutDown() } let channel = server.connectChannel() let document = LiveDocument(inspectableApp: makeApp(server, channel: channel)) - defer { document.close() } + defer { closeInspector(document) } document.makeWindowControllers() let windowController = try #require(document.staticWindowController) - let hierarchyRequestCount = { server.receivedRequestTypes.filter { $0 == UInt32(RequestType.hierarchy) }.count } - - let runningFetch = Task { try? await windowController.reloadHierarchy(initiator: .host) } - #expect(await waitUntil { hierarchyRequestCount() == 1 }) server.pushApplicationState(isActive: false) - #expect(await waitUntil { document.applicationInBackgroundBannerMessage != nil }) + #expect(await waitUntil { document.applicationStatusBannerMessage != nil }) server.pushApplicationState(isActive: true) - #expect(await waitUntil { document.applicationInBackgroundBannerMessage == nil }) - // The refresh was refused; give it a retry or two while the - // first fetch still runs. - try await Task.sleep(for: AutomaticRefreshRetryPolicy.defaultRetryInterval * 3) - #expect(hierarchyRequestCount() == 1) + #expect(await waitUntil { document.applicationStatusBannerMessage == nil }) + await drainMainQueue() + #expect(!server.receivedRequestTypes.contains(hierarchyRequest)) - server.answerHeldRequests(with: ConnectionResponseAttachment.attachment(error: ConnectionError.inner)) - _ = await runningFetch.value - #expect(await waitUntil { hierarchyRequestCount() == 2 }) + let refreshed = try await windowController.reloadHierarchy(initiator: .host) + #expect(refreshed?.appInfo?.appInfoIdentifier == 1) + #expect(server.receivedRequestTypes.filter { $0 == hierarchyRequest }.count == 1) + } - server.answerHeldRequests(with: ConnectionResponseAttachment.attachment(error: ConnectionError.inner)) + @Test(.timeLimit(.minutes(1))) + func reconnectingToTheSameIOSProcessDoesNotRefresh() async throws { + let server = makeIOSServer(bundleIdentifier: "com.lookinside.apptests.same-ios-process") + defer { server.shutDown() } + let port = try server.listen() + let apps = await AppsManager.shared.fetchAppInfos(needImages: false, localInfos: nil) + let originalApp = try #require(apps.first { $0.origin?.port == port }) + let originalChannel = try #require(originalApp.channel) + let document = LiveDocument(inspectableApp: originalApp) + defer { closeInspector(document) } + document.makeWindowControllers() - // Closing the inspector window brings the launch window back - // (AppDelegate), whose scans would reach the other tests' ports. - document.close() - _ = await waitUntil(timeout: .seconds(1)) { NavigationManager.shared.launchWindowController != nil } - NavigationManager.shared.closeLaunch() + server.disconnectAll() + #expect(await waitUntil { document.connectionLossBannerMessage != nil }) + #expect(await waitUntil(timeout: .seconds(10)) { document.inspectableApp !== originalApp }) + #expect(document.inspectableApp.channel !== originalChannel) + #expect(document.inspectableApp.channel?.isConnected == true) + #expect(document.connectionLossBannerMessage == nil) + await drainMainQueue() + #expect(!server.receivedRequestTypes.contains(UInt32(RequestType.hierarchy))) + + server.disconnectAll() + #expect(await waitUntil { document.connectionLossBannerMessage != nil }) + } + + @Test(.timeLimit(.minutes(1))) + func reconnectingToANewIOSProcessWaitsForExplicitRefresh() async throws { + let server = makeIOSServer(bundleIdentifier: "com.lookinside.apptests.new-ios-process") + defer { server.shutDown() } + let port = try server.listen() + let apps = await AppsManager.shared.fetchAppInfos(needImages: false, localInfos: nil) + let originalApp = try #require(apps.first { $0.origin?.port == port }) + let document = LiveDocument(inspectableApp: originalApp) + defer { closeInspector(document) } + document.makeWindowControllers() + let windowController = try #require(document.staticWindowController) + windowController.applyHierarchyInfo(makeHierarchy(for: originalApp.appInfo), for: originalApp, keepState: false) + + server.appInfo.appInfoIdentifier = 2 + let hierarchy = makeHierarchy(for: server.appInfo) + let hierarchyRequest = UInt32(RequestType.hierarchy) + server.disconnectAll() + #expect(await waitUntil { document.connectionLossBannerMessage != nil }) + #expect(await waitUntil(timeout: .seconds(10)) { document.applicationStatusBannerMessage != nil }) + #expect(document.connectionLossBannerMessage == nil) + await drainMainQueue() + #expect(!server.receivedRequestTypes.contains(hierarchyRequest)) + #expect(document.inspectableApp === originalApp) + #expect(document.inspectableApp.channel?.isConnected != true) + #expect(windowController.hierarchyDataSource.rawHierarchyInfo?.appInfo?.appInfoIdentifier == 1) + + await #expect(throws: (any Error).self) { + try await windowController.reloadHierarchy(initiator: .host) + } + #expect(document.inspectableApp === originalApp) + #expect(document.applicationStatusBannerMessage != nil) + #expect(windowController.hierarchyDataSource.rawHierarchyInfo?.appInfo?.appInfoIdentifier == 1) + + server.responders[hierarchyRequest] = { _ in hierarchy } + let refreshed = try await windowController.reloadHierarchy(initiator: .host) + #expect(refreshed?.appInfo?.appInfoIdentifier == 2) + #expect(server.receivedRequestTypes.filter { $0 == hierarchyRequest }.count == 2) + #expect(document.inspectableApp !== originalApp) + #expect(windowController.hierarchyDataSource.rawHierarchyInfo?.appInfo?.appInfoIdentifier == 2) + #expect(document.applicationStatusBannerMessage == nil) + #expect(document.connectionLossBannerMessage == nil) } } } diff --git a/LookInside/Base/ConnectionTipsBinding.swift b/LookInside/Base/ConnectionTipsBinding.swift index 434c758..18306bb 100644 --- a/LookInside/Base/ConnectionTipsBinding.swift +++ b/LookInside/Base/ConnectionTipsBinding.swift @@ -5,8 +5,8 @@ // Drives a view controller's "Reconnecting…" banner from its live // document: the banner shows (and pulses) while the document has a // connection-loss message and follows the document's current app icon. -// A second, neutral banner shows the document's message while the app is -// in the background. +// A second, neutral banner shows when the app is in the background or +// when the user needs to reload its hierarchy. // Used by BaseViewController, which stays Objective-C while ObjC view // controllers still subclass it. // @@ -37,10 +37,10 @@ final class ConnectionTipsBinding: NSObject { containerView.needsLayout = true } }, - document.observe(\.applicationInBackgroundBannerMessage, options: [.initial, .new]) { [weak backgroundTipsView, weak viewController] document, _ in + document.observe(\.applicationStatusBannerMessage, options: [.initial, .new]) { [weak backgroundTipsView, weak viewController] document, _ in guard let backgroundTipsView, let viewController else { return } let containerView = viewController.view - let message = document.applicationInBackgroundBannerMessage ?? "" + let message = document.applicationStatusBannerMessage ?? "" if message.isEmpty { backgroundTipsView.isHidden = true } else { diff --git a/LookInside/Connection/LiveDocument.swift b/LookInside/Connection/LiveDocument.swift index d04bd8d..5ff03a7 100644 --- a/LookInside/Connection/LiveDocument.swift +++ b/LookInside/Connection/LiveDocument.swift @@ -6,9 +6,9 @@ // app over its channel. It is untitled, never autosaves, and Save As exports // the current hierarchy as a `.lookin` file. When the app's channel ends, // the document shows a banner and looks for the same app every 3 seconds; -// when it reappears, the document switches to its new channel and fetches -// the hierarchy again. While the app is in the background the document -// shows another banner and refreshes once the app is back. +// when it reappears, the document watches its new channel. AppKit apps +// refresh on reconnect. UIKit apps keep their tree when they return and +// wait for a reload before switching to a new process. // `LiveSessionState` makes those decisions; this class carries them out. // @@ -38,11 +38,17 @@ final class LiveDocument: NSDocument { /// KVO; the window shows it as a banner. @objc private(set) dynamic var connectionLossBannerMessage: String? - /// Set while the app is in the background, which keeps it from - /// answering; nil otherwise. Never set together with - /// `connectionLossBannerMessage`. Observable with KVO; the window shows it - /// as a banner. - @objc private(set) dynamic var applicationInBackgroundBannerMessage: String? + /// Explains why the app cannot be inspected yet, while it is in the + /// background or while a new process is waiting for a hierarchy reload. + @objc private(set) dynamic var applicationStatusBannerMessage: String? + + /// Only hierarchy reloads can use this app until the new tree arrives. + /// Requests for objects in the old tree still use the disconnected app. + private(set) var reconnectedAppAwaitingReload: InspectableApp? + + var connectedChannel: ServerChannel? { + (reconnectedAppAwaitingReload ?? inspectableApp).channel + } private var sessionState = LiveSessionState() @@ -57,7 +63,7 @@ final class LiveDocument: NSDocument { private var applicationStateTask: Task? private var reconnectTask: Task? private var backgroundProbeTask: Task? - /// The refresh started after the app returned, with its retries. + /// The refresh started after a Mac app reconnected, with its retries. private var automaticRefreshTask: Task? private static let automaticRefreshRetryPolicy = AutomaticRefreshRetryPolicy() @@ -188,6 +194,7 @@ final class LiveDocument: NSDocument { backgroundProbeTask = nil automaticRefreshTask?.cancel() automaticRefreshTask = nil + reconnectedAppAwaitingReload = nil super.close() } @@ -198,7 +205,7 @@ final class LiveDocument: NSDocument { /// The app holds its channel weakly, so the channel may already be gone, /// or ended, when this runs; that counts as an end, and the document /// reconnects. - private func watchCurrentChannel() { + private func watchCurrentChannel(reloadHierarchyOnReconnect: Bool = false) { channelEndTask?.cancel() channelEndTask = nil applicationStateTask?.cancel() @@ -206,7 +213,7 @@ final class LiveDocument: NSDocument { // A refresh still waiting to be retried was meant for the old one. automaticRefreshTask?.cancel() automaticRefreshTask = nil - guard let channel = inspectableApp.channel, channel.isConnected else { + guard let channel = connectedChannel, channel.isConnected else { handle(.watchedChannel(isAlive: false)) return } @@ -229,7 +236,7 @@ final class LiveDocument: NSDocument { } } } - handle(.watchedChannel(isAlive: true)) + handle(.watchedChannel(isAlive: true, reloadHierarchyOnReconnect: reloadHierarchyOnReconnect)) } /// Applies `event` to the session, shows its banner and carries out @@ -248,6 +255,7 @@ final class LiveDocument: NSDocument { for action in actions { switch action { case .startReconnecting: + reconnectedAppAwaitingReload = nil if let appInfo = inspectableApp.appInfo { lastKnownAppInfo = appInfo } @@ -258,7 +266,7 @@ final class LiveDocument: NSDocument { automaticRefreshTask = nil attemptAutoReconnect() case .reloadHierarchy: - reloadHierarchyAfterReturn() + reloadHierarchyAfterReconnect() case let .startBackgroundProbe(interval): startBackgroundProbe(interval: interval) case .stopBackgroundProbe: @@ -273,18 +281,20 @@ final class LiveDocument: NSDocument { let appName = (appInfo?.appName).flatMap { $0.isEmpty ? nil : $0 } ?? NSLocalizedString("Inspected app", comment: "") let lossMessage: String? - let backgroundMessage: String? + let applicationMessage: String? switch sessionState.banner { case .none: lossMessage = nil - backgroundMessage = nil + applicationMessage = reconnectedAppAwaitingReload.map { _ in + String(format: NSLocalizedString("Connection to %@ restored. Reload to inspect the current hierarchy.", comment: "Banner when a reconnected app needs a manual hierarchy reload; %@ is the app's name"), appName) + } case .connectionLost: lossMessage = String(format: NSLocalizedString("Connection to %@ lost. Trying to reconnect…", comment: ""), appName) - backgroundMessage = nil + applicationMessage = nil case .applicationInBackground: lossMessage = nil - backgroundMessage = String( - format: NSLocalizedString("%@ is in the background. LookInside refreshes when it returns.", comment: "Banner over a live inspector window while the inspected app is in the background; %@ is the app's name"), + applicationMessage = String( + format: NSLocalizedString("%@ is in the background.", comment: "Banner while the inspected app is in the background; %@ is the app's name"), appName ) } @@ -292,8 +302,8 @@ final class LiveDocument: NSDocument { if connectionLossBannerMessage != lossMessage { connectionLossBannerMessage = lossMessage } - if applicationInBackgroundBannerMessage != backgroundMessage { - applicationInBackgroundBannerMessage = backgroundMessage + if applicationStatusBannerMessage != applicationMessage { + applicationStatusBannerMessage = applicationMessage } } @@ -312,13 +322,19 @@ final class LiveDocument: NSDocument { } } - /// Switches to the app found again; watching its channel fetches the - /// hierarchy again (`LiveSessionState`), since the tree on screen belongs - /// to the old process. private func adoptReconnectedApp(_ newApp: InspectableApp) { - replaceApp(with: newApp) + let osDescription = newApp.appInfo?.osDescription?.lowercased() ?? "" + let reloadAutomatically = osDescription.hasPrefix("macos") || osDescription.hasPrefix("os x") + || (osDescription.isEmpty && newApp.appInfo?.deviceType == .mac) + let treeProcessID = hierarchyDataSource?.rawHierarchyInfo?.appInfo?.appInfoIdentifier + ?? inspectableApp.appInfo?.appInfoIdentifier ?? 0 + if reloadAutomatically || (treeProcessID != 0 && treeProcessID == newApp.appInfo?.appInfoIdentifier) { + replaceApp(with: newApp) + } else { + reconnectedAppAwaitingReload = newApp + } reconnectTask = nil - watchCurrentChannel() + watchCurrentChannel(reloadHierarchyOnReconnect: reloadAutomatically) } /// Makes `app` the one this document inspects: its window was just @@ -329,9 +345,13 @@ final class LiveDocument: NSDocument { /// stops. func bind(to app: InspectableApp) { guard app !== inspectableApp else { return } - let isOnAnotherChannel = app.channel !== inspectableApp.channel + let isOnAnotherChannel = app.channel !== connectedChannel + reconnectedAppAwaitingReload = nil replaceApp(with: app) - guard isOnAnotherChannel else { return } + guard isOnAnotherChannel else { + updateBanners() + return + } reconnectTask?.cancel() reconnectTask = nil watchCurrentChannel() @@ -394,15 +414,14 @@ final class LiveDocument: NSDocument { deviceType: -1 ) - /// The refresh after a reconnect or after the app came back from the - /// background. A refresh the window refuses because a fetch or the - /// detail sync is running is tried again once that is over + /// The refresh after an AppKit app reconnects. If the window refuses + /// because a fetch or a detail sync is running, try again once it ends /// (`AutomaticRefreshRetryPolicy`); a refresh started meanwhile, a new /// channel and closing the document cancel the retries. Any other /// failure leaves the old tree: a refusal in the background shows its /// banner through the connection manager's report, and other errors are /// the ones a manual reload would show. - private func reloadHierarchyAfterReturn() { + private func reloadHierarchyAfterReconnect() { automaticRefreshTask?.cancel() automaticRefreshTask = Task { [weak self] in var retriesSoFar = 0 @@ -420,7 +439,7 @@ final class LiveDocument: NSDocument { } } - /// One attempt of `reloadHierarchyAfterReturn()`; nil without a window. + /// One attempt of `reloadHierarchyAfterReconnect()`; nil without a window. private func attemptAutomaticRefresh() async -> AutomaticRefreshRetryPolicy.Outcome? { guard let staticWindowController else { return nil } do { @@ -450,7 +469,7 @@ final class LiveDocument: NSDocument { while !Task.isCancelled { try? await Task.sleep(for: interval) guard !Task.isCancelled, let self else { return } - guard let channel = inspectableApp.channel, channel.isConnected else { return } + guard let channel = connectedChannel, channel.isConnected else { return } do { try await ConnectionManager.shared.ping(channel: channel) } catch { diff --git a/LookInside/Connection/LiveDocumentController.swift b/LookInside/Connection/LiveDocumentController.swift index bb47b92..8723e85 100644 --- a/LookInside/Connection/LiveDocumentController.swift +++ b/LookInside/Connection/LiveDocumentController.swift @@ -43,6 +43,6 @@ final class LiveDocumentController: NSObject { guard let channel else { return nil } return NSDocumentController.shared.documents .compactMap { $0 as? LiveDocument } - .first { $0.inspectableApp.channel === channel } + .first { $0.connectedChannel === channel } } } diff --git a/LookInside/Localizable.xcstrings b/LookInside/Localizable.xcstrings index cfe4038..a58dbda 100644 --- a/LookInside/Localizable.xcstrings +++ b/LookInside/Localizable.xcstrings @@ -676,85 +676,85 @@ } } }, - "%@ is in the background. LookInside refreshes when it returns." : { - "comment" : "Banner over a live inspector window while the inspected app is in the background; %@ is the app's name", + "%@ is in the background." : { + "comment" : "Banner while the inspected app is in the background; %@ is the app's name", "localizations" : { "ar" : { "stringUnit" : { "state" : "translated", - "value" : "%@ في الخلفية. سيُحدِّث LookInside البيانات عند عودته." + "value" : "%@ في الخلفية." } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "%@ ist im Hintergrund. LookInside aktualisiert, sobald die App zurückkehrt." + "value" : "%@ ist im Hintergrund." } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "%@ is in the background. LookInside refreshes when it returns." + "value" : "%@ is in the background." } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "%@ está en segundo plano. LookInside se actualizará cuando vuelva." + "value" : "%@ está en segundo plano." } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "%@ est en arrière-plan. LookInside actualisera dès son retour." + "value" : "%@ est en arrière-plan." } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "%@ è in background. LookInside si aggiornerà al suo ritorno." + "value" : "%@ è in background." } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%@ はバックグラウンドにあります。戻ると LookInside が更新します。" + "value" : "%@ はバックグラウンドにあります。" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "%@이(가) 백그라운드에 있습니다. 돌아오면 LookInside가 새로 고칩니다." + "value" : "%@이(가) 백그라운드에 있습니다." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "%@ está em segundo plano. O LookInside atualizará quando ele voltar." + "value" : "%@ está em segundo plano." } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "%@ в фоновом режиме. LookInside обновит данные, когда приложение вернётся." + "value" : "%@ в фоновом режиме." } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "%@ đang chạy nền. LookInside sẽ làm mới khi ứng dụng quay lại." + "value" : "%@ đang chạy nền." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%@ 在后台。回到前台后 LookInside 会自动刷新。" + "value" : "%@ 在后台。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%@ 在背景執行。回到前景後 LookInside 會自動重新整理。" + "value" : "%@ 在背景執行。" } } } @@ -7680,6 +7680,89 @@ } } }, + "Connection to %@ restored. Reload to inspect the current hierarchy." : { + "comment" : "Banner when a reconnected app needs a manual hierarchy reload; %@ is the app's name", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "تمت استعادة الاتصال بـ %@. أعد التحميل لفحص التسلسل الهرمي الحالي." + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Die Verbindung zu %@ wurde wiederhergestellt. Lade die aktuelle Hierarchie neu, um sie zu prüfen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Connection to %@ restored. Reload to inspect the current hierarchy." + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Se restableció la conexión con %@. Recarga para inspeccionar la jerarquía actual." + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "La connexion à %@ est rétablie. Rechargez pour inspecter la hiérarchie actuelle." + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "Connessione a %@ ripristinata. Ricarica per ispezionare la gerarchia attuale." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ に再接続しました。現在の階層を調べるには再読み込みしてください。" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@에 다시 연결했습니다. 현재 계층 구조를 검사하려면 다시 불러오세요." + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "A conexão com %@ foi restabelecida. Recarregue para inspecionar a hierarquia atual." + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Соединение с %@ восстановлено. Обновите данные, чтобы изучить текущую иерархию." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã kết nối lại với %@. Tải lại để kiểm tra cấu trúc phân cấp hiện tại." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已重新连接到 %@。点击“重新载入”查看当前层级。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已重新連線至 %@。按一下「重新載入」查看目前的階層。" + } + } + } + }, "Console" : { "localizations" : { "ar" : { diff --git a/LookInside/MCPBridge/MCPBridgeEventPublisher.swift b/LookInside/MCPBridge/MCPBridgeEventPublisher.swift index f08b9b0..7ce911f 100644 --- a/LookInside/MCPBridge/MCPBridgeEventPublisher.swift +++ b/LookInside/MCPBridge/MCPBridgeEventPublisher.swift @@ -205,7 +205,10 @@ final class MCPBridgeEventPublisher { /// name a target identifier the client already knows rather than an /// opaque channel the bridge protocol never exposes. private func document(forChannel channel: ServerChannel) -> LiveDocument? { - LiveDocumentController.shared.liveDocument(for: channel) + guard let document = LiveDocumentController.shared.liveDocument(for: channel), + document.inspectableApp.channel === channel + else { return nil } + return document } private func publishDisconnected(channel: ServerChannel) { diff --git a/LookInside/MCPBridge/MCPBridgeInspectionModels.swift b/LookInside/MCPBridge/MCPBridgeInspectionModels.swift index 1308c67..67e758b 100644 --- a/LookInside/MCPBridge/MCPBridgeInspectionModels.swift +++ b/LookInside/MCPBridge/MCPBridgeInspectionModels.swift @@ -501,7 +501,7 @@ struct MCPBridgeSelectorListResult: Sendable, Codable { /// same screen it already had. Reporting both counts answers that without a /// follow-up `hierarchy.read`. struct MCPBridgeRefreshResult: Sendable, Codable { - /// Echo of the requested target. + /// The refreshed target, which may have a new identifier after an app restart. let targetIdentifier: String /// Top-level windows / scenes after the reload. Usable directly as diff --git a/LookInside/MCPBridge/MCPBridgeRefreshService.swift b/LookInside/MCPBridge/MCPBridgeRefreshService.swift index 6e1c051..9cbd101 100644 --- a/LookInside/MCPBridge/MCPBridgeRefreshService.swift +++ b/LookInside/MCPBridge/MCPBridgeRefreshService.swift @@ -110,7 +110,7 @@ final class MCPBridgeRefreshService { .map { MCPBridgeLiveDocumentLookup.objectIdentifierString(for: $0) } let result = MCPBridgeRefreshResult( - targetIdentifier: targetIdentifier, + targetIdentifier: document.inspectableApp.appInfo.map { String($0.appInfoIdentifier) } ?? targetIdentifier, rootObjectIdentifiers: rootIdentifiers, nodeCount: document.hierarchyDataSource?.rawFlatItems?.count ?? 0, previousNodeCount: previousNodeCount, diff --git a/LookInside/Static/StaticWindowController.swift b/LookInside/Static/StaticWindowController.swift index b86341d..2f94d6f 100644 --- a/LookInside/Static/StaticWindowController.swift +++ b/LookInside/Static/StaticWindowController.swift @@ -371,7 +371,8 @@ final class StaticWindowController: WindowController, NSToolbarDelegate, @precon ))) return } - guard let app = inspectableApp else { + let pendingApp = (document as? LiveDocument)?.reconnectedAppAwaitingReload + guard let app = pendingApp ?? inspectableApp else { completion(.failure(ReloadError.make( ReloadError.noInspectableApp, NSLocalizedString("This window is not attached to an app.", comment: "") @@ -413,8 +414,20 @@ final class StaticWindowController: WindowController, NSToolbarDelegate, @precon } switch result { case let .info(info): - viewController.progressView.finish(completion: nil) - hierarchyDataSource.reload(with: info, keepState: true) + if let pendingApp { + guard let info, pendingApp.channel?.isConnected == true, + (document as? LiveDocument)?.reconnectedAppAwaitingReload === pendingApp + else { + viewController.progressView.resetToZero() + isFetchingHierarchy = false + completion(.failure(info == nil ? ConnectionError.inner : ConnectionError.noConnect)) + return + } + applyHierarchyInfo(info, for: pendingApp, keepState: false) + } else { + viewController.progressView.finish(completion: nil) + hierarchyDataSource.reload(with: info, keepState: true) + } isFetchingHierarchy = false PerformanceReporter.sharedInstance().didFetchHierarchy() completion(.success(info)) @@ -551,6 +564,7 @@ final class StaticWindowController: WindowController, NSToolbarDelegate, @precon @objc(_handleShowBackingLayersDidChange:) private func handleShowBackingLayersDidChange(_: MessageActionParameters) { + guard (document as? LiveDocument)?.reconnectedAppAwaitingReload == nil else { return } // No app bound or a reload already running: the new value still // applies on the next manual reload, so refusals stay quiet. reloadHierarchy { _ in } @@ -805,14 +819,21 @@ final class StaticWindowController: WindowController, NSToolbarDelegate, @precon /// here, and so does a hierarchy the launch window or the app picker /// fetched for this window. func applyHierarchyInfo(_ info: HierarchyInfo?, for app: InspectableApp, keepState: Bool) { + let liveDocument = document as? LiveDocument + let reconnectedChannel = liveDocument?.reconnectedAppAwaitingReload?.channel + let replacesProcess = reconnectedChannel != nil && reconnectedChannel === app.channel + if replacesProcess, info == nil { + viewController.progressView.resetToZero() + return + } viewController.progressView.finish(completion: nil) inspectableApp = app asyncUpdateManager.inspectableApp = app // Both hold the app weakly; the document keeps it alive, so it has // to take the app on too, or the window loses it once the caller — // the launch window, the app picker — lets its scan's copy go. - (document as? LiveDocument)?.bind(to: app) - hierarchyDataSource.reload(with: info, keepState: keepState) + liveDocument?.bind(to: app) + hierarchyDataSource.reload(with: info, keepState: keepState && !replacesProcess) // Move this bundle id to the front of the expansion-state LRU, so // inspected apps aren't evicted just because nothing was toggled yet. diff --git a/Packages/LookInsideHostCore/Sources/LookInsideHostCore/LiveSessionState.swift b/Packages/LookInsideHostCore/Sources/LookInsideHostCore/LiveSessionState.swift index 61e475a..1298f75 100644 --- a/Packages/LookInsideHostCore/Sources/LookInsideHostCore/LiveSessionState.swift +++ b/Packages/LookInsideHostCore/Sources/LookInsideHostCore/LiveSessionState.swift @@ -4,8 +4,8 @@ // // What a live inspection window knows about its app's connection, and what // it does when that changes: the banner it shows, reconnecting after the -// channel ended, refreshing the hierarchy once the app is back, and -// watching an app that went to the background. `LiveDocument` feeds it the +// channel ended, optionally refreshing on reconnect, and watching an app +// that went to the background. `LiveDocument` feeds it the // events and carries out the actions. // @@ -25,7 +25,7 @@ public struct LiveSessionState: Equatable, Sendable { /// The window started watching its app's channel: when it opened, or /// after a reconnect handed it a new one. `isAlive` is false when the /// channel was already released or ended by then. - case watchedChannel(isAlive: Bool) + case watchedChannel(isAlive: Bool, reloadHierarchyOnReconnect: Bool = true) /// The watched channel ended. case channelEnded /// The Server pushed its application's state (Servers that predate @@ -75,7 +75,7 @@ public struct LiveSessionState: Equatable, Sendable { /// Applies `event` and returns what to do, in order. public mutating func handle(_ event: Event) -> [Action] { switch event { - case let .watchedChannel(isAlive): + case let .watchedChannel(isAlive, reloadHierarchyOnReconnect): guard isAlive else { return endConnection() } @@ -83,9 +83,8 @@ public struct LiveSessionState: Equatable, Sendable { guard banner == .connectionLost else { return [] } - // A reconnect: the tree on screen is the old process's. banner = .none - return [.reloadHierarchy] + return reloadHierarchyOnReconnect ? [.reloadHierarchy] : [] case .channelEnded: return endConnection() @@ -124,14 +123,12 @@ public struct LiveSessionState: Equatable, Sendable { return stopProbing() + [.startReconnecting] } - /// Clears the background banner and refreshes, once. + /// Clears the background banner and stops probing. private mutating func returnToForeground() -> [Action] { - let stop = stopProbing() - guard banner == .applicationInBackground else { - return stop + if banner == .applicationInBackground { + banner = .none } - banner = .none - return stop + [.reloadHierarchy] + return stopProbing() } /// Probes while the background banner shows, at the interval that @@ -154,8 +151,7 @@ public struct LiveSessionState: Equatable, Sendable { } } -/// Whether a refresh a live window starts on its own (`reloadHierarchy`: -/// after a reconnect, after its app came back) is tried again. +/// Whether an automatic refresh after a reconnect is tried again. /// /// The window refuses a refresh while a hierarchy fetch or the detail sync /// is running. Dropping the automatic refresh then left the old tree on diff --git a/Packages/LookInsideHostCore/Tests/LookInsideHostCoreTests/LiveSessionStateTests.swift b/Packages/LookInsideHostCore/Tests/LookInsideHostCoreTests/LiveSessionStateTests.swift index d706a26..5608e19 100644 --- a/Packages/LookInsideHostCore/Tests/LookInsideHostCoreTests/LiveSessionStateTests.swift +++ b/Packages/LookInsideHostCore/Tests/LookInsideHostCoreTests/LiveSessionStateTests.swift @@ -40,6 +40,14 @@ struct LiveSessionStateTests { #expect(state.banner == .none) } + @Test("a reconnect that leaves reload to the user still clears the connection-loss banner") + func aReconnectCanSkipTheHierarchyReload() { + var state = openWindow() + _ = state.handle(.channelEnded) + #expect(state.handle(.watchedChannel(isAlive: true, reloadHierarchyOnReconnect: false)) == []) + #expect(state.banner == .none) + } + /// The channel is held weakly: it can be released, or end, before the /// window starts watching it. Until now the window then watched nothing /// and never reconnected. @@ -65,23 +73,21 @@ struct LiveSessionStateTests { #expect(state.banner == .applicationInBackground) } - @Test("a Server that reports its app active again clears the banner, stops pinging and refreshes") - func aForegroundPushRefreshes() { + @Test("a foreground push clears the banner and stops pinging without reloading") + func aForegroundPushStopsProbing() { var state = openWindow() _ = state.handle(.serverReportedApplicationState(isActive: false)) - #expect(state.handle(.serverReportedApplicationState(isActive: true)) == [.stopBackgroundProbe, .reloadHierarchy]) + #expect(state.handle(.serverReportedApplicationState(isActive: true)) == [.stopBackgroundProbe]) #expect(state.banner == .none) - // The probe answering late refreshes nothing more. + // The probe answering late does not change the session again. #expect(state.handle(.backgroundProbeAnswered) == []) } - /// The probe and the push both report the return; the hierarchy is - /// fetched once. - @Test("a ping answered before the foreground push refreshes once") - func aProbeAnsweredBeforeTheForegroundPushRefreshesOnce() { + @Test("a ping answered before the foreground push stops probing without reloading") + func aProbeAnsweredBeforeTheForegroundPushStopsProbing() { var state = openWindow() _ = state.handle(.serverReportedApplicationState(isActive: false)) - #expect(state.handle(.backgroundProbeAnswered) == [.stopBackgroundProbe, .reloadHierarchy]) + #expect(state.handle(.backgroundProbeAnswered) == [.stopBackgroundProbe]) #expect(state.handle(.serverReportedApplicationState(isActive: true)) == []) #expect(state.banner == .none) } @@ -131,22 +137,22 @@ struct LiveSessionStateTests { #expect(state.handle(.requestRefusedInBackground) == []) } - @Test("an answered ping clears the banner, stops pinging and refreshes") - func anAnsweredProbeRefreshes() { + @Test("an answered ping clears the banner and stops pinging without reloading") + func anAnsweredProbeStopsProbing() { var state = openWindow() _ = state.handle(.requestRefusedInBackground) - #expect(state.handle(.backgroundProbeAnswered) == [.stopBackgroundProbe, .reloadHierarchy]) + #expect(state.handle(.backgroundProbeAnswered) == [.stopBackgroundProbe]) #expect(state.banner == .none) } /// A Server that pushes and was refused before its first push (the /// Host connected while the app was inactive): the push and the probe - /// can both report the return; the hierarchy is fetched once. - @Test("a foreground push while pinging stops the ping and refreshes once") - func aForegroundPushWhileProbingRefreshesOnce() { + /// can both report the return. + @Test("a foreground push while pinging stops the ping without reloading") + func aForegroundPushWhileProbingStopsProbing() { var state = openWindow() _ = state.handle(.requestRefusedInBackground) - #expect(state.handle(.serverReportedApplicationState(isActive: true)) == [.stopBackgroundProbe, .reloadHierarchy]) + #expect(state.handle(.serverReportedApplicationState(isActive: true)) == [.stopBackgroundProbe]) #expect(state.handle(.backgroundProbeAnswered) == []) #expect(state.banner == .none) } @@ -183,7 +189,7 @@ struct LiveSessionStateTests { } struct AutomaticRefreshRetryPolicyTests { - /// The refresh after a reconnect or a return from the background was + /// The refresh after a reconnect was /// dropped when a fetch was running, and the tree stayed stale. @Test("a refresh refused while a fetch or the detail sync runs is tried again after the interval") func aRefusedRefreshIsRetried() { diff --git a/Scripts/e2e-reconnect-driver.py b/Scripts/e2e-reconnect-driver.py index f6b30b0..88fc0fa 100755 --- a/Scripts/e2e-reconnect-driver.py +++ b/Scripts/e2e-reconnect-driver.py @@ -41,7 +41,7 @@ def env_float(name, default): "disconnect": env_float("E2E_DISCONNECT_TIMEOUT", 2), "reconnect": env_float("E2E_RECONNECT_TIMEOUT", 8), "background": env_float("E2E_BACKGROUND_TIMEOUT", 1), - "foreground_refresh": env_float("E2E_FOREGROUND_REFRESH_TIMEOUT", 6), + "foreground": env_float("E2E_FOREGROUND_REFRESH_TIMEOUT", 6), "stop_silence": env_float("E2E_STOP_SILENCE", 6), "silent_close": env_float("E2E_SILENT_CLOSE_TIMEOUT", 4), "pending_failure": env_float("E2E_PENDING_FAILURE_TIMEOUT", 1), @@ -464,6 +464,7 @@ def scenario_terminate(self): if not self.ensure_connected(name): return old_pid = self.app.pid() + old_target = self.target_identifier() start = time.time() self.app.terminate() disconnected = self.wait_disconnected(start, TIMEOUTS["disconnect"] + 3) @@ -484,7 +485,15 @@ def scenario_terminate(self): start = time.time() new_pid = self.app.launch() self.results.check(name, "relaunched with a new pid", new_pid and new_pid != old_pid, f"{old_pid} -> {new_pid}") - self.expect_return(name, start, TIMEOUTS["reconnect"], "reconnect") + returned = self.expect_return(name, start, TIMEOUTS["reconnect"], "reconnect") + if returned and self.arguments.mode == "simulator": + result = self.refresh_explicitly(name) + if result is None: + return + new_target = self.target_identifier() + self.results.check(name, "refresh adopts the relaunched target", old_target and new_target and old_target != new_target) + returned_target = result.get("targetIdentifier") + self.results.check(name, "refresh returns the relaunched target ID", new_target and returned_target == new_target) def expect_return(self, name, start, limit, label): cleared = self.wait_banner({"none"}, start, limit + 10) @@ -494,6 +503,18 @@ def expect_return(self, name, start, limit, label): cleared and cleared["_time"] - start <= limit, f"{seconds(cleared['_time'] - start)} ({cleared['event']}, actions {cleared['actions']})" if cleared else "never", ) + if not cleared: + return False + if self.arguments.mode == "simulator": + reloaded = self.wait_reloaded(start, TIMEOUTS["settle"]) + self.results.check( + name, + f"{label}: no automatic refresh", + "reloadHierarchy" not in cleared["actions"] and reloaded is None, + f"actions {cleared['actions']}" if reloaded is None else f"reloaded after {seconds(reloaded[0] - start)}", + ) + return True + reloaded = self.wait_reloaded(start, limit + 10) self.results.check( name, @@ -503,7 +524,22 @@ def expect_return(self, name, start, limit, label): ) if reloaded: self.settle() - return reloaded + return reloaded is not None + + def refresh_explicitly(self, name): + target = self.target_identifier() + frame, elapsed = self.mcp.call("hierarchy.refresh", {"targetIdentifier": target}, timeout=TIMEOUTS["refresh_after_reconnect"]) + error = (frame or {}).get("error") or {} + refreshed = self.results.check( + name, + "explicit hierarchy refresh succeeds", + frame is not None and "result" in frame, + f"{error.get('code', 'ok')} after {seconds(elapsed)}" if frame else "no response", + ) + if refreshed: + self.settle() + return frame["result"] + return None def scenario_background(self): name = "3 background+return" @@ -512,6 +548,7 @@ def scenario_background(self): return if not self.ensure_connected(name): return + original_pid = self.app.pid() start = time.time() self.app.background() entry = self.wait_banner({"applicationInBackground", "connectionLost"}, start, TIMEOUTS["background"] + 5) @@ -526,9 +563,11 @@ def scenario_background(self): banner = self.current_banner() self.results.check(name, "banner holds while in the background", banner in ("applicationInBackground", "connectionLost"), f"banner {banner}") start = time.time() - self.app.foreground() - limit = TIMEOUTS["foreground_refresh"] if banner != "connectionLost" else TIMEOUTS["reconnect"] - self.expect_return(name, start, limit, "return") + foreground_pid = self.app.foreground() + self.results.check(name, "returned in the same process", original_pid and foreground_pid == original_pid, f"{original_pid} -> {foreground_pid}") + limit = TIMEOUTS["foreground"] if banner != "connectionLost" else TIMEOUTS["reconnect"] + if self.expect_return(name, start, limit, "return"): + self.refresh_explicitly(name) def scenario_stop(self): name = "4 SIGSTOP silent channel" @@ -593,8 +632,7 @@ def scenario_pending_request(self): time.sleep(1) start = time.time() self.app.launch() - reloaded = self.expect_return(name, start, TIMEOUTS["reconnect"], "reconnect") - if not reloaded: + if not self.expect_return(name, start, TIMEOUTS["reconnect"], "reconnect"): return # The fetch of the dead channel must not leave the window busy. deadline = time.time() + TIMEOUTS["refresh_after_reconnect"] diff --git a/Scripts/e2e-reconnect.sh b/Scripts/e2e-reconnect.sh index bc7e8ae..23491e6 100755 --- a/Scripts/e2e-reconnect.sh +++ b/Scripts/e2e-reconnect.sh @@ -9,17 +9,19 @@ # Host does and how fast: # # terminate the app is terminated: targets.disconnected and the -# connection-lost banner; relaunched: banner cleared and -# hierarchy.reloaded{initiator: host}, new pid +# connection-lost banner; relaunched: new pid, then refresh +# on demand in the simulator and automatically in AppKit # background another app comes to the front: the background banner (or # connection lost, when the app is suspended); back to the -# front: banner cleared and an automatic refresh +# front: banner cleared, no automatic refresh, and an explicit +# refresh succeeds # (simulator only) # stop SIGSTOP, silence, an MCP hierarchy.refresh: "closing a silent -# channel" and connection lost; SIGCONT: reconnect + refresh +# channel" and connection lost; SIGCONT: reconnect, with an +# automatic refresh only in AppKit mode # pending an MCP refresh in flight when the app dies fails at once, -# not at its timeout; the refresh after the reconnect is not -# refused as already running +# not at its timeout; an explicit refresh after reconnect +# succeeds without a busy rejection # # Usage: # Scripts/e2e-reconnect.sh [--mode simulator|appkit] [--skip-build]