From 6d185f04008ade177ea52809536b924c8c785eba Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Tue, 31 Mar 2026 01:51:57 +0200 Subject: [PATCH 1/8] Use WKContentWorld.defaultClient for all browser panel JS injection Sites with strict CSP (Airtable, various React SPAs) block scripts injected into WKContentWorld.page, causing js_error from browser.eval and snapshot --interactive. Switch all evaluateJavaScript calls and WKUserScript registrations targeting browser panel webviews to use .defaultClient, which is CSP-exempt but retains full DOM access. --- Sources/AppDelegate.swift | 8 ++--- Sources/Panels/BrowserPanel.swift | 49 ++++++++++++++++++------------- Sources/Panels/CmuxWebView.swift | 16 +++++----- Sources/TerminalController.swift | 18 ++++++------ 4 files changed, 50 insertions(+), 41 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index bffe3632e333..2d157f46f0aa 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -8052,9 +8052,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent })(); """ - panel.webView.evaluateJavaScript(script) { [weak self] result, _ in + panel.webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { [weak self] callResult in guard let self else { return } - let payload = result as? [String: Any] + let payload = (try? callResult.get()) as? [String: Any] let focused = (payload?["focused"] as? Bool) ?? false let inputId = (payload?["id"] as? String) ?? "" let secondaryInputId = (payload?["secondaryId"] as? String) ?? "" @@ -8260,8 +8260,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent })(); """ - panel.webView.evaluateJavaScript(script) { result, _ in - let payload = result as? [String: Any] + panel.webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { callResult in + let payload = (try? callResult.get()) as? [String: Any] completion([ "id": (payload?["id"] as? String) ?? "", "tag": (payload?["tag"] as? String) ?? "", diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index dfbd8a9c125f..06258e2f1870 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -2517,7 +2517,8 @@ final class BrowserPanel: Panel, ObservableObject { WKUserScript( source: Self.telemetryHookBootstrapScriptSource, injectionTime: .atDocumentStart, - forMainFrameOnly: true + forMainFrameOnly: true, + in: .defaultClient ) ) // Track the last editable focused element continuously so omnibar exit can @@ -2527,7 +2528,8 @@ final class BrowserPanel: Panel, ObservableObject { WKUserScript( source: Self.addressBarFocusTrackingBootstrapScript, injectionTime: .atDocumentStart, - forMainFrameOnly: true + forMainFrameOnly: true, + in: .defaultClient ) ) } @@ -3540,8 +3542,8 @@ final class BrowserPanel: Panel, ObservableObject { continuation.resume(returning: value) } - webView.evaluateJavaScript(script) { result, _ in - let value = result as? String + webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { result in + let value = (try? result.get()) as? String Task { @MainActor in resume(value) } @@ -4807,7 +4809,7 @@ extension BrowserPanel { /// Execute JavaScript func evaluateJavaScript(_ script: String) async throws -> Any? { - try await webView.evaluateJavaScript(script) + try await webView.evaluateJavaScript(script, in: nil, in: .defaultClient) } // MARK: - Find in Page @@ -4867,7 +4869,7 @@ extension BrowserPanel { func findNext() { Task { @MainActor [weak self] in guard let self else { return } - let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.nextScript()) + let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.nextScript(), in: nil, in: .defaultClient) self.parseFindResult(result) } } @@ -4875,7 +4877,7 @@ extension BrowserPanel { func findPrevious() { Task { @MainActor [weak self] in guard let self else { return } - let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.previousScript()) + let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.previousScript(), in: nil, in: .defaultClient) self.parseFindResult(result) } } @@ -4909,7 +4911,7 @@ extension BrowserPanel { guard let self else { return } let js = BrowserFindJavaScript.searchScript(query: needle) do { - let result = try await self.webView.evaluateJavaScript(js) + let result = try await self.webView.evaluateJavaScript(js, in: nil, in: .defaultClient) self.parseFindResult(result) } catch { NSLog("Find: browser JS search error: %@", error.localizedDescription) @@ -4921,7 +4923,7 @@ extension BrowserPanel { Task { @MainActor [weak self] in guard let self else { return } do { - _ = try await self.webView.evaluateJavaScript(BrowserFindJavaScript.clearScript()) + _ = try await self.webView.evaluateJavaScript(BrowserFindJavaScript.clearScript(), in: nil, in: .defaultClient) } catch { NSLog("Find: browser JS clear error: %@", error.localizedDescription) } @@ -5236,25 +5238,25 @@ extension BrowserPanel { } private func captureAddressBarPageFocusIfNeeded() { - webView.evaluateJavaScript(Self.addressBarFocusCaptureScript) { [weak self] result, error in + webView.evaluateJavaScript(Self.addressBarFocusCaptureScript, in: nil, in: .defaultClient) { [weak self] callResult in #if DEBUG guard let self else { return } - if let error { + switch callResult { + case .failure(let error): dlog( "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + "result=error message=\(error.localizedDescription)" ) - return + case .success(let result): + let resultValue = (result as? String) ?? "unknown" + dlog( + "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + + "result=\(resultValue)" + ) } - let resultValue = (result as? String) ?? "unknown" - dlog( - "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + - "result=\(resultValue)" - ) #else _ = self - _ = result - _ = error + _ = callResult #endif } } @@ -5308,7 +5310,14 @@ extension BrowserPanel { completion(false) return } - webView.evaluateJavaScript(Self.addressBarFocusRestoreScript) { [weak self] result, error in + webView.evaluateJavaScript(Self.addressBarFocusRestoreScript, in: nil, in: .defaultClient) { [weak self] callResult in + let result: Any? + let error: Error? + switch callResult { + case .success(let value): result = value; error = nil + case .failure(let err): result = nil; error = err + } + guard let self else { completion(false) return diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 9693e3727ab2..f883c611210f 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -415,8 +415,8 @@ final class CmuxWebView: WKWebView { return ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let href = result as? String, !href.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let href = (try? callResult.get()) as? String, !href.isEmpty, let url = URL(string: href) else { completion(nil) return @@ -860,8 +860,8 @@ final class CmuxWebView: WKWebView { return candidateFromElement(single) || ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let src = result as? String, !src.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let src = (try? callResult.get()) as? String, !src.isEmpty, let url = URL(string: src) else { completion(nil) return @@ -940,8 +940,8 @@ final class CmuxWebView: WKWebView { return linkFromElement(single) || ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let href = result as? String, !href.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let href = (try? callResult.get()) as? String, !href.isEmpty, let url = URL(string: href) else { completion(nil) return @@ -982,9 +982,9 @@ final class CmuxWebView: WKWebView { return JSON.stringify({count: nodes.length, entries}); })(); """ - evaluateJavaScript(js) { [weak self] result, _ in + evaluateJavaScript(js, in: nil, in: .defaultClient) { [weak self] callResult in guard let self, - let payload = result as? String, + let payload = (try? callResult.get()) as? String, !payload.isEmpty else { return } self.debugContextDownload( "browser.ctxdl.inspect trace=\(traceID) kind=\(kind) payload=\(payload)" diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 66d1c7232f63..94a8cca40a8d 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -7106,7 +7106,7 @@ class TerminalController { script: asyncFunctionBody, timeout: timeout, preferAsync: true, - contentWorld: .page + contentWorld: .defaultClient ) } else { let evaluateFallback = """ @@ -7114,7 +7114,7 @@ class TerminalController { \(asyncFunctionBody) })() """ - rawResult = v2RunJavaScript(webView, script: evaluateFallback, timeout: timeout, contentWorld: .page) + rawResult = v2RunJavaScript(webView, script: evaluateFallback, timeout: timeout, contentWorld: .defaultClient) } if !useEval, case .failure(let pageMessage) = rawResult, #available(macOS 11.0, *) { @@ -9373,7 +9373,7 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.telemetryHookBootstrapScriptSource, timeout: 5.0, - contentWorld: .page + contentWorld: .defaultClient ) } @@ -9382,7 +9382,7 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.dialogTelemetryHookBootstrapScriptSource, timeout: 5.0, - contentWorld: .page + contentWorld: .defaultClient ) } @@ -9414,7 +9414,7 @@ class TerminalController { })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10072,7 +10072,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10110,7 +10110,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10287,7 +10287,7 @@ class TerminalController { scripts.append(script) v2BrowserInitScriptsBySurface[surfaceId] = scripts - let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false) + let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .defaultClient) browserPanel.webView.configuration.userContentController.addUserScript(userScript) _ = v2RunBrowserJavaScript(browserPanel.webView, surfaceId: surfaceId, script: script, timeout: 10.0) @@ -10340,7 +10340,7 @@ class TerminalController { })() """ - let userScript = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false) + let userScript = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .defaultClient) browserPanel.webView.configuration.userContentController.addUserScript(userScript) _ = v2RunBrowserJavaScript(browserPanel.webView, surfaceId: surfaceId, script: source, timeout: 10.0) From bca310c77ca26c74cb24c3216d55f772fa33dc87 Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Tue, 31 Mar 2026 02:23:00 +0200 Subject: [PATCH 2/8] Remove dead isolated-world retry block, document macOS <11 fallback --- Sources/TerminalController.swift | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 94a8cca40a8d..2be980a99899 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -6837,6 +6837,7 @@ class TerminalController { } } } else { + // macOS < 11.0: contentWorld parameter is ignored; JS runs in .page webView.evaluateJavaScript(script) { value, error in if let error { finish(nil, error.localizedDescription) @@ -7117,24 +7118,6 @@ class TerminalController { rawResult = v2RunJavaScript(webView, script: evaluateFallback, timeout: timeout, contentWorld: .defaultClient) } - if !useEval, case .failure(let pageMessage) = rawResult, #available(macOS 11.0, *) { - let isolatedResult = v2RunJavaScript( - webView, - script: asyncFunctionBody, - timeout: timeout, - preferAsync: true, - contentWorld: .defaultClient - ) - switch isolatedResult { - case .success: - rawResult = isolatedResult - case .failure(let isolatedMessage): - if isolatedMessage != pageMessage { - rawResult = .failure("\(pageMessage) (isolated-world retry: \(isolatedMessage))") - } - } - } - switch rawResult { case .failure(let message): return .failure(message) From 8e3535e9c47a375f704244f561b6ea73770aa47a Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Tue, 31 Mar 2026 02:32:24 +0200 Subject: [PATCH 3/8] Add preferAsync to v2RunJavaScript calls so contentWorld is enforced, add contentWorld parameter to BrowserPanel.evaluateJavaScript --- Sources/Panels/BrowserPanel.swift | 4 ++-- Sources/TerminalController.swift | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 06258e2f1870..f4fcab518441 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -4808,8 +4808,8 @@ extension BrowserPanel { } /// Execute JavaScript - func evaluateJavaScript(_ script: String) async throws -> Any? { - try await webView.evaluateJavaScript(script, in: nil, in: .defaultClient) + func evaluateJavaScript(_ script: String, contentWorld: WKContentWorld = .defaultClient) async throws -> Any? { + try await webView.evaluateJavaScript(script, in: nil, in: contentWorld) } // MARK: - Find in Page diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 2be980a99899..2b5224235882 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -9356,6 +9356,7 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.telemetryHookBootstrapScriptSource, timeout: 5.0, + preferAsync: true, contentWorld: .defaultClient ) } @@ -9365,6 +9366,7 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.dialogTelemetryHookBootstrapScriptSource, timeout: 5.0, + preferAsync: true, contentWorld: .defaultClient ) } @@ -9397,7 +9399,7 @@ class TerminalController { })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10055,7 +10057,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10093,7 +10095,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .defaultClient) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): From 05d1aecf177f381d9159a7c8a13a0937d240b489 Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Wed, 1 Apr 2026 14:50:22 +0200 Subject: [PATCH 4/8] Restore window positions when external displays reconnect --- Sources/AppDelegate.swift | 85 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 2d157f46f0aa..880ff9d80e27 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -2302,6 +2302,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private var mainWindowContexts: [ObjectIdentifier: MainWindowContext] = [:] private var mainWindowControllers: [MainWindowController] = [] + /// Per-display window frame cache for restoring positions when external displays reconnect. + /// Keyed by CGDirectDisplayID, values map window identity to the last known frame on that display. + private var displayWindowFrameCache: [UInt32: [ObjectIdentifier: CGRect]] = [:] + /// Set of display IDs that were connected at last check, used to detect reconnections. + private var knownConnectedDisplayIDs: Set = [] + /// Tracks the cascade point for new windows, matching Ghostty's upstream algorithm. /// Reset to `.zero` so the first window seeds the point from its own position. private var lastCascadePoint = NSPoint.zero @@ -2426,6 +2432,33 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent suspensionBehavior: .deliverImmediately ) + // Track external display connect/disconnect for window position restoration. + knownConnectedDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleScreenParametersDidChange(_:)), + name: NSApplication.didChangeScreenParametersNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleWindowDidChangeScreen(_:)), + name: NSWindow.didChangeScreenNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleWindowDidMove(_:)), + name: NSWindow.didMoveNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleWindowDidResize(_:)), + name: NSWindow.didResizeNotification, + object: nil + ) + #if DEBUG // UI tests run on a shared VM user profile, so persisted shortcuts can drift and make // key-equivalent routing flaky. Force defaults for deterministic tests. @@ -3525,6 +3558,58 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) } + // MARK: - Display reconnection window restoration + + /// Cache the current frame of a managed window, keyed by its current display. + private func cacheWindowFrameForDisplay(_ window: NSWindow) { + guard mainWindowContexts[ObjectIdentifier(window)] != nil else { return } + guard let displayID = window.screen?.cmuxDisplayID else { return } + displayWindowFrameCache[displayID, default: [:]][ObjectIdentifier(window)] = window.frame + } + + @objc private func handleWindowDidMove(_ notification: Notification) { + guard let window = notification.object as? NSWindow else { return } + cacheWindowFrameForDisplay(window) + } + + @objc private func handleWindowDidResize(_ notification: Notification) { + guard let window = notification.object as? NSWindow else { return } + cacheWindowFrameForDisplay(window) + } + + @objc private func handleWindowDidChangeScreen(_ notification: Notification) { + guard let window = notification.object as? NSWindow else { return } + cacheWindowFrameForDisplay(window) + } + + @objc private func handleScreenParametersDidChange(_ notification: Notification) { + let currentDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) + let reconnected = currentDisplayIDs.subtracting(knownConnectedDisplayIDs) + knownConnectedDisplayIDs = currentDisplayIDs + + guard !reconnected.isEmpty else { return } + + for displayID in reconnected { + guard let cachedFrames = displayWindowFrameCache[displayID], + let screen = NSScreen.screens.first(where: { $0.cmuxDisplayID == displayID }) else { + continue + } + for (windowID, frame) in cachedFrames { + guard let (_, ctx) = mainWindowContexts.first(where: { $0.key == windowID }), + let window = ctx.window else { + continue + } + let clamped = Self.clampFrame( + frame, + within: screen.visibleFrame, + minWidth: CGFloat(SessionPersistencePolicy.minimumWindowWidth), + minHeight: CGFloat(SessionPersistencePolicy.minimumWindowHeight) + ) + window.setFrame(clamped, display: true, animate: true) + } + } + } + private func startSessionAutosaveTimerIfNeeded() { guard sessionAutosaveTimer == nil else { return } let env = ProcessInfo.processInfo.environment From d96cf7dca94110470842828453290b792ac886c7 Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Wed, 1 Apr 2026 14:59:52 +0200 Subject: [PATCH 5/8] Purge display frame cache on window close, only cache most recent display per window --- Sources/AppDelegate.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 880ff9d80e27..4307e39e5247 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -3561,10 +3561,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent // MARK: - Display reconnection window restoration /// Cache the current frame of a managed window, keyed by its current display. + /// Clears entries for this window on all other displays so that only the most + /// recent display is remembered (prevents restoring a window the user + /// intentionally moved away). private func cacheWindowFrameForDisplay(_ window: NSWindow) { guard mainWindowContexts[ObjectIdentifier(window)] != nil else { return } guard let displayID = window.screen?.cmuxDisplayID else { return } - displayWindowFrameCache[displayID, default: [:]][ObjectIdentifier(window)] = window.frame + let windowID = ObjectIdentifier(window) + for otherDisplayID in displayWindowFrameCache.keys where otherDisplayID != displayID { + displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) + } + displayWindowFrameCache[displayID, default: [:]][windowID] = window.frame } @objc private func handleWindowDidMove(_ notification: Notification) { @@ -11560,6 +11567,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent commandPaletteSelectionByWindowId.removeValue(forKey: removed.windowId) commandPaletteSnapshotByWindowId.removeValue(forKey: removed.windowId) + // Purge per-display frame cache for the closing window to prevent + // address-reuse collisions with future windows. + let closingID = ObjectIdentifier(window) + for displayID in displayWindowFrameCache.keys { + displayWindowFrameCache[displayID]?.removeValue(forKey: closingID) + } + // Avoid stale notifications that can no longer be opened once the owning window is gone. if let store = notificationStore { for tab in removed.tabManager.tabs { From 4c585e4eb8f804d25099ea0d9f4e8fc426d04bf6 Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Wed, 1 Apr 2026 18:55:18 +0200 Subject: [PATCH 6/8] Seed display cache on window registration, preserve disconnected display entries --- Sources/AppDelegate.swift | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 4307e39e5247..853bf660eef7 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -3561,15 +3561,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent // MARK: - Display reconnection window restoration /// Cache the current frame of a managed window, keyed by its current display. - /// Clears entries for this window on all other displays so that only the most - /// recent display is remembered (prevents restoring a window the user - /// intentionally moved away). + /// Only clears entries on other *currently connected* displays so that a + /// disconnect-driven relocation to the primary display doesn't erase the + /// frame we need for restoration. private func cacheWindowFrameForDisplay(_ window: NSWindow) { guard mainWindowContexts[ObjectIdentifier(window)] != nil else { return } guard let displayID = window.screen?.cmuxDisplayID else { return } let windowID = ObjectIdentifier(window) for otherDisplayID in displayWindowFrameCache.keys where otherDisplayID != displayID { - displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) + // Only prune entries for displays that are still connected. + // Disconnected display entries are preserved for restoration. + if knownConnectedDisplayIDs.contains(otherDisplayID) { + displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) + } } displayWindowFrameCache[displayID, default: [:]][windowID] = window.frame } @@ -4156,6 +4160,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) #endif notifyMainWindowContextsDidChange() + cacheWindowFrameForDisplay(window) if window.isKeyWindow { setActiveMainWindow(window) } From a8bea41de911e9e557dbe464454c3b9be03bb38d Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Wed, 1 Apr 2026 19:36:54 +0200 Subject: [PATCH 7/8] Use stable windowId (UUID) instead of ObjectIdentifier for display frame cache --- Sources/AppDelegate.swift | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 853bf660eef7..94cfde4cb706 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -2303,8 +2303,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private var mainWindowControllers: [MainWindowController] = [] /// Per-display window frame cache for restoring positions when external displays reconnect. - /// Keyed by CGDirectDisplayID, values map window identity to the last known frame on that display. - private var displayWindowFrameCache: [UInt32: [ObjectIdentifier: CGRect]] = [:] + /// Keyed by CGDirectDisplayID, values map stable window UUID to the last known frame on that display. + private var displayWindowFrameCache: [UInt32: [UUID: CGRect]] = [:] /// Set of display IDs that were connected at last check, used to detect reconnections. private var knownConnectedDisplayIDs: Set = [] @@ -3565,9 +3565,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent /// disconnect-driven relocation to the primary display doesn't erase the /// frame we need for restoration. private func cacheWindowFrameForDisplay(_ window: NSWindow) { - guard mainWindowContexts[ObjectIdentifier(window)] != nil else { return } + guard let ctx = mainWindowContexts[ObjectIdentifier(window)] else { return } guard let displayID = window.screen?.cmuxDisplayID else { return } - let windowID = ObjectIdentifier(window) + let windowID = ctx.windowId for otherDisplayID in displayWindowFrameCache.keys where otherDisplayID != displayID { // Only prune entries for displays that are still connected. // Disconnected display entries are preserved for restoration. @@ -3605,8 +3605,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent let screen = NSScreen.screens.first(where: { $0.cmuxDisplayID == displayID }) else { continue } - for (windowID, frame) in cachedFrames { - guard let (_, ctx) = mainWindowContexts.first(where: { $0.key == windowID }), + for (windowUUID, frame) in cachedFrames { + guard let ctx = mainWindowContexts.values.first(where: { $0.windowId == windowUUID }), let window = ctx.window else { continue } @@ -11572,11 +11572,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent commandPaletteSelectionByWindowId.removeValue(forKey: removed.windowId) commandPaletteSnapshotByWindowId.removeValue(forKey: removed.windowId) - // Purge per-display frame cache for the closing window to prevent - // address-reuse collisions with future windows. - let closingID = ObjectIdentifier(window) + // Purge per-display frame cache for the closing window. for displayID in displayWindowFrameCache.keys { - displayWindowFrameCache[displayID]?.removeValue(forKey: closingID) + displayWindowFrameCache[displayID]?.removeValue(forKey: removed.windowId) } // Avoid stale notifications that can no longer be opened once the owning window is gone. From 4c83c9f62285d1df961346f5843a80808dbb6db3 Mon Sep 17 00:00:00 2001 From: joshuaswanson Date: Wed, 1 Apr 2026 19:55:14 +0200 Subject: [PATCH 8/8] Clear disconnected display entries on user-initiated moves, preserve during system relayout --- Sources/AppDelegate.swift | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 94cfde4cb706..f1782c2b6651 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -2307,6 +2307,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private var displayWindowFrameCache: [UInt32: [UUID: CGRect]] = [:] /// Set of display IDs that were connected at last check, used to detect reconnections. private var knownConnectedDisplayIDs: Set = [] + /// Brief flag set during system-driven display relayout to suppress pruning + /// of disconnected display cache entries. + private var isHandlingDisplayDisconnect = false /// Tracks the cascade point for new windows, matching Ghostty's upstream algorithm. /// Reset to `.zero` so the first window seeds the point from its own position. @@ -3561,19 +3564,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent // MARK: - Display reconnection window restoration /// Cache the current frame of a managed window, keyed by its current display. - /// Only clears entries on other *currently connected* displays so that a - /// disconnect-driven relocation to the primary display doesn't erase the - /// frame we need for restoration. + /// During system-driven relayout (display disconnect), disconnected display + /// entries are preserved. User-initiated moves clear all other entries so + /// the window won't snap back to a display it was moved away from. private func cacheWindowFrameForDisplay(_ window: NSWindow) { guard let ctx = mainWindowContexts[ObjectIdentifier(window)] else { return } guard let displayID = window.screen?.cmuxDisplayID else { return } let windowID = ctx.windowId for otherDisplayID in displayWindowFrameCache.keys where otherDisplayID != displayID { - // Only prune entries for displays that are still connected. - // Disconnected display entries are preserved for restoration. - if knownConnectedDisplayIDs.contains(otherDisplayID) { - displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) + if isHandlingDisplayDisconnect && !knownConnectedDisplayIDs.contains(otherDisplayID) { + // Preserve disconnected display entries during system relayout. + continue } + displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) } displayWindowFrameCache[displayID, default: [:]][windowID] = window.frame } @@ -3596,8 +3599,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent @objc private func handleScreenParametersDidChange(_ notification: Notification) { let currentDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) let reconnected = currentDisplayIDs.subtracting(knownConnectedDisplayIDs) + let disconnected = knownConnectedDisplayIDs.subtracting(currentDisplayIDs) knownConnectedDisplayIDs = currentDisplayIDs + // Briefly suppress pruning of disconnected display entries so that + // the system-driven window relocation preserves the restore frame. + if !disconnected.isEmpty { + isHandlingDisplayDisconnect = true + DispatchQueue.main.async { [weak self] in + self?.isHandlingDisplayDisconnect = false + } + } + guard !reconnected.isEmpty else { return } for displayID in reconnected {