Skip to content
Merged
28 changes: 22 additions & 6 deletions Sources/App/SettingsWindowPresenter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum SettingsWindowPresenter {
private static var pendingNavigationTarget: SettingsNavigationTarget?
private static var pendingContentNavigationTarget: SettingsNavigationTarget?
private static var shouldOpenWhenConfigured = false
private static var focusHandler: @MainActor (NSWindow) -> Void = { performFocus($0) }

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 New singleton side channel in production type

focusHandler is a mutable static closure that lives in the production portion of SettingsWindowPresenter (outside #if DEBUG), making arbitrary focus behaviour injectable at runtime even though the mutation API (setFocusHandlerForTests) is guarded. Per the project's architectural-rethink rule, introducing a new singleton side channel — even one whose default is always performFocus — leaves the production invariant implicit rather than enforced. Consider moving the property and its default assignment inside #if DEBUG as well, and calling performFocus directly in the production focus(_:) body.

Rule Used: Flag Swift fixes that patch symptoms while leaving... (source)

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!


static func configure(
openWindow: @escaping @MainActor () -> Void,
Expand All @@ -33,16 +34,19 @@ enum SettingsWindowPresenter {
}

static func configure(window: NSWindow) {
let shouldFocusAfterConfiguration = settingsWindow !== window
settingsWindow = window
window.identifier = NSUserInterfaceItemIdentifier(windowIdentifier)
window.isRestorable = false
window.minSize = minimumSize
window.contentMinSize = minimumSize
clampToVisibleAreaIfNeeded(window)
attachToPreferredParent(window)
Task { @MainActor in
guard settingsWindow === window else { return }
focus(window)
if shouldFocusAfterConfiguration {
Task { @MainActor in
guard settingsWindow === window else { return }
focus(window)
}
}
}

Expand All @@ -64,10 +68,13 @@ enum SettingsWindowPresenter {
pendingContentNavigationTarget = navigationTarget

if let window = existingWindow() {
pendingNavigationTarget = nil
pendingContentNavigationTarget = nil
let shouldDeferNavigation = window.isMiniaturized
if !shouldDeferNavigation {
pendingNavigationTarget = nil
pendingContentNavigationTarget = nil
}
focus(window)
if let navigationTarget {
if let navigationTarget, !shouldDeferNavigation {
SettingsNavigationRequest.post(navigationTarget)
}
return
Expand Down Expand Up @@ -115,6 +122,11 @@ enum SettingsWindowPresenter {
pendingNavigationTarget = nil
pendingContentNavigationTarget = nil
shouldOpenWhenConfigured = false
focusHandler = { performFocus($0) }
}

static func setFocusHandlerForTests(_ handler: @escaping @MainActor (NSWindow) -> Void) {
focusHandler = handler
}
#endif

Expand All @@ -128,6 +140,10 @@ enum SettingsWindowPresenter {
}

private static func focus(_ window: NSWindow) {
focusHandler(window)
}

private static func performFocus(_ window: NSWindow) {
if window.isMiniaturized {
window.deminiaturize(nil)
}
Expand Down
95 changes: 75 additions & 20 deletions Sources/cmuxApp.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AppKit
import SwiftUI
import Observation
import Darwin
import Bonsplit
import UniformTypeIdentifiers
Expand Down Expand Up @@ -634,11 +635,8 @@ struct cmuxApp: App {
}

Window(String(localized: "settings.title", defaultValue: "Settings"), id: SettingsWindowPresenter.windowID) {
SettingsRootView()
SettingsWindowRootView()
.cmuxAppearanceColorScheme(appearanceMode)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.background(WindowAccessor { window in
SettingsWindowPresenter.configure(window: window)
})
}
.defaultSize(width: 980, height: 680)
.windowResizability(.contentMinSize)
Expand Down Expand Up @@ -5312,8 +5310,7 @@ struct SettingsView: View {
@State private var didRequestBrowserImportDetection = false
@State private var isDetectingImportBrowsers = false
@State private var browserImportDetectionGeneration = 0
@State private var browserInsecureHTTPAllowlistDraft = BrowserInsecureHTTPSettings.defaultAllowlistText
@State private var socketPasswordDraft = ""
@Bindable var draftState: SettingsDraftState
@State private var socketPasswordStatusMessage: String?
@State private var socketPasswordStatusIsError = false
@State private var notificationCustomSoundStatusMessage: String?
Expand Down Expand Up @@ -5785,7 +5782,7 @@ struct SettingsView: View {
}

private var browserInsecureHTTPAllowlistHasUnsavedChanges: Bool {
browserInsecureHTTPAllowlistDraft != browserInsecureHTTPAllowlist
draftState.browserInsecureHTTPAllowlistDraft != browserInsecureHTTPAllowlist
}

private var hasCustomNotificationSoundFilePath: Bool {
Expand Down Expand Up @@ -6066,7 +6063,7 @@ struct SettingsView: View {
}

private func saveSocketPassword() {
let trimmed = socketPasswordDraft.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmed = draftState.socketPasswordDraft.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
socketPasswordStatusMessage = String(localized: "settings.automation.socketPassword.enterFirst", defaultValue: "Enter a password first.")
socketPasswordStatusIsError = true
Expand All @@ -6075,7 +6072,7 @@ struct SettingsView: View {

do {
try SocketControlPasswordStore.savePassword(trimmed)
socketPasswordDraft = ""
draftState.socketPasswordDraft = ""
socketPasswordStatusMessage = String(localized: "settings.automation.socketPassword.saved", defaultValue: "Password saved.")
socketPasswordStatusIsError = false
} catch {
Expand All @@ -6087,7 +6084,7 @@ struct SettingsView: View {
private func clearSocketPassword() {
do {
try SocketControlPasswordStore.clearPassword()
socketPasswordDraft = ""
draftState.socketPasswordDraft = ""
socketPasswordStatusMessage = String(localized: "settings.automation.socketPassword.cleared", defaultValue: "Password cleared.")
socketPasswordStatusIsError = false
} catch {
Expand Down Expand Up @@ -6938,15 +6935,15 @@ struct SettingsView: View {
: String(localized: "settings.automation.socketPassword.subtitleUnset", defaultValue: "No password set. External clients will be blocked until one is configured.")
) {
HStack(spacing: 8) {
SecureField(String(localized: "settings.automation.socketPassword.placeholder", defaultValue: "Password"), text: $socketPasswordDraft)
SecureField(String(localized: "settings.automation.socketPassword.placeholder", defaultValue: "Password"), text: $draftState.socketPasswordDraft)
.textFieldStyle(.roundedBorder)
.frame(width: 170)
Button(hasSocketPasswordConfigured ? String(localized: "settings.automation.socketPassword.change", defaultValue: "Change") : String(localized: "settings.automation.socketPassword.set", defaultValue: "Set")) {
saveSocketPassword()
}
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(socketPasswordDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
.disabled(draftState.socketPasswordDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
if hasSocketPasswordConfigured {
Button(String(localized: "settings.automation.socketPassword.clear", defaultValue: "Clear")) {
clearSocketPassword()
Expand Down Expand Up @@ -7275,7 +7272,7 @@ struct SettingsView: View {
.font(.caption)
.foregroundStyle(.secondary)

TextEditor(text: $browserInsecureHTTPAllowlistDraft)
TextEditor(text: $draftState.browserInsecureHTTPAllowlistDraft)
.font(.system(size: 12, weight: .regular, design: .monospaced))
.frame(minHeight: 86)
.padding(6)
Expand Down Expand Up @@ -7737,7 +7734,7 @@ struct SettingsView: View {
browserImportHintVariantRaw = BrowserImportHintSettings.variant(for: browserImportHintVariantRaw).rawValue
didLoadBrowserHistoryForSettings = BrowserHistoryStore.shared.isLoaded
browserHistoryEntryCount = didLoadBrowserHistoryForSettings ? BrowserHistoryStore.shared.entries.count : 0
browserInsecureHTTPAllowlistDraft = browserInsecureHTTPAllowlist
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
draftState.browserInsecureHTTPAllowlistDraft = browserInsecureHTTPAllowlist
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
reloadWorkspaceTabColorSettings()
refreshNotificationCustomSoundStatus()
let target = SettingsWindowPresenter.consumePendingContentNavigationTarget()
Expand All @@ -7760,8 +7757,8 @@ struct SettingsView: View {
}
.onChange(of: browserInsecureHTTPAllowlist) { oldValue, newValue in
// Keep draft in sync with external changes unless the user has local unsaved edits.
if browserInsecureHTTPAllowlistDraft == oldValue {
browserInsecureHTTPAllowlistDraft = newValue
if draftState.browserInsecureHTTPAllowlistDraft == oldValue {
draftState.browserInsecureHTTPAllowlistDraft = newValue
}
}
.onReceive(BrowserHistoryStore.shared.$entries) { entries in
Expand Down Expand Up @@ -7888,7 +7885,7 @@ struct SettingsView: View {
browserHostWhitelist = BrowserLinkOpenSettings.defaultBrowserHostWhitelist
browserExternalOpenPatterns = BrowserLinkOpenSettings.defaultBrowserExternalOpenPatterns
browserInsecureHTTPAllowlist = BrowserInsecureHTTPSettings.defaultAllowlistText
browserInsecureHTTPAllowlistDraft = BrowserInsecureHTTPSettings.defaultAllowlistText
draftState.browserInsecureHTTPAllowlistDraft = BrowserInsecureHTTPSettings.defaultAllowlistText
notificationSound = NotificationSoundSettings.defaultValue
notificationSoundCustomFilePath = NotificationSoundSettings.defaultCustomFilePath
notificationCustomSoundStatusMessage = nil
Expand Down Expand Up @@ -7962,7 +7959,7 @@ struct SettingsView: View {
sidebarMatchTerminalBackground = false
showOpenAccessConfirmation = false
pendingOpenAccessMode = nil
socketPasswordDraft = ""
draftState.socketPasswordDraft = ""
socketPasswordStatusMessage = nil
socketPasswordStatusIsError = false
refreshDetectedImportBrowsers()
Expand Down Expand Up @@ -8017,7 +8014,7 @@ struct SettingsView: View {
}

private func saveBrowserInsecureHTTPAllowlist() {
browserInsecureHTTPAllowlist = browserInsecureHTTPAllowlistDraft
browserInsecureHTTPAllowlist = draftState.browserInsecureHTTPAllowlistDraft
}

private func refreshDetectedImportBrowsers() {
Expand Down Expand Up @@ -8739,7 +8736,65 @@ private struct GlobalHotkeySection: View {
}
}

private struct SettingsWindowRootView: View {
@State private var draftState = SettingsDraftState()
@State private var window: NSWindow?
@State private var shouldRenderSettingsContent = true

var body: some View {
Group {
if shouldRenderSettingsContent {
SettingsRootView(draftState: draftState)
} else {
Color.clear
.frame(
minWidth: SettingsWindowPresenter.minimumSize.width,
minHeight: SettingsWindowPresenter.minimumSize.height
)
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
.background(WindowAccessor { window in
self.window = window
SettingsWindowPresenter.configure(window: window)
setContentVisibility(!window.isMiniaturized)
})
.onReceive(NotificationCenter.default.publisher(for: NSWindow.didMiniaturizeNotification)) { notification in
guard notification.object as? NSWindow === window else { return }
setContentVisibility(false)
}
.onReceive(NotificationCenter.default.publisher(for: NSWindow.didDeminiaturizeNotification)) { notification in
guard notification.object as? NSWindow === window else { return }
setContentVisibility(true)
}
.onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { notification in
guard notification.object as? NSWindow === window else { return }
setContentVisibility(true)
}
.onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeMainNotification)) { notification in
guard notification.object as? NSWindow === window else { return }
setContentVisibility(true)
}
.onReceive(NotificationCenter.default.publisher(for: NSWindow.willCloseNotification)) { notification in
guard notification.object as? NSWindow === window else { return }
setContentVisibility(false)
}
}

private func setContentVisibility(_ isVisible: Bool) {
guard shouldRenderSettingsContent != isVisible else { return }
shouldRenderSettingsContent = isVisible
}
}
Comment on lines +8820 to +8876

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 Ephemeral @State lost on every miniaturize/restore cycle

Because SettingsRootView is fully torn down when shouldRenderSettingsContent goes false, any @State that isn't backed by @SceneStorage is silently discarded. Concretely, searchText resets to "" and columnVisibility resets to .all each time the window is miniaturized then restored. A user who typed a search query, minimizes Settings while Codex runs, and then restores it will find the search field blank — that's a behavioral change from the pre-PR code where the tree was never unmounted. @SceneStorage values (section, sidebar entry) survive, but non-persisted view state does not.

Rule Used: Flag SwiftUI changes that can cause stale state, b... (source)


@MainActor
@Observable
final class SettingsDraftState {
var browserInsecureHTTPAllowlistDraft = BrowserInsecureHTTPSettings.defaultAllowlistText
var socketPasswordDraft = ""
}

private struct SettingsRootView: View {
@Bindable var draftState: SettingsDraftState
@SceneStorage("selectedSettingsSection") private var selectedSectionRaw = SettingsNavigationTarget.account.rawValue
@SceneStorage("selectedSettingsSidebarEntry") private var selectedSidebarEntryID = SettingsSearchIndex.defaultSelectionID
@State private var columnVisibility: NavigationSplitViewVisibility = .all
Expand Down Expand Up @@ -8786,7 +8841,7 @@ private struct SettingsRootView: View {
)
.navigationSplitViewColumnWidth(210)
} detail: {
SettingsView()
SettingsView(draftState: draftState)
}
.navigationSplitViewStyle(.balanced)
.frame(minWidth: SettingsWindowPresenter.minimumSize.width, minHeight: SettingsWindowPresenter.minimumSize.height)
Expand Down
60 changes: 58 additions & 2 deletions cmuxTests/SettingsWindowPresenterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,50 @@ final class SettingsWindowPresenterTests: XCTestCase {
XCTAssertNil(SettingsWindowPresenter.consumePendingContentNavigationTarget())
}

func testRepeatedConfigureForSameSettingsWindowDoesNotRefocus() async {
let settingsWindow = makeWindow(identifier: SettingsWindowPresenter.windowIdentifier)
var focusedWindows: [NSWindow] = []
defer {
settingsWindow.orderOut(nil)
}

SettingsWindowPresenter.setFocusHandlerForTests { window in
focusedWindows.append(window)
}

SettingsWindowPresenter.configure(window: settingsWindow)
await Task.yield()
SettingsWindowPresenter.configure(window: settingsWindow)
await Task.yield()

XCTAssertEqual(focusedWindows.count, 1)
XCTAssertTrue(focusedWindows.first === settingsWindow)
}

func testShowPreservesPendingNavigationWhenExistingSettingsWindowIsMiniaturized() async {
let settingsWindow = makeWindow(
identifier: SettingsWindowPresenter.windowIdentifier,
isMiniaturizedForTests: true
)
var didOpen = false
defer {
settingsWindow.orderOut(nil)
}

SettingsWindowPresenter.setFocusHandlerForTests { _ in }
SettingsWindowPresenter.configure(window: settingsWindow)
await Task.yield()

SettingsWindowPresenter.show(
navigationTarget: .browserImport,
openWindowOverride: { didOpen = true }
)

XCTAssertFalse(didOpen)
XCTAssertEqual(SettingsWindowPresenter.consumePendingNavigationTarget(), .browserImport)
XCTAssertEqual(SettingsWindowPresenter.consumePendingContentNavigationTarget(), .browserImport)
}

func testParentsSettingsAbovePreferredMainWindow() {
let parentWindow = makeWindow(identifier: "cmux.main.\(UUID().uuidString)")
let settingsWindow = makeWindow(identifier: SettingsWindowPresenter.windowIdentifier)
Expand Down Expand Up @@ -149,16 +193,28 @@ final class SettingsWindowPresenterTests: XCTestCase {
}
}

private func makeWindow(identifier: String) -> NSWindow {
let window = NSWindow(
private func makeWindow(
identifier: String,
isMiniaturizedForTests: Bool? = nil
) -> NSWindow {
let window = TestSettingsWindow(
contentRect: NSRect(x: 0, y: 0, width: 320, height: 220),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
defer: false
)
window.isMiniaturizedForTests = isMiniaturizedForTests
window.isReleasedWhenClosed = false
window.identifier = NSUserInterfaceItemIdentifier(identifier)
return window
}

private final class TestSettingsWindow: NSWindow {
var isMiniaturizedForTests: Bool?

override var isMiniaturized: Bool {
isMiniaturizedForTests ?? super.isMiniaturized
}
}
}
#endif
Loading