Skip to content
Closed
110 changes: 106 additions & 4 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 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<UInt32> = []
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// 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
Expand Down Expand Up @@ -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
)
Comment on lines +2438 to +2463

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Seed the display cache when a main window becomes managed.

Right now the cache is only populated by future move/resize/screen-change notifications. A window that's already sitting on an external display when it registers can unplug before any of those fire, leaving handleScreenParametersDidChange with nothing to restore. Please backfill from the current window.frame once registration completes.

Also applies to: 3577-3590

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 2435 - 2460, Seed the display cache
immediately when a main window becomes managed by populating
knownConnectedDisplayIDs from the window's current screen/frame instead of
waiting for move/resize/screen-change notifications: after the observers are
registered (the block that sets knownConnectedDisplayIDs =
Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) and adds
NSApplication.didChangeScreenParametersNotification /
NSWindow.didChangeScreenNotification / NSWindow.didMoveNotification /
NSWindow.didResizeNotification), also examine the managed window's current
screen via window.screen and its frame (window.frame) and add that screen's
cmuxDisplayID into knownConnectedDisplayIDs (or call the same seeding logic used
by handleScreenParametersDidChange) so a window already on an external display
is backfilled; make the same change at the other occurrence noted (the block
around lines 3577-3590) and ensure any restoration logic in
handleScreenParametersDidChange uses this preseeded set.


#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.
Expand Down Expand Up @@ -3525,6 +3558,69 @@ 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.
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 {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// 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
Comment on lines +3570 to +3581

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don't restore windows that were intentionally rehomed while a display was away.

The disconnected-display entry survives later moves/resizes on a connected display, and the reconnect path restores every window still cached under that old display. If a user unplugs display A, keeps working on display B, and manually repositions the window on B, reconnecting A will still snap it back to A. This needs a per-window recency / pending-restore check so post-disconnect user moves clear the stale entry.

Also applies to: 3603-3620

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 3567 - 3578, The
cacheWindowFrameForDisplay logic must avoid restoring windows that were
intentionally moved on a different (connected) display after a disconnect: when
caching a window frame into displayWindowFrameCache for the current display (in
cacheWindowFrameForDisplay), clear any stale entries for that same ctx.windowId
that live under disconnected displayIDs by removing
displayWindowFrameCache[oldDisplayID]?[windowID] if oldDisplayID is not equal to
displayID (instead of only pruning connected displays), and/or record a
per-window "lastMovedAt" timestamp or a pendingRestore flag on
mainWindowContexts[ObjectIdentifier(window)] that you set here; then update the
reconnect/restore path to consult that timestamp/flag (e.g., skip restoration if
lastMovedAt is newer than the disconnect time or pendingRestore is false). Use
the existing symbols displayWindowFrameCache, mainWindowContexts, ctx.windowId,
knownConnectedDisplayIDs and the reconnect restore code to implement this
recency check.

}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

@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)
}
Comment on lines +3570 to +3597

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Only prune other display entries on confirmed user moves/resizes.

didMove, didResize, and didChangeScreen all funnel through the same pruning path here. After the one-turn isHandlingDisplayDisconnect window closes, any later non-user geometry change on the fallback display clears the disconnected-display entry too, so reconnect restore stops working. Keep the frame update here, but gate cross-display pruning on real user-initiated moves/resizes only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 3570 - 3597,
cacheWindowFrameForDisplay currently always prunes other-display entries, which
causes disconnected-display entries to be removed by non-user-driven geometry
changes; change cacheWindowFrameForDisplay(_:) to accept a Bool (e.g.,
shouldPruneOtherDisplays) or add an internal flag to control pruning and only
run the for-otherDisplayID removal when shouldPruneOtherDisplays is true; then
call cacheWindowFrameForDisplay(window, shouldPruneOtherDisplays: true) from
user-driven handlers handleWindowDidMove and handleWindowDidResize, but call it
with shouldPruneOtherDisplays: false (or leave default false) from
handleWindowDidChangeScreen so cross-display pruning only happens on real user
moves/resizes.


@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 (windowUUID, frame) in cachedFrames {
guard let ctx = mainWindowContexts.values.first(where: { $0.windowId == windowUUID }),
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)
}
}
}
Comment on lines +3599 to +3635

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Restoration triggers when user intentionally moved window away from the display

displayWindowFrameCache stores frames per display without any notion of why the window left the display. Consider this sequence:

  1. External display A is connected; window lives on A.
  2. User manually drags the window to the primary display (cache now has entries for both displays).
  3. External display A disconnects and later reconnects.

handleScreenParametersDidChange sees display A as "reconnected," finds the stale cache entry for the window under display A's ID, and moves the window back to A — overriding the user's explicit choice. Filtering out windows that are already on a still-connected display before restoring would prevent this.

Comment on lines +3599 to +3635

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Wire the disconnected-display cache into session persistence too.

This reconnect handler restores the live window, but buildSessionSnapshot(...) and persistWindowGeometry(from:) still save the current window.frame / displaySnapshot(for:) from the fallback display. If the app terminates before another save after reconnection, the saved session is still overwritten and the next launch loses the original placement.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 3599 - 3635, The reconnect logic
restores windows from displayWindowFrameCache but session saving still reads
live window.frame and displaySnapshot(for:), which can record fallback-display
data and overwrite the cached placement; update buildSessionSnapshot(...) and
persistWindowGeometry(from:) to prefer using displayWindowFrameCache and the
cached displayID/frame when present (lookup by window UUID and/or displayID)
instead of the current NSScreen-derived values, and fall back to
window.frame/displaySnapshot(for:) only if no cached entry exists; ensure you
reference displayWindowFrameCache, window UUID keys used in mainWindowContexts,
and the same clamping/SessionPersistencePolicy minimums so persisted snapshots
match the restored geometry.


private func startSessionAutosaveTimerIfNeeded() {
guard sessionAutosaveTimer == nil else { return }
let env = ProcessInfo.processInfo.environment
Expand Down Expand Up @@ -4064,6 +4160,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
)
#endif
notifyMainWindowContextsDidChange()
cacheWindowFrameForDisplay(window)
if window.isKeyWindow {
setActiveMainWindow(window)
}
Expand Down Expand Up @@ -8052,9 +8149,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) ?? ""
Expand Down Expand Up @@ -8260,8 +8357,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) ?? "",
Expand Down Expand Up @@ -11475,6 +11572,11 @@ 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.
for displayID in displayWindowFrameCache.keys {
displayWindowFrameCache[displayID]?.removeValue(forKey: removed.windowId)
}

// 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 {
Expand Down
51 changes: 30 additions & 21 deletions Sources/Panels/BrowserPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -2527,7 +2528,8 @@ final class BrowserPanel: Panel, ObservableObject {
WKUserScript(
source: Self.addressBarFocusTrackingBootstrapScript,
injectionTime: .atDocumentStart,
forMainFrameOnly: true
forMainFrameOnly: true,
in: .defaultClient
)
)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -4806,8 +4808,8 @@ extension BrowserPanel {
}

/// Execute JavaScript
func evaluateJavaScript(_ script: String) async throws -> Any? {
try await webView.evaluateJavaScript(script)
func evaluateJavaScript(_ script: String, contentWorld: WKContentWorld = .defaultClient) async throws -> Any? {
try await webView.evaluateJavaScript(script, in: nil, in: contentWorld)
}

// MARK: - Find in Page
Expand Down Expand Up @@ -4867,15 +4869,15 @@ 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)
}
}

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)
}
}
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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
Comment on lines 5310 to 5323

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Unnecessary decomposition of Result into legacy variables

The callback decomposes the Result back into separate result and error variables to feed the existing downstream code, unlike every other converted site in this PR which switches on the Result directly. The current approach works correctly but is inconsistent with the pattern used elsewhere in the same changeset.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Expand Down
16 changes: 8 additions & 8 deletions Sources/Panels/CmuxWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)"
Expand Down
Loading