Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces-macos): open the New UI from the notch and menu bar (CUA-1407) (#5031)

Francesco Bonaccie088b19c3c68
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
index 6d6bd5c730..6b2637d0d5 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
@@ -54,6 +54,10 @@ public final class NotchController {
/// Its Dismiss: hide the indicator and the tiles' key (nothing is
/// revoked or wiped).
@ObservationIgnored public var onDismissAccess: (() -> Void)?
+ /// The header's list and Settings buttons; unset, `showMain` and
+ /// `showSettings`.
+ @ObservationIgnored public var onOpenList: (() -> Void)?
+ @ObservationIgnored public var onOpenSettings: (() -> Void)?
/// Opens (or brings forward) the main window, which may have been
/// closed while the notch stayed up. Set by the notch view.
@ObservationIgnored public var showMain: (() -> Void)?
@@ -455,8 +459,8 @@ extension NotchController: NotchSurface {
model.send(.dismiss)
NSApp.activate()
switch button {
- case .list: showMain?()
- case .settings: showSettings?()
+ case .list: (onOpenList ?? showMain)?()
+ case .settings: (onOpenSettings ?? showSettings)?()
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
index 4ff6caf716..a026b3e2f7 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
@@ -170,17 +170,20 @@ struct MenuBarContent: View {
}
private func run(_ id: AppMenuItemId) {
+ let router = MainUIRouter(model: model)
switch id {
- case .open: activate(); openWindow(id: "main")
+ case .open: router.open(.home) { activate(); openWindow(id: "main") }
case .newSpace:
activate()
// The native sheet needs the main window; New UI opens its own.
if !model.settings.experiments.webUi { openWindow(id: "main") }
Task { await model.openNewSpace() }
- case .settings: activate(); openSettings()
+ case .settings: router.open(.settings) { activate(); openSettings() }
case .volumeConflicts:
- activate(); openWindow(id: "main")
- model.selection = .drive
+ router.open(.drive) {
+ activate(); openWindow(id: "main")
+ model.selection = .drive
+ }
case .quit: NSApp.terminate(nil)
case .status, .separator: break
}
@@ -257,35 +260,53 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
model.closeWebUI = { WebUIWindowController.closeShared() }
let controller = NotchController(model: model.notch)
controller.sidebar = model.dropTargets
- // Each of these shows its result in the main window: open it when
- // it was closed (the notch stays up without it), or a drop would
- // commit to nothing visible.
+ // 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
+ // nothing visible.
+ let router = MainUIRouter(model: model)
controller.onOpenSpace = { [weak controller] id in
model.select(id)
- NSApp.activate()
- controller?.showMain?()
+ router.open(.space(id)) {
+ NSApp.activate()
+ controller?.showMain?()
+ }
+ }
+ controller.onOpenList = { [weak controller] in
+ router.open(.home) { controller?.showMain?() }
+ }
+ controller.onOpenSettings = { [weak controller] in
+ router.open(.settings) { controller?.showSettings?() }
}
controller.onOpenAccess = { [weak controller] in
- model.selection = .keyvault(.category(category: .access))
- NSApp.activate()
- controller?.showMain?()
+ router.open(.access) {
+ model.selection = .keyvault(.category(category: .access))
+ NSApp.activate()
+ controller?.showMain?()
+ }
}
controller.onDismissAccess = { model.keyvault.dismiss() }
controller.onTeleport = { [weak controller] spaceId, entry in
model.select(spaceId)
- model.pendingTeleport = PendingTeleport(spaceId: spaceId, entry: entry, files: [])
- NSApp.activate()
- controller?.showMain?()
+ // The page opens Teleport at the app as for a drop of it.
+ let app = entry?.hostPath.map { URL(fileURLWithPath: $0) }
+ router.open(.space(spaceId, dropped: app.map { [$0] } ?? [])) {
+ model.pendingTeleport = PendingTeleport(spaceId: spaceId, entry: entry, files: [])
+ NSApp.activate()
+ controller?.showMain?()
+ }
}
controller.onDropURLs = { [weak controller] spaceId, urls in
model.select(spaceId)
- Task {
- guard let context = try? await model.backend.teleportContext(id: spaceId) else { return }
- let parsed = context.0.parseDrop(items: urls.map(\.path))
- let entry = parsed.apps.first.flatMap { try? context.0.catalogEntryForPath(path: $0, options: nil) }
- model.pendingTeleport = PendingTeleport(spaceId: spaceId, entry: entry, files: parsed.files)
- NSApp.activate()
- controller?.showMain?()
+ router.open(.space(spaceId, dropped: urls)) {
+ Task {
+ guard let context = try? await model.backend.teleportContext(id: spaceId) else { return }
+ let parsed = context.0.parseDrop(items: urls.map(\.path))
+ let entry = parsed.apps.first.flatMap { try? context.0.catalogEntryForPath(path: $0, options: nil) }
+ model.pendingTeleport = PendingTeleport(spaceId: spaceId, entry: entry, files: parsed.files)
+ NSApp.activate()
+ controller?.showMain?()
+ }
}
}
// "Spaces tab in the notch": applied now and on every change.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift
new file mode 100644
index 0000000000..656f4c018d
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import Foundation
+
+/// Where the app's chrome (the notch, the menu bar item) opens the main UI.
+/// With New UI on it is a page of the New UI window, at the routes the
+/// Electron app opens for the same actions (apps/cua-spaces-desktop/src/main.ts).
+public enum MainUIRoute: Equatable, Sendable {
+ /// The Spaces list.
+ case home
+ /// A Space's page; `dropped` are the apps and files dropped on its notch
+ /// tile, which the page handles as a drop on its well (an app opens
+ /// Teleport at it, files are sent).
+ case space(String, dropped: [URL] = [])
+ case settings
+ /// The Keyvault's Access page.
+ case access
+ /// Cua Volume.
+ case drive
+
+ /// The page's path, query included.
+ var webPath: String {
+ switch self {
+ case .home: return "/spaces"
+ case .settings: return "/settings"
+ case .access: return "/keyvault?view=access"
+ case .drive: return "/volume"
+ case let .space(id, dropped):
+ let path = "/spaces/\(Self.encodeComponent(id))"
+ let names = dropped.map(\.lastPathComponent)
+ guard !names.isEmpty, let data = try? JSONEncoder().encode(names),
+ let json = String(data: data, encoding: .utf8) else { return path }
+ return "\(path)?dropped=\(Self.encodeComponent(json))"
+ }
+ }
+
+ var dropped: [URL] {
+ if case let .space(_, dropped) = self { return dropped }
+ return []
+ }
+
+ /// JavaScript's `encodeURIComponent`.
+ static func encodeComponent(_ s: String) -> String {
+ var allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
+ allowed.insert(charactersIn: "-_.!~*'()")
+ return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s
+ }
+}
+
+/// 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.
+@MainActor
+struct MainUIRouter {
+ let model: AppModel
+ /// Opens the New UI window at a route (tests set their own).
+ var web: (MainUIRoute) -> Void
+
+ init(model: AppModel, web: ((MainUIRoute) -> Void)? = nil) {
+ self.model = model
+ self.web = web ?? { WebUIWindowController.show(model: model, at: $0) }
+ }
+
+ func open(_ route: MainUIRoute, native: () -> Void) {
+ if model.settings.experiments.webUi { web(route) } else { native() }
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Files.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Files.swift
index e28d41e1eb..78fc769f41 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Files.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Files.swift
@@ -32,11 +32,18 @@ extension WebUIBridge {
}
}
- /// The files on the last drag's pasteboard whose names the page saw
- /// dropped (an older drag's files never match).
+ /// The apps and files of the last drop on a notch tile whose names the
+ /// page asks for, else the files on the last drag's pasteboard whose
+ /// names the page saw dropped (an older drag's files never match).
func dropped(names: [String]) -> [URL] {
let wanted = Set(names)
guard !wanted.isEmpty else { return [] }
+ // A drop on a notch tile, handed over once.
+ let fromNotch = WebUIWindowController.notchDrop.filter { wanted.contains($0.lastPathComponent) }
+ if !fromNotch.isEmpty {
+ WebUIWindowController.notchDrop = []
+ return fromNotch
+ }
let urls = dragPasteboard().readObjects(forClasses: [NSURL.self],
options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
return urls.filter { wanted.contains($0.lastPathComponent) }
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 7584c7abd3..6833fdec40 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -127,6 +127,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
var pendingNewSpace: String??
/// Settings asked for before the page listened.
var pendingSettings = false
+ /// A route asked for before the page listened (the latest wins).
+ var pendingRoute: String?
/// Local paths the user picked or dropped here: the only ones
/// `spaces.sendFiles` sends (WebUIBridge+Files.swift).
var offeredPaths: Set<String> = []
@@ -199,6 +201,10 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
pendingSettings = false
DispatchQueue.main.async { [weak self] in self?.emitSettings() }
}
+ if let path = pendingRoute {
+ pendingRoute = nil
+ DispatchQueue.main.async { [weak self] in self?.emitRoute(path) }
+ }
}
static func reply(id: String, error: Failure) -> [String: Any] {
@@ -465,6 +471,18 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
host?.emit("settings.openRequested")
}
+ // MARK: - Routes (the notch and the menu bar item open the page at one)
+
+ /// Asks the page to go to `path` (`/spaces/<id>`, `/settings`, ...);
+ /// queued until the page listens.
+ func requestRoute(_ path: String) {
+ if pageListening { emitRoute(path) } else { pendingRoute = path }
+ }
+
+ func emitRoute(_ path: String) {
+ host?.emit("route.openRequested", payload: ["path": path])
+ }
+
/// `spaces.createOptions`: the env the native New Space sheet opens
/// with (`AppModel.newSpaceEnv`: this Mac's runtimes, storage and GPUs,
/// your machines that provide Spaces, your clouds, pricing), which the
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
index 43377ead54..8b4e0be305 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
@@ -55,6 +55,18 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,
c.load()
}
+ /// Opens the window (or brings it forward) at `route`. A drop on a
+ /// notch tile is kept for the page, which asks for it by name
+ /// (`spaces.droppedFiles`).
+ public static func show(model: AppModel, at route: MainUIRoute) {
+ notchDrop = route.dropped
+ show(model: model)
+ shared?.bridge.requestRoute(route.webPath)
+ }
+
+ /// The apps and files last dropped on a notch tile, until the page takes them.
+ 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.
public static func closeShared() {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift
new file mode 100644
index 0000000000..8b998f245c
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import Foundation
+import Testing
+
+/// With New UI on, the notch and the menu bar item open the New UI window at
+/// the page Electron opens for the same action; with it off, the native
+/// window or Settings as before.
+@MainActor
+@Suite("Main UI routes", .serialized)
+struct MainUIRouteTests {
+ init() { _ = NSApplication.shared }
+
+ func model(webUi: Bool) -> AppModel {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-route-\(UUID().uuidString)")
+ let m = AppModel(backend: FixtureSpacesBackend(), keyvault: KeyvaultModel(client: nil),
+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),
+ settingsPath: dir.appendingPathComponent("settings.json").path,
+ telemetry: FixtureTelemetry())
+ m.settings.experiments = AppExperiments(cuaVolume: true, yourCloud: false, sharing: false, webUi: webUi)
+ return m
+ }
+
+ @Test func eachRouteIsThePagesPath() {
+ #expect(MainUIRoute.home.webPath == "/spaces")
+ #expect(MainUIRoute.settings.webPath == "/settings")
+ #expect(MainUIRoute.access.webPath == "/keyvault?view=access")
+ #expect(MainUIRoute.drive.webPath == "/volume")
+ #expect(MainUIRoute.space("s 1/x").webPath == "/spaces/s%201%2Fx")
+ let drop = MainUIRoute.space("s1", dropped: [URL(fileURLWithPath: "/Applications/Slack.app"),
+ URL(fileURLWithPath: "/tmp/a b.txt")])
+ // encodeURIComponent(JSON.stringify(["Slack.app","a b.txt"])), as Electron's.
+ #expect(drop.webPath == "/spaces/s1?dropped=%5B%22Slack.app%22%2C%22a%20b.txt%22%5D")
+ #expect(drop.dropped.map(\.lastPathComponent) == ["Slack.app", "a b.txt"])
+ #expect(MainUIRoute.home.dropped.isEmpty)
+ }
+
+ @Test func newUIOnOpensTheWebWindowElseTheNativeOne() {
+ for webUi in [true, false] {
+ var web: [MainUIRoute] = []
+ var native = 0
+ let router = MainUIRouter(model: model(webUi: webUi), web: { web.append($0) })
+ router.open(.space("s1")) { native += 1 }
+ router.open(.settings) { native += 1 }
+ #expect(web == (webUi ? [.space("s1"), .settings] : []))
+ #expect(native == (webUi ? 0 : 2))
+ }
+ }
+
+ /// The page gets `route.openRequested {path}`: queued until it listens
+ /// (the latest wins), at once after.
+ @Test func thePageIsToldWhereToGo() async {
+ let c = WebUIWindowController(model: model(webUi: true))
+ defer { c.window?.close() }
+ let bridge = c.bridge
+ var seen: [String] = []
+ c.onEmit = { event, payload in
+ seen.append("\(event) \((payload as? [String: Any])?["path"] as? String ?? "")")
+ }
+ bridge.requestRoute("/settings")
+ bridge.requestRoute("/spaces/s1")
+ #expect(seen.isEmpty && bridge.pendingRoute == "/spaces/s1")
+ bridge.pageIsListening()
+ await withCheckedContinuation { k in DispatchQueue.main.async { k.resume() } }
+ #expect(seen == ["route.openRequested /spaces/s1"])
+ #expect(bridge.pendingRoute == nil)
+ bridge.requestRoute("/spaces")
+ #expect(seen.last == "route.openRequested /spaces")
+ }
+
+ /// A drop on a notch tile reaches the page's well by name, once, and is
+ /// then sendable.
+ @Test func aNotchDropIsHandedToThePageOnce() async throws {
+ let m = model(webUi: true)
+ await m.refresh()
+ let id = try #require(m.spaces.first?.id)
+ let c = WebUIWindowController(model: m)
+ defer { c.window?.close(); WebUIWindowController.notchDrop = [] }
+ let bridge = c.bridge
+ let board = NSPasteboard(name: NSPasteboard.Name("cua-test-drag-\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ board.clearContents()
+ bridge.dragPasteboard = { board }
+
+ WebUIWindowController.notchDrop = MainUIRoute.space(id, dropped: [URL(fileURLWithPath: "/tmp/n.txt")]).dropped
+ #expect(try await bridge.handle("spaces.droppedFiles", ["names": ["n.txt"]]) as? [String] == ["/tmp/n.txt"])
+ #expect(WebUIWindowController.notchDrop.isEmpty)
+ #expect(try await bridge.handle("spaces.droppedFiles", ["names": ["n.txt"]]) as? [String] == [])
+ #expect(try await bridge.handle("spaces.sendFiles", ["spaceId": id, "paths": ["/tmp/n.txt"]]) is [Any])
+ }
+
+ /// The header's list and Settings buttons go through the app's hooks
+ /// when set, else the notch view's own actions.
+ @Test func theNotchHeaderButtonsUseTheAppsHooks() {
+ let c = NotchController(model: NotchModel(scheduler: ManualScheduler()))
+ var calls: [String] = []
+ c.attach(openMain: { calls.append("main") }, openSettings: { calls.append("native settings") })
+ c.run(.list)
+ c.run(.settings)
+ c.onOpenList = { calls.append("list") }
+ c.onOpenSettings = { calls.append("settings") }
+ c.run(.list)
+ c.run(.settings)
+ #expect(calls == ["main", "native settings", "list", "settings"])
+ }
+}
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index f5a664f042..730968c2c8 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -183,7 +183,10 @@ speaks it as is:
the native sheet is the fallback while New UI is off. The app menu's
Settings command (⌘,) sends `settings.openRequested` while the New UI
window is in front, and the page goes to Settings (also with no focus in
- its web view).
+ its web view). While New UI is on, the notch and the menu bar item send
+ `route.openRequested {path}` (a Space's tile `/spaces/<id>`, with
+ `?dropped=[names]` for a drop on it; the list `/spaces`; Settings
+ `/settings`), and the page goes there.
- `machines.list` carries `hostnames` (what each relay machine's cua-spacesd
reported), so a machine and its enrolled device list once.
- `keyvault.unlock` with a passphrase fails with `native_only`.
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index c87b27ec93..f5b2254348 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -167,6 +167,8 @@ export type HostMethod = WebkitMethod | (typeof ELECTRON_HOST_METHODS)[number];
/** The app menu's Settings command (⌘,) while the SwiftUI app's New UI window is in front: go to Settings. */
export const WEBKIT_OPEN_SETTINGS_EVENT = "settings.openRequested";
+/** The SwiftUI app's notch and menu bar item while New UI is on: go to `payload.path` (`/spaces/<id>`, `/settings`, ...). */
+export const WEBKIT_OPEN_ROUTE_EVENT = "route.openRequested";
/** The app menu's Help > Getting Started: show the getting-started checklist again. */
export const WEBKIT_OPEN_CHECKLIST_EVENT = "checklist.openRequested";
diff --git a/apps/cua-spaces-web/src/hooks/use-global-keybindings.test.tsx b/apps/cua-spaces-web/src/hooks/use-global-keybindings.test.tsx
index 60132937ca..ade55f19b5 100644
--- a/apps/cua-spaces-web/src/hooks/use-global-keybindings.test.tsx
+++ b/apps/cua-spaces-web/src/hooks/use-global-keybindings.test.tsx
@@ -5,11 +5,11 @@ import { act, cleanup, render } from "@testing-library/react";
import { createMemoryHistory, createRootRoute, createRoute, createRouter, Outlet, RouterProvider } from "@tanstack/react-router";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { WEBKIT_EVENT, WEBKIT_OPEN_SETTINGS_EVENT } from "@/bridge/webkit-protocol";
+import { WEBKIT_EVENT, WEBKIT_OPEN_ROUTE_EVENT, WEBKIT_OPEN_SETTINGS_EVENT } from "@/bridge/webkit-protocol";
import { isMacPlatform } from "@/lib/utils";
import { useUiStore } from "@/stores/ui";
-import { useGlobalKeybindings } from "./use-global-keybindings";
+import { appPath, useGlobalKeybindings } from "./use-global-keybindings";
afterEach(cleanup);
// The router scrolls on navigation; jsdom has no scrolling.
@@ -24,7 +24,7 @@ function Shell() {
async function mountAt(path: string) {
const root = createRootRoute({ component: Shell });
- const tree = root.addChildren(["/", "/spaces", "/settings"].map((p) => createRoute({ getParentRoute: () => root, path: p, component: () => null })));
+ const tree = root.addChildren(["/", "/spaces", "/spaces/$spaceId", "/settings"].map((p) => createRoute({ getParentRoute: () => root, path: p, component: () => null })));
const router = createRouter({ routeTree: tree, history: createMemoryHistory({ initialEntries: [path] }) });
await act(async () => {
render(<RouterProvider router={router} />);
@@ -33,7 +33,7 @@ async function mountAt(path: string) {
return router;
}
-const hostEvent = (event: string) => window.dispatchEvent(new CustomEvent(WEBKIT_EVENT, { detail: { event } }));
+const hostEvent = (event: string, payload?: unknown) => window.dispatchEvent(new CustomEvent(WEBKIT_EVENT, { detail: { event, payload } }));
describe("global keybindings", () => {
it("opens Settings on ⌘, in the page", async () => {
@@ -54,6 +54,31 @@ describe("global keybindings", () => {
expect(useUiStore.getState().paletteOpen).toBe(false);
});
+ it("goes where the SwiftUI app's notch or menu bar item asks (New UI on)", async () => {
+ const router = await mountAt("/settings");
+ useUiStore.getState().setPaletteOpen(true);
+ const dropped = encodeURIComponent(JSON.stringify(["Slack.app", "a b.txt"]));
+ await act(async () => {
+ hostEvent(WEBKIT_OPEN_ROUTE_EVENT, { path: `/spaces/s%201?dropped=${dropped}` });
+ });
+ expect(router.state.matches.at(-1)?.params).toEqual({ spaceId: "s 1" });
+ expect(router.state.location.search).toEqual({ dropped: ["Slack.app", "a b.txt"] });
+ expect(useUiStore.getState().paletteOpen).toBe(false);
+ await act(async () => {
+ hostEvent(WEBKIT_OPEN_ROUTE_EVENT, { path: "https://example.com/" });
+ hostEvent(WEBKIT_OPEN_ROUTE_EVENT, { path: "//example.com/" });
+ hostEvent(WEBKIT_OPEN_ROUTE_EVENT, null);
+ });
+ expect(router.state.matches.at(-1)?.params).toEqual({ spaceId: "s 1" });
+ });
+
+ it("takes only this app's paths from the host", () => {
+ expect(appPath({ path: "/settings" })).toBe("/settings");
+ expect(appPath({ path: "/keyvault?view=access" })).toBe("/keyvault?view=access");
+ for (const path of ["settings", "//evil.example", "/\\evil.example", "https://evil.example/", 7]) expect(appPath({ path })).toBeNull();
+ expect(appPath(null)).toBeNull();
+ });
+
it("ignores the host's other events and stops listening when it unmounts", async () => {
const router = await mountAt("/spaces");
await act(async () => {
diff --git a/apps/cua-spaces-web/src/hooks/use-global-keybindings.ts b/apps/cua-spaces-web/src/hooks/use-global-keybindings.ts
index a1594a8802..bfc46edd33 100644
--- a/apps/cua-spaces-web/src/hooks/use-global-keybindings.ts
+++ b/apps/cua-spaces-web/src/hooks/use-global-keybindings.ts
@@ -4,7 +4,7 @@
import { useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
-import { WEBKIT_EVENT, WEBKIT_OPEN_SETTINGS_EVENT, type WebkitEventDetail } from "@/bridge/webkit-protocol";
+import { WEBKIT_EVENT, WEBKIT_OPEN_ROUTE_EVENT, WEBKIT_OPEN_SETTINGS_EVENT, type WebkitEventDetail } from "@/bridge/webkit-protocol";
import { resolveCommand, type KeybindingCommand } from "@/lib/keybindings";
import { useThemeStore } from "@/lib/theme";
import { useUiStore } from "@/stores/ui";
@@ -49,10 +49,20 @@ export function useGlobalKeybindings(): void {
};
// The SwiftUI app's Settings command (⌘, in its menu) reaches the page as an event, so it works
// when the web view has no focus too (the native menu gets the key first then).
+ // Its notch and menu bar item open a page of the app (New UI on) the same way.
const onHostEvent = (event: Event) => {
- if ((event as CustomEvent<WebkitEventDetail>).detail?.event !== WEBKIT_OPEN_SETTINGS_EVENT) return;
- useUiStore.getState().setPaletteOpen(false);
- void navigate({ to: "/settings" });
+ const detail = (event as CustomEvent<WebkitEventDetail>).detail;
+ if (detail?.event === WEBKIT_OPEN_SETTINGS_EVENT) {
+ useUiStore.getState().setPaletteOpen(false);
+ void navigate({ to: "/settings" });
+ return;
+ }
+ if (detail?.event === WEBKIT_OPEN_ROUTE_EVENT) {
+ const path = appPath(detail.payload);
+ if (!path) return;
+ useUiStore.getState().setPaletteOpen(false);
+ void navigate({ href: path });
+ }
};
window.addEventListener("keydown", onKeyDown);
window.addEventListener(WEBKIT_EVENT, onHostEvent);
@@ -62,3 +72,10 @@ export function useGlobalKeybindings(): void {
};
}, [navigate]);
}
+
+/** The host's route: a path of this app (`/spaces/x?dropped=...`), never another origin. */
+export function appPath(payload: unknown): string | null {
+ const path = (payload as { path?: unknown } | null)?.path;
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return null;
+ return path;
+}