Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces-macos): New UI (preview) replaces the main window instead of adding one (#5054)
ddupontd35d1ccd08b2
diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.mdindex dcfa25d881..b103257d80 100644--- a/apps/cua-spaces-macos/README.md+++ b/apps/cua-spaces-macos/README.md@@ -75,11 +75,16 @@ run (with a throwaway `HOME`). State lives under `$HOME/Library/Application Supp## New UI (preview)-Settings, Experiments, "New UI (preview)" (`web_ui`, off by default) adds-File, "Open New UI (preview)" (⇧⌘U) and a "New UI" toolbar button. They open-`WebUIWindowController` (`Sources/CuaSpacesMacKit/WebHost`): a `WKWebView`-with the shared React UI (`apps/cua-spaces-web`) in a window without a title-bar. The notch, the menu bar extra, Touch ID, the updater and video stay+Settings, Experiments, "New UI (preview)" (`web_ui`, off by default) makes+`WebUIWindowController` (`Sources/CuaSpacesMacKit/WebHost`) the main window: a+`WKWebView` with the shared React UI (`apps/cua-spaces-web`) in a window+without a title bar. Turning it on puts that window where the native one was+(same frame) and closes the native one; turning it off does the reverse+(`MainWindowSwitch`). While it is on, everything that opens the main window+opens it instead, at the matching page (`MainUIRouter`): the Dock icon, the+menu bar item, the notch, File, New Space (⌘N), the View menu, Help, Getting+Started and the app's notifications; the native window, opened any other way+(the Window menu), gives way to it. The notch, the menu bar extra, Touch ID, the updater and video staynative; a Space's desktop opens in its native window.- Release: `scripts/build-app.sh` copies the web build (`apps/cua-spaces-web/dist`,diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 49ff3857f5..e9aef6e2b2 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -666,7 +666,11 @@ public final class AppModel {/// false when there is no New UI window to show it in. Set by the New UI/// window while the `web_ui` experiment is on.public var openWebNewSpace: ((_ on: String?) -> Bool)?- /// Closes the New UI window (the `web_ui` experiment was turned off).+ /// Puts the New UI window in the native main window's place (the+ /// `web_ui` experiment was turned on).+ public var openWebUI: (() -> Void)?+ /// Closes the New UI window and puts the native one in its place (the+ /// `web_ui` experiment was turned off).public var closeWebUI: (() -> Void)?/// New Space with "Run on" set to `on` (`host:<machine>`): a machine's@@ -1212,7 +1216,8 @@ public final class AppModel {saveSettings()telemetry?.record(signals)onboarding.send(.experimentsLoaded(experiments: after))- // New UI off: its window goes with it (the native one takes over).+ // New UI on: its window takes the native one's place; off: the reverse.+ if !before.webUi, after.webUi { openWebUI?() }if before.webUi, !after.webUi { closeWebUI?() }wizard.update(env: wizardEnv(from: wizard.env))// The Volume page went with Cua Volume: back to the Spaces.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swiftindex 201c985792..ee9d0bda5b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift@@ -683,6 +683,8 @@ public final class DevicesModel {final class DeviceNotifier: NSObject, UNUserNotificationCenterDelegate {static let shared = DeviceNotifier()private var authorized: Bool?+ /// A notification was clicked (its identifier): the app opens its main UI.+ var onOpen: ((String) -> Void)?static var available: Bool { Bundle.main.bundleURL.pathExtension == "app" }@@ -709,6 +711,10 @@ final class DeviceNotifier: NSObject, UNUserNotificationCenterDelegate {nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse) async {- await MainActor.run { NSApp.activate() }+ let id = response.notification.request.identifier+ await MainActor.run {+ NSApp.activate()+ onOpen?(id)+ }}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swiftindex 365034fc9e..c4223952f0 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift@@ -328,6 +328,8 @@ final class AgentNotifier {func post(_ note: AppSystemNote) {guard DeviceNotifier.available else { return }let center = UNUserNotificationCenter.current()+ // Its click opens the main UI too.+ center.delegate = DeviceNotifier.sharedlet content = UNMutableNotificationContent()content.title = note.titlecontent.body = note.bodydiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CommandPaletteView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CommandPaletteView.swiftindex 9225e575a1..f30ba3abb4 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CommandPaletteView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CommandPaletteView.swift@@ -73,20 +73,24 @@ struct NavigationCommands: View {@Environment(\.openWindow) private var openWindowvar body: some View {- Button("Command Palette…") { inMain { model.showingPalette = true } }+ Button("Command Palette…") { inMain(.home) { model.showingPalette = true } }.keyboardShortcut(SharedShortcuts.shortcut("commandPalette.toggle"))Divider()ForEach(NavTarget.all(model)) { target in- Button(target.label) { inMain { model.go(target.command) } }+ Button(target.label) { inMain(MainUIRouter.route(forNav: target.command)) { model.go(target.command) } }.keyboardShortcut(SharedShortcuts.shortcut(target.command))}}- private func inMain(_ then: () -> Void) {+ /// The native main window, then `then`; New UI's window at `route`+ /// while it is on (its page handles these keys itself when in front).+ private func inMain(_ route: MainUIRoute?, _ then: () -> Void) {if WebUIWindowController.shared?.window?.isKeyWindow == true { return }guard model.startup.isReady, model.onboarding.completed else { return }- openWindow(id: "main")- then()+ MainUIRouter(model: model).open(route ?? .home) {+ openWindow(id: "main")+ then()+ }}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex 0345d1f3f6..f9117712c6 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -46,13 +46,6 @@ public struct CuaSpacesMacApp: App {// No `.appSettings` group here: the `Settings` scene's item is the// app menu's one "Settings…". The New UI window answers its// action itself (`WebUIAppWindow`), so ⌘, opens its Settings.- // New UI (preview): the shared web UI in its own window.- CommandGroup(after: .newItem) {- if model.settings.experiments.webUi {- OpenWebUIButton(model: model)- .keyboardShortcut("u", modifiers: [.command, .shift])- }- }CommandGroup(before: .sidebar) {NavigationCommands(model: model)Divider()@@ -131,12 +124,15 @@ struct RootView: View {}} else if model.onboarding.completed {MainWindow(model: model)+ // New UI on: whatever opened this window gets New UI in its place.+ .background(WindowReader { MainWindowSwitch.nativeAppeared($0, model: model) }).onAppear {// The New UI window's bridge opens these scenes.WebUIWindowController.actions = .make(openWindow: openWindow)// Opened at login: the menu bar item and the notch only,// as after the window is closed (once per launch).- if AppDelegate.takeQuietStart() { dismissWindow(id: "main") }+ if AppDelegate.takeQuietStart() { dismissWindow(id: "main"); return }+ MainWindowSwitch.nativeAppeared(nil, model: model)}} else {OnboardingView(onboarding: model.onboarding, onSignIn: model.account == nil ? nil : {@@ -157,9 +153,12 @@ struct GettingStartedCommand: View {var body: some View {Button("Getting Started") {guard model.startup.isReady, model.onboarding.completed else { return }- NSApp.activate()- openWindow(id: "main")model.openGettingStarted()+ // New UI shows the checklist on its Spaces page.+ MainUIRouter(model: model).open(.home) {+ NSApp.activate()+ openWindow(id: "main")+ }}}}@@ -274,14 +273,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate {start(Self.model)}+ /// The Dock icon (or opening the app again) with no window up: the main+ /// UI in use, New UI while it is on. The notch and the menu bar item's+ /// panels don't count as windows.+ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {+ let model = Self.model+ guard model.startup.isReady, model.onboarding.completed else { return true }+ guard !NSApp.windows.contains(where: { $0.isVisible && $0.canBecomeMain }) else { return true }+ MainUIRouter(model: model).open(.home) { WebUIWindowController.actions?.openMain() }+ return false+ }+func start(_ model: AppModel) {guard !started else { return }started = true// New Space opens New UI's wizard while its experiment is on.model.openWebNewSpace = { on in WebUIWindowController.showNewSpace(model: model, on: on) }+ // New UI on and off: one window, its frame kept, never two.+ model.openWebUI = { MainWindowSwitch.switchToWebUI(model: model) }model.closeWebUI = { WebUIWindowController.closeShared() }let controller = NotchController(model: model.notch)controller.sidebar = model.dropTargets+ controller.showMain = { WebUIWindowController.actions?.openMain() }// Each of these shows its result in the main window (the New UI// window while its experiment is on): open it when it was closed// (the notch stays up without it), or a drop would commit to@@ -378,6 +391,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {// approval sheet) even with the window closed; this Mac's own// enrollment shows as the main window's banner. Nothing else asks.model.devices.notify = { DeviceNotifier.shared.post($0) }+ // A click on one of the app's notifications: the main UI in use.+ DeviceNotifier.shared.onOpen = { id in+ router.open(id.hasPrefix("agent-") ? .agents : .home) { WebUIWindowController.actions?.openMain() }+ }// Persistent agents' answers and requests, from the daemon's feed,// while the app runs (the daemon keeps them while it does not).model.persistent.post = { AgentNotifier.shared.post($0) }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swiftindex 3fa7655cb9..847f7465a5 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift@@ -46,12 +46,6 @@ public struct MainWindow: View {.keyboardShortcut("n", modifiers: .command).help(chrome.newSpaceLabel)}- if model.settings.experiments.webUi {- ToolbarItem(placement: .primaryAction) {- OpenWebUIButton(model: model, label: "New UI")- .help("Open New UI (preview)")- }- }}.sheet(isPresented: $model.showingNewSpace) {NewSpaceWizardView(wizard: model.wizard,diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swiftindex 656f4c018d..f95cc8e1a6 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift@@ -1,6 +1,7 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.+import AppKitimport Foundation/// Where the app's chrome (the notch, the menu bar item) opens the main UI.@@ -18,6 +19,9 @@ public enum MainUIRoute: Equatable, Sendable {case access/// Cua Volume.case drive+ case machines+ case agents+ case keyvault/// The page's path, query included.var webPath: String {@@ -26,6 +30,9 @@ public enum MainUIRoute: Equatable, Sendable {case .settings: return "/settings"case .access: return "/keyvault?view=access"case .drive: return "/volume"+ case .machines: return "/machines"+ case .agents: return "/agents"+ case .keyvault: return "/keyvault"case let .space(id, dropped):let path = "/spaces/\(Self.encodeComponent(id))"let names = dropped.map(\.lastPathComponent)@@ -48,9 +55,9 @@ public enum MainUIRoute: Equatable, Sendable {}}-/// The one place the notch and the menu bar item open the main UI: the New-/// UI window at a route while its experiment is on, else the native window-/// or Settings as before.+/// The one place the app's chrome (the notch, the menu bar item, the menus,+/// notifications) opens the main UI: the New UI window at a route while its+/// experiment is on, else the native window or Settings as before.@MainActorstruct MainUIRouter {let model: AppModel@@ -65,4 +72,93 @@ struct MainUIRouter {func open(_ route: MainUIRoute, native: () -> Void) {if model.settings.experiments.webUi { web(route) } else { native() }}++ /// The page a View menu `nav.*` command names.+ static func route(forNav command: String) -> MainUIRoute? {+ switch command {+ case "nav.spaces": return .home+ case "nav.machines": return .machines+ case "nav.agents": return .agents+ case "nav.keyvault": return .keyvault+ case "nav.settings": return .settings+ default: return nil+ }+ }+}++/// New UI (preview) is the main window while it is on, not a second one:+/// turning it on puts its window where the native one was (same frame) and+/// closes that; turning it off does the reverse. Whatever opens the native+/// main window while it is on (the Dock, the Window menu, a path not routed+/// through `MainUIRouter`) gets the New UI window in its place.+@MainActor+enum MainWindowSwitch {+ /// The native main window (`Window(id: "main")`), while it exists.+ static weak var nativeWindow: NSWindow?+ /// Where the native window opens next: New UI's frame when it was turned off.+ static var pendingNativeFrame: NSRect?++ /// Whether the native window showing the main UI (not the launch or the+ /// first run) gives way to New UI.+ static func replacesNative(webUi: Bool, ready: Bool, onboarded: Bool) -> Bool {+ webUi && ready && onboarded+ }++ static func replacesNative(_ model: AppModel) -> Bool {+ replacesNative(webUi: model.settings.experiments.webUi, ready: model.startup.isReady,+ onboarded: model.onboarding.completed)+ }++ /// The native window is showing the main UI (`MainWindow` appeared in+ /// it): with New UI on, New UI opens in its frame and it closes.+ static func nativeAppeared(_ window: NSWindow?, model: AppModel,+ web: ((NSRect?) -> Void)? = nil) {+ if let window { nativeWindow = window }+ guard let window = window ?? nativeWindow else { return }+ if let frame = pendingNativeFrame {+ pendingNativeFrame = nil+ // After SwiftUI placed it.+ DispatchQueue.main.async { window.setFrame(frame, display: true) }+ }+ guard replacesNative(model) else { return }+ replace(window, model: model, web: web)+ }++ /// New UI was turned on: its window takes the native one's place.+ static func switchToWebUI(model: AppModel, web: ((NSRect?) -> Void)? = nil) {+ guard let window = nativeWindow, window.isVisible else {+ // No native window up (only Settings, say): New UI opens as at launch.+ if model.startup.isReady, model.onboarding.completed { (web ?? { show(model, frame: $0) })(nil) }+ return+ }+ replace(window, model: model, web: web)+ }++ /// The native window being closed for New UI (its reader and its+ /// `onAppear` both report it).+ private static weak var replacing: NSWindow?++ private static func replace(_ window: NSWindow, model: AppModel, web: ((NSRect?) -> Void)?) {+ guard replacing !== window else { return }+ replacing = window+ let frame = window.frame.width > 0 ? window.frame : nil+ // Never seen: hidden before it draws, where it can.+ window.alphaValue = 0+ (web ?? { show(model, frame: $0) })(frame)+ DispatchQueue.main.async {+ window.close()+ window.alphaValue = 1+ if replacing === window { replacing = nil }+ }+ }++ private static func show(_ model: AppModel, frame: NSRect?) {+ WebUIWindowController.show(model: model, frame: frame)+ }++ /// New UI was turned off: the native window opens in its frame.+ static func switchToNative(webFrame: NSRect?, openMain: (() -> Void)?) {+ pendingNativeFrame = webFrame+ openMain?()+ }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swiftindex 9f5bbe08c0..2b4dab501b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift@@ -43,14 +43,23 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,return devServer}- /// Opens the window, or brings it forward.- public static func show(model: AppModel) {+ /// Opens the window, or brings it forward; at `frame` when given (the+ /// native main window's, which it replaces).+ public static func show(model: AppModel, frame: NSRect? = nil) {+ show(model: model, frame: frame, startRoute: nil)+ }++ /// `startRoute`: the page a new window loads first (an open one is+ /// asked to go there instead).+ static func show(model: AppModel, frame: NSRect?, startRoute: String?) {if let c = shared {c.bridge.actions = actions ?? c.bridge.actions+ if let frame { c.window?.setFrame(frame, display: true) }c.present()return}- let c = WebUIWindowController(model: model)+ let c = WebUIWindowController(model: model, route: startRoute)+ if let frame { c.window?.setFrame(frame, display: false) }shared = cc.load()}@@ -60,6 +69,12 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,/// (`spaces.droppedFiles`).public static func show(model: AppModel, at route: MainUIRoute) {notchDrop = route.dropped+ guard shared != nil else {+ // A new window loads the page there: a route asked for while it+ // starts could reach it before its router listens, and be lost.+ show(model: model, frame: nil, startRoute: route.webPath)+ return+ }show(model: model)shared?.bridge.requestRoute(route.webPath)}@@ -68,14 +83,15 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,static var notchDrop: [URL] = []/// Closes the New UI window, if open (its experiment was turned off),- /// and shows the native main window in its place.+ /// and shows the native main window in its place, at its frame.public static func closeShared() {guard let c = shared else { return }- let main = c.bridge.actions?.openMain+ let main = c.bridge.actions?.openMain ?? actions?.openMain// After the bridge answered the page's switch.DispatchQueue.main.async {+ let frame = c.window?.isVisible == true ? c.window?.frame : nilc.window?.close()- main?()+ MainWindowSwitch.switchToNative(webFrame: frame, openMain: main)}}@@ -89,6 +105,12 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,return true}+ /// `route` (a page's path, its query too) under `base`.+ static func url(_ route: String, in base: URL) -> URL {+ let relative = route.hasPrefix("/") ? String(route.dropFirst()) : route+ return URL(string: relative, relativeTo: base)?.absoluteURL ?? base+ }+let bridge: WebUIBridgelet webView: WebUIWebView/// Native video under `<StreamSurface>`; nil unless its experiment is on.@@ -102,7 +124,7 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,init(model: AppModel, route: String? = nil) {let dev = Self.devURLlet base = dev ?? WebUISchemeHandler.startURL- startURL = route.map { base.appendingPathComponent($0) } ?? base+ startURL = route.map { Self.url($0, in: base) } ?? basevar origins: Set<String> = ["\(WebUISchemeHandler.scheme)://\(WebUISchemeHandler.host)"]if let dev, let host = dev.host {origins.insert("\(dev.scheme ?? "http")://\(host)\(dev.port.map { ":\($0)" } ?? "")")@@ -403,7 +425,7 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,public func windowDidExitFullScreen(_ notification: Notification) { applyInset() }public func windowWillClose(_ notification: Notification) {- // Opened again (⇧⌘U), it comes back where it was.+ // Opened again, it comes back where it was.window?.saveFrame(usingName: Self.frameName)videoSurfaces?.removeAll()webView.configuration.userContentController.removeAllScriptMessageHandlers()@@ -533,31 +555,6 @@ extension NSColor {}}-/// "Open New UI (preview)": the menu command and the main window's toolbar-/// button, while the experiment is on. It also hands the bridge the scenes'-/// window actions.-public struct OpenWebUIButton: View {- let model: AppModel- var label: String = "Open New UI (preview)"- @Environment(\.openWindow) private var openWindow-- public init(model: AppModel, label: String = "Open New UI (preview)") {- self.model = model- self.label = label- }-- public var body: some View {- Button(label) {- WebUIWindowController.actions = actions- WebUIWindowController.show(model: model)- }- }-- var actions: WebUIActions {- WebUIActions.make(openWindow: openWindow)- }-}-extension WebUIActions {/// The scenes' window actions for the bridge.static func make(openWindow: OpenWindowAction) -> WebUIActions {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swiftindex 8b998f245c..3082a0104e 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift@@ -107,4 +107,139 @@ struct MainUIRouteTests {c.run(.settings)#expect(calls == ["main", "native settings", "list", "settings"])}++ // MARK: - One main window: New UI replaces the native one++ /// A new window loads the page at its route (query included) rather+ /// than asking a page that may not listen yet.+ @Test func aNewWindowStartsAtItsRoute() {+ let base = URL(string: "cua-spaces://app/")!+ #expect(WebUIWindowController.url("/settings", in: base).absoluteString == "cua-spaces://app/settings")+ #expect(WebUIWindowController.url(MainUIRoute.access.webPath, in: base).absoluteString+ == "cua-spaces://app/keyvault?view=access")+ #expect(WebUIWindowController.url("spaces/s1", in: base).absoluteString == "cua-spaces://app/spaces/s1")+ let dev = URL(string: "http://localhost:5174/")!+ #expect(WebUIWindowController.url("/spaces/a%20b?dropped=%5B%5D", in: dev).absoluteString+ == "http://localhost:5174/spaces/a%20b?dropped=%5B%5D")+ let c = WebUIWindowController(model: model(webUi: true), route: MainUIRoute.settings.webPath)+ defer { c.window?.close() }+ #expect(c.startURL.absoluteString.hasSuffix("/settings"))+ }++ @Test func theViewMenusPagesHaveTheirRoutes() {+ #expect(MainUIRouter.route(forNav: "nav.spaces") == .home)+ #expect(MainUIRouter.route(forNav: "nav.machines")?.webPath == "/machines")+ #expect(MainUIRouter.route(forNav: "nav.agents")?.webPath == "/agents")+ #expect(MainUIRouter.route(forNav: "nav.keyvault")?.webPath == "/keyvault")+ #expect(MainUIRouter.route(forNav: "nav.settings") == .settings)+ #expect(MainUIRouter.route(forNav: "nav.nope") == nil)+ }++ /// Only the main UI gives way: the launch and the first run stay in+ /// the native window.+ @Test func onlyTheMainUIGivesWayToNewUI() {+ #expect(MainWindowSwitch.replacesNative(webUi: true, ready: true, onboarded: true))+ #expect(!MainWindowSwitch.replacesNative(webUi: false, ready: true, onboarded: true))+ #expect(!MainWindowSwitch.replacesNative(webUi: true, ready: false, onboarded: true))+ #expect(!MainWindowSwitch.replacesNative(webUi: true, ready: true, onboarded: false))+ }++ /// A frame inside the screen (a CI runner's is small), so the window+ /// server keeps it as given; `dx` tells two apart.+ func onScreen(dx: CGFloat = 0) -> NSRect {+ let v = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1024, height: 700)+ return NSRect(x: v.minX + 20 + dx, y: v.minY + 20, width: min(760, v.width - 80), height: min(480, v.height - 60))+ }++ func nativeWindow(_ frame: NSRect) -> NSWindow {+ let w = NSWindow(contentRect: frame, styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: true)+ w.isReleasedWhenClosed = false+ w.setFrame(frame, display: false)+ return w+ }++ func settle() async {+ await withCheckedContinuation { k in DispatchQueue.main.async { k.resume() } }+ await withCheckedContinuation { k in DispatchQueue.main.async { k.resume() } }+ }++ /// Whatever opens the native window while New UI is on (the Dock, the+ /// Window menu, a path not routed) gets New UI in its frame; it closes.+ @Test func theNativeWindowOpeningWithNewUIOnIsReplacedInPlace() async {+ let m = model(webUi: true)+ m.onboarding.finish()+ let w = nativeWindow(onScreen())+ w.orderFront(nil)+ let frame = w.frame+ var opened: [NSRect?] = []+ MainWindowSwitch.nativeAppeared(w, model: m, web: { opened.append($0) })+ // Reported twice (its reader, its onAppear): replaced once.+ MainWindowSwitch.nativeAppeared(nil, model: m, web: { opened.append($0) })+ #expect(opened == [frame])+ await settle()+ #expect(!w.isVisible)+ #expect(w.alphaValue == 1)+ }++ @Test func theNativeWindowStaysWithNewUIOff() async {+ let m = model(webUi: false)+ m.onboarding.finish()+ let w = nativeWindow(onScreen())+ w.orderFront(nil)+ defer { w.close() }+ var opened = 0+ MainWindowSwitch.nativeAppeared(w, model: m, web: { _ in opened += 1 })+ await settle()+ #expect(opened == 0 && w.isVisible)+ }++ /// Turning New UI on with the native window up: New UI in its frame.+ @Test func turningNewUIOnSwapsTheWindowInPlace() async {+ let m = model(webUi: true)+ m.onboarding.finish()+ let w = nativeWindow(onScreen())+ w.orderFront(nil)+ let frame = w.frame+ MainWindowSwitch.nativeWindow = w+ var opened: [NSRect?] = []+ MainWindowSwitch.switchToWebUI(model: m, web: { opened.append($0) })+ #expect(opened == [frame])+ await settle()+ #expect(!w.isVisible)+ // With no native window up (only Settings), New UI opens as at launch.+ MainWindowSwitch.switchToWebUI(model: m, web: { opened.append($0) })+ #expect(opened == [frame, nil])+ }++ /// Turning it off: the native window opens where New UI was.+ @Test func turningNewUIOffOpensTheNativeWindowInItsFrame() async {+ let m = model(webUi: false)+ m.onboarding.finish()+ let webFrame = onScreen(dx: 30)+ var opened = 0+ MainWindowSwitch.switchToNative(webFrame: webFrame, openMain: { opened += 1 })+ #expect(opened == 1)+ let w = nativeWindow(onScreen())+ w.orderFront(nil)+ defer { w.close() }+ #expect(w.frame != webFrame)+ MainWindowSwitch.nativeAppeared(w, model: m)+ await settle()+ #expect(w.frame == webFrame)+ #expect(MainWindowSwitch.pendingNativeFrame == nil)+ }++ /// The setting's switch: on puts New UI in the native window's place,+ /// off the reverse.+ @Test func theSwitchSwapsTheWindows() {+ let m = model(webUi: false)+ var calls: [String] = []+ m.openWebUI = { calls.append("open") }+ m.closeWebUI = { calls.append("close") }+ m.chooseExperiment(row: "experiment:web_ui", option: "on")+ #expect(m.settings.experiments.webUi)+ m.chooseExperiment(row: "experiment:web_ui", option: "on")+ m.chooseExperiment(row: "experiment:web_ui", option: "off")+ #expect(calls == ["open", "close"])+ }}