Giving SwiftUI Item Windows Their Own UndoManager on macOS
When you open an item in its own dedicated macOS window using SwiftUI’s WindowGroup(_:id:for:), you often want that window—and any other window showing the same item—to share a single UndoManager tied to the model object rather than whatever default or scene-level undo manager AppKit and SwiftUI hand out.
My earlier NSHostingView responder trick worked most of the time, until a user clicked the window’s chrome to activate it without landing on a focused subview—or focus drifted back to the NSWindow itself, which doesn’t become first responder the way a control does. Auto-focusing something on activation felt brittle and still left edge cases open.
Going straight to NSWindow‘s backing undo manager turned out to be surprisingly direct—with a couple of private-API quirks and a SwiftUI environment refresh catch.
Why the Responder Trick Wasn’t Enough
In an item-detail window, routing undo/redo through responder focus assumes there is always a willing first responder inside the content hierarchy to supply or intercept the right UndoManager.
In practice, two cases break that assumption:
- Chrome activation: Clicking the title bar or window frame can bring a window forward without placing focus inside a view that participates in your
NSHostingViewundo routing. - Window-level focus: Even when views aren’t claiming first responder status, focus can sit with the window itself rather than a child view, leaving the Edit menu and
\.undoManagerpointing at the wrong manager.
Instead of fighting responder focus on every window activation, I wanted the NSWindow itself to back its undo manager with item.undoManager.
Finding the Undo Manager in NSWindowAuxiliary
NSWindow doesn’t expose a public setter for its internal undo manager, and SwiftUI.AppKitWindow layers its own scene/window machinery on top. Tracing -[NSWindow _getUndoManager:] in disassembly pointed past a guard check and bitflag test at +0xf4 inside _auxiliaryStorage to a slot (r8[0x5] in the decompiler, at byte offset +0x28 inside <NSWindowAuxiliary>).
Inspecting live memory in LLDB confirmed that aux + 0x28 held the window’s NSUndoManager instance. Even more surprisingly, _auxiliaryStorage responds to Key-Value Coding (value(forKey:) and setValue(_:forKey:)):
Swift
if let storage = window.value(forKey: "_auxiliaryStorage") as? NSObject {
print(storage.value(forKey: "undoManager") as Any)
storage.setValue(customUndoManager, forKey: "undoManager")
}
Writing via setValue(_:forKey:) updated the slot cleanly—until I checked SwiftUI’s @Environment(\.undoManager) inside the view hierarchy.
The Refresh Catch: Faking didBecomeKeyNotification
Mutating the undo manager inside _auxiliaryStorage updates window.undoManager, but SwiftUI doesn’t watch raw storage changes. In my testing, SwiftUI views only picked up the new \.undoManager after the window was deactivated and reactivated.
Posting NSWindow.didBecomeKeyNotification for that NSWindow after updating storage nudges SwiftUI to re-read window.undoManager immediately without requiring a manual focus toggle:
extension View {
/// Makes `undoManager` the undo manager of the window this view is in, instead of the window's
/// own, so that the Edit menu and `\.undoManager` use it. Apply it to a `WindowGroup`'s root view
/// with the same instance to have every window of the group share one undo history.
///
/// ```swift
/// WindowGroup {
/// ContentView()
/// .windowUndoManager(sharedUndoManager)
/// }
/// ```
///
/// It's set when the view moves into a window, so pass the same instance for the window's whole
/// life. This replaces a private property of `NSWindow` and may stop working in a future macOS.
public func windowUndoManager(_ undoManager: UndoManager) -> some View {
onWindowChange { window in
window?.replaceUndoManager(with: undoManager)
}
}
}
private extension NSWindow {
func replaceUndoManager(with undoManager: UndoManager) {
// NSWindow keeps the undo manager it makes lazily in its auxiliary storage.
guard let storage = value(forKey: "_auxiliaryStorage") as? NSObject,
storage.value(forKey: "undoManager") as? UndoManager !== undoManager else { return }
storage.setValue(undoManager, forKey: "undoManager")
// SwiftUI only reads window.undoManager again when the window becomes key, so post that
// to have \.undoManager pick up the new one.
NotificationCenter.default.post(name: NSWindow.didBecomeKeyNotification, object: self)
}
}
Wiring It Into the WindowGroup
In the app, each item window is keyed by URL and shares persistenceController.container.viewContext with the main library so every window showing the same Item points to the same managed object instance and its item.undoManager:
WindowGroup("Item", id: "item", for: URL.self) { $itemURL in
// The same context as the library's, so the item is the same instance in every window.
// The window uses the item's undo manager, so every window showing the item shares its history.
ItemDetailView(
itemURL: itemURL,
context: persistenceController.container.viewContext,
isInItemWindow: true
)
}
Inside the detail view, updateItem(_:) resolves the NSManagedObjectID and guards against !item.isDeleted—since a deleted object remains registered in the context until saved, and disappears from existingObject(with:) after save until an undo reinserts that same instance:
Swift
private func updateItem(_ trigger: Trigger) {
// A deleted item stays registered until the delete is saved, so check isDeleted too. Once
// saved, existingObject doesn't find it, until an undo inserts the same instance again.
guard let itemURL = trigger.itemURL,
let objectID = trigger.context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: itemURL),
let item = try? trigger.context.existingObject(with: objectID) as? Item, !item.isDeleted else {
self.item = nil
return
}
self.item = item
}
@ViewBuilder private var editorOrNotFound: some View {
if let item {
if isInItemWindow {
// Set when the editor moves into the window. The window only ever shows this
// item, and its undo manager lasts as long as the instance, so it stays the same.
ItemEditor(item: item, context: context)
.windowUndoManager(item.undoManager)
} else {
ItemEditor(item: item, context: context)
}
} else {
ContentUnavailableView("Item Not Found", systemImage: "questionmark.square.dashed")
.onAppear {
updateItem(trigger)
}
}
}
Rough Edges, What I’d Tidy Up, and What Should Be Public API
This got the exact behavior I wanted—activating via window chrome works, focus quirks don’t break undo routing, and multiple windows viewing the same item share its undo stack—but there are a few things I’d clean up and keep an eye on:
- Private SPI & KVC fragility:
_auxiliaryStorageand"undoManager"are undocumented internals. Any macOS release can rename them, change their KVC behavior, or shift how SwiftUI resolves scene/window undo managers. - Synthetic lifecycle notifications: Posting
NSWindow.didBecomeKeyNotificationmanually is a pragmatic workaround for SwiftUI’s refresh timing, not a contract. Any observers listening for key-window transitions on that window will see a synthetic notification, so it’s worth watching for side effects. - Cleaner separation & guards: The
replaceUndoManager(with:)logic can be tightened up (for example, failing loudly in debug builds if the KVC lookup or set ever stops matching expectations, and keeping the window-binding assumption—one item and oneUndoManagerper window lifetime—explicit). - Hoping
SynchronizeUndoManagerandSynchronizeSceneUndoManagerbecome public: Behind the scenes, SwiftUI already has internal machinery—SynchronizeUndoManagerandSynchronizeSceneUndoManager—that writes to the environmentUndoManagerkey and feeds into the same underlying setup used when a window is created, which the rest of the view hierarchy’s environment then reads from. In fact, the scene modifier.modelContainer(for: Item.self, isUndoEnabled: true)specifically sets the window’s undo manager to theModelContext‘s undo manager for every window. Hopefully one day Apple makesSynchronizeUndoManagerandSynchronizeSceneUndoManagerpublic so apps can bind window and scene undo managers cleanly without reaching into_auxiliaryStorageor faking key-window notifications.