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): picture in picture hands the live desktop back; the ⋯ menu no longer blacks it out (CUA-2473) (#6055)
ddupont3d6be5173e4f
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/VideoSurfaceLayout.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/VideoSurfaceLayout.swiftindex fcd02184ac..43eb9aa82c 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/VideoSurfaceLayout.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/VideoSurfaceLayout.swift@@ -40,6 +40,9 @@ struct VideoSurfaceUpdate: Equatable {var clip: CGRect?var radius: CGFloatvar occluded: Bool+ /// Floating page UI over the slot (a menu, a popover, a tooltip, a+ /// toast, the viewer's key bar), CSS px like `rect`: no video there.+ var holes: [CGRect] = []var visible: Bool/// Reads one entry of a `surfaces` message's `update`; nil when it is malformed.@@ -55,11 +58,12 @@ struct VideoSurfaceUpdate: Equatable {clip = Self.rect(json["clip"])radius = Self.number(json["radius"])occluded = json["occluded"] as? Bool ?? false+ holes = (json["holes"] as? [Any] ?? []).compactMap(Self.rect)visible = json["visible"] as? Bool ?? true}init(surfaceId: String, spaceId: String, tier: VideoTier, interactive: Bool, rect: CGRect,- clip: CGRect?, radius: CGFloat = 0, occluded: Bool = false, visible: Bool = true) {+ clip: CGRect?, radius: CGFloat = 0, occluded: Bool = false, holes: [CGRect] = [], visible: Bool = true) {self.surfaceId = surfaceIdself.spaceId = spaceIdself.tier = tier@@ -68,6 +72,7 @@ struct VideoSurfaceUpdate: Equatable {self.clip = clipself.radius = radiusself.occluded = occluded+ self.holes = holesself.visible = visible}@@ -116,6 +121,10 @@ struct VideoSurfaceLayout: Equatable {/// The video, in the container's flipped (top-left) coordinates.var video: CGRectvar radius: CGFloat+ /// Where floating page UI sits over the video, in the container's+ /// flipped coordinates: the video is cut out there so the page's menu+ /// (or tooltip, toast, key bar) shows, and the rest keeps playing.+ var holes: [CGRect] = []/// Nothing to draw: off screen, clipped away, covered by page UI or empty.var hidden: Bool@@ -128,13 +137,31 @@ struct VideoSurfaceLayout: Equatable {let clip = scaled(clipCSS, z)let rect = scaled(u.rect, z)let y = flipped ? clip.minY : viewHeight - clip.maxY+ let bounds = CGRect(origin: .zero, size: clip.size)+ let holes = u.holes.compactMap { hole -> CGRect? in+ let h = scaled(hole, z).offsetBy(dx: -clip.minX, dy: -clip.minY).intersection(bounds)+ return h.isNull || h.width <= 0 || h.height <= 0 ? nil : h+ }return VideoSurfaceLayout(container: CGRect(x: clip.minX, y: y, width: clip.width, height: clip.height),video: rect.offsetBy(dx: -clip.minX, dy: -clip.minY),radius: max(0, u.radius * z),+ holes: holes,hidden: false)}+ /// The container's visible shape: all of it but the holes (nil: no holes, no mask).+ var maskPath: CGPath? {+ guard !holes.isEmpty else { return nil }+ let cut = CGMutablePath()+ for h in holes { cut.addRect(h) }+ return CGPath(rect: CGRect(origin: .zero, size: container.size), transform: nil)+ .subtracting(cut, using: .winding)+ }++ /// Whether a point (container coordinates) is in a hole: the page's UI there takes the click.+ func inHole(_ p: CGPoint) -> Bool { holes.contains { $0.contains(p) } }+private static func scaled(_ r: CGRect, _ z: CGFloat) -> CGRect {CGRect(x: r.minX * z, y: r.minY * z, width: r.width * z, height: r.height * z)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 1d01ac3ca7..feacbb20f3 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -278,7 +278,11 @@ extension WebUIBridge {} else {throw Failure.notFound("no window \(row)")}- if type == "open" { stream.pips.popOut(source) } else { stream.pips.popIn(source) }+ if type == "open" {+ try await popOut(source, of: try spaceId(args), stream: stream)+ } else {+ stream.pips.popIn(source)+ }return stream.rows.openRows(openKeys: stream.pips.openKeys)// This machine@@ -752,9 +756,43 @@ extension WebUIBridge {let s = (rows: StreamRowsModel(space: space, provider: provider, backend: model.backend),pips: StreamPiPSet(provider: provider))streams[id] = s+ watchPanels(of: id, pips: s.pips, rows: s.rows)return s}+ /// Pops a source out. The desktop shows this window's own viewer+ /// session (the inline desktop's), held while the panel is open: no+ /// second stream opens, and closing the panel hands the same live+ /// session back to the page, with no reconnect. A window (or a window+ /// with no native video) gets a session of its own.+ func popOut(_ source: StreamSource, of id: String,+ stream: (rows: StreamRowsModel, pips: StreamPiPSet)) async throws {+ guard source == .desktop, !stream.pips.isOpen(.desktop), let surfaces = host?.videoSurfaces else {+ stream.pips.popOut(source)+ return+ }+ let session = try await surfaces.holdViewer(spaceId: id)+ heldDesktops.insert(id)+ stream.pips.popOut(.desktop, sharing: session)+ }++ /// Follows a Space's open panels: tells the page when they change (a+ /// panel closed by its own button), and lets go of the viewer session a+ /// closed desktop panel held.+ func watchPanels(of id: String, pips: StreamPiPSet, rows: StreamRowsModel) {+ pipWatches[id] = pips.$openKeys.dropFirst().removeDuplicates().sink { [weak self, weak rows] keys in+ guard let self else { return }+ if !keys.contains(StreamSource.desktop.pipKey), self.heldDesktops.remove(id) != nil {+ self.host?.videoSurfaces?.releaseViewer(spaceId: id)+ }+ let open = rows?.openRows(openKeys: keys) ?? []+ self.host?.emit(Self.pipChangedEvent, payload: ["spaceId": id, "open": open])+ }+ }++ /// The page's `PIP_CHANGED_EVENT` (apps/cua-spaces-web/src/bridge/space-detail.ts).+ static let pipChangedEvent = "stream.pipChanged"+/// Closes and drops the streams of Spaces that are gone (a loaded/// roster only: an empty one is a launch, not a deletion).func pruneStreams() {@@ -763,6 +801,7 @@ extension WebUIBridge {for id in streams.keys where !ids.contains(id) {streams[id]?.pips.popInAll()streams[id] = nil+ pipWatches[id] = nil}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex dabee04a7e..9cc97e9b3d 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -2,6 +2,7 @@// Copyright (c) 2026 Cua AI, Inc.import AppKit+import Combineimport CuaSDKimport CuaSpacesFFIimport CuaSpacesStreaming@@ -159,6 +160,13 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {/// detail view keeps them. A deleted Space's are closed and dropped/// (`pruneStreams`).var streams: [String: (rows: StreamRowsModel, pips: StreamPiPSet)] = [:]+ /// Each Space's watch on its open panels: the page hears a panel that+ /// closed by itself (`stream.pipChanged`), and the desktop panel's hold+ /// on the viewer session goes when it closes.+ var pipWatches: [String: AnyCancellable] = [:]+ /// Spaces whose desktop panel holds this window's viewer session+ /// (`WebUIVideoSurfaces.holdViewer`).+ var heldDesktops: Set<String> = []/// The page has called in since it last loaded (its listener is up).var pageListening = false/// A New Space asked for before the page listened (`on`: "Run on").diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swiftindex 0f5f291577..295dfa1771 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift@@ -88,7 +88,12 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {/// One session per Space and tier, shared by its surfaces.final class Stream {var session: LiveStreamSession?+ /// Slots showing it, plus holds (`holdViewer`).var users = 0+ /// Holders other than slots: the desktop's picture-in-picture panel,+ /// which shows this same session. A held stream keeps going while+ /// the window is hidden, and outlives its slots.+ var holds = 0var opening: Task<Void, Never>?var failure: String?var status: AnyCancellable?@@ -330,14 +335,80 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {surface.view.removeFromSuperview()if surfaces.isEmpty { unwatchWindow() }guard let stream = streams[surface.key] else { return }+ letGo(stream, key: surface.key)+ }++ /// One user fewer; the last one stops the session.+ private func letGo(_ stream: Stream, key: StreamKey) {stream.users -= 1- guard stream.users <= 0 else { return }- streams[surface.key] = nil+ guard stream.users <= 0, streams[key] === stream else { return }+ streams[key] = nilstream.opening?.cancel()stream.status?.cancel()if let session = stream.session { Task { await session.stop() } }}+ // MARK: - Picture in picture++ /// How long a released hold keeps the session for the page's slot to+ /// come back to it (the page hears the panel closed, then mounts its+ /// slot again).+ static let handBackGrace: Duration = .seconds(5)++ /// The Space's viewer session (its full-tier stream), held for the+ /// desktop's picture-in-picture panel: the panel shows this same+ /// session, so popping out and back in never closes or reopens the+ /// stream. The inline slot that comes back binds to the live session+ /// and shows its current frame at once. Opens the stream when no slot+ /// has. Balance with `releaseViewer`.+ func holdViewer(spaceId: String) async throws -> LiveStreamSession {+ let key = StreamKey(spaceId: spaceId, tier: .full)+ let stream: Stream+ if let existing = streams[key], existing.failure == nil {+ stream = existing+ } else {+ // A stream that failed to open starts over for the panel.+ if let failed = streams[key] { failed.opening?.cancel(); failed.status?.cancel() }+ stream = Stream()+ stream.users = streams[key]?.users ?? 0+ streams[key] = stream+ }+ stream.users += 1+ stream.holds += 1+ if stream.session == nil, stream.opening == nil { openStream(stream, key: key) }+ await stream.opening?.value+ guard let session = stream.session else {+ let why = stream.failure ?? "the desktop stream did not open"+ stream.holds -= 1+ letGo(stream, key: key)+ throw Failure(why)+ }+ // A hidden window paused it; the panel shows it regardless.+ if paused { Task { await session.start() } }+ return session+ }++ /// The panel closed: after `grace`, the hold goes (the session stops+ /// unless a slot shows it by then).+ func releaseViewer(spaceId: String, after grace: Duration = handBackGrace) {+ let key = StreamKey(spaceId: spaceId, tier: .full)+ guard let stream = streams[key], stream.holds > 0 else { return }+ Task { @MainActor [weak self, weak stream] in+ if grace > .zero { try? await Task.sleep(for: grace) }+ guard let self, let stream else { return }+ stream.holds -= 1+ self.letGo(stream, key: key)+ if self.paused, stream.holds == 0, self.streams[key] === stream, let session = stream.session {+ await session.stop()+ }+ }+ }++ struct Failure: Error, CustomStringConvertible {+ let description: String+ init(_ description: String) { self.description = description }+ }+/// The streams and their sessions (the harness's stats).func streamsSnapshot() -> [(StreamKey, Stream)] { streams.map { ($0.key, $0.value) } }@@ -412,7 +483,8 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {guard hidden != paused else { return }paused = hiddenfor stream in streams.values {- guard let session = stream.session else { continue }+ // The picture-in-picture panel shows a held stream: it keeps going.+ guard let session = stream.session, stream.holds == 0 else { continue }Task { hidden ? await session.stop() : await session.start() }}}@@ -446,11 +518,34 @@ final class VideoSurfaceView: NSView {override var isFlipped: Bool { true }+ /// Where the page's floating UI sits over the video (container coordinates).+ private(set) var layout = VideoSurfaceLayout.none+func apply(_ layout: VideoSurfaceLayout) {+ self.layout = layoutframe = layout.containerinput.frame = layout.videoinput.layer?.cornerRadius = layout.radiuspresence?.frame = layout.video+ applyHoles()+ }++ /// Cuts the video out under the page's menus, popovers, tooltips and+ /// toasts, so they show and the rest of the desktop keeps playing+ /// (hiding the whole view for a menu turned it black).+ private func applyHoles() {+ guard let layer else { return }+ guard !layout.holes.isEmpty else {+ layer.mask = nil+ return+ }+ // The holes are in this (flipped) view's coordinates: into the layer's.+ let toLayer = VideoSurfaceLayout(container: layout.container, video: layout.video, radius: layout.radius,+ holes: layout.holes.map { convertToLayer($0) }, hidden: layout.hidden)+ let mask = (layer.mask as? CAShapeLayer) ?? CAShapeLayer()+ mask.frame = layer.bounds+ mask.path = toLayer.maskPath+ layer.mask = mask}/// Adds the presence layer over the picture. It takes no clicks or keys@@ -475,6 +570,8 @@ final class VideoSurfaceView: NSView {override func hitTest(_ point: NSPoint) -> NSView? {guard interactive, !isHidden else { return nil }+ // Over a hole the page's own UI (a menu, the key bar) takes the click.+ if layout.inHole(convert(point, from: superview)) { return nil }if NSApp.currentEvent?.type == .scrollWheel, window?.firstResponder !== input { return nil }return super.hitTest(point)}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swiftindex 6a6c6c5ce4..129f9546f9 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift@@ -474,6 +474,117 @@ struct WebUIVideoSurfacesTests {s.removeAll()}+ // MARK: - Picture in picture++ /// Regression: closing the desktop's picture in picture showed "Could+ /// not connect to the desktop", then "Connecting…", before the inline+ /// desktop came back: the panel opened a second stream, the inline one+ /// closed, and closing the panel closed that one and dialled again. The+ /// panel now holds the viewer's own session; the slot that comes back+ /// binds to it, live at once, with no second open and no failure.+ @Test func pictureInPictureHandsTheSameLiveSessionBackWithNoReopen() async throws {+ let host = Host()+ let units = AccessUnit.split(Self.tinyH264)+ let s = surfaces(host) { _, _ in SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30) }+ s.handle(message([entry("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ let first = try #require(s.surfaces["v1"])+ let inline = try #require(s.sessionFor(first))++ // Popped out: the panel holds the same session, and the page's slot goes.+ let held = try await s.holdViewer(spaceId: "a")+ #expect(held === inline)+ s.handle(message([], remove: ["v1"]))+ #expect(host.opened.count == 1)+ #expect(held.status == .streaming)+ // A hidden window pauses slots, never the panel's stream.+ s.setPaused(true)+ try? await Task.sleep(for: .milliseconds(100))+ #expect(held.status == .streaming)+ s.setPaused(false)++ // Closed: the slot that comes back is live at once, on the same session.+ s.releaseViewer(spaceId: "a", after: .milliseconds(200))+ s.handle(message([entry("v2", space: "a")]))+ // Its first word is live, on the next main-queue turn (the session's current frame).+ await settle(tries: 5) { !host.phases("v2").isEmpty }+ #expect(host.phases("v2") == ["live"])+ let back = try #require(s.surfaces["v2"])+ #expect(s.sessionFor(back) === inline)+ try? await Task.sleep(for: .milliseconds(400))+ #expect(host.opened.count == 1)+ #expect(!host.events.contains { $0.0 == "video.surface" && $0.1["state"] as? String == "failed" })+ #expect(s.stats().first?["users"] as? Int == 1)+ s.removeAll()+ #expect(s.stats().isEmpty)+ }++ @Test func aReleasedHoldWithNoSlotStopsTheStreamAfterTheGrace() async throws {+ let host = Host()+ let units = AccessUnit.split(Self.tinyH264)+ let s = surfaces(host) { _, _ in SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30) }+ // No inline slot (auto-connect off): the panel opens the viewer stream itself.+ let held = try await s.holdViewer(spaceId: "a")+ #expect(host.opened.map(\.1) == [.full])+ #expect(s.stats().count == 1)+ s.releaseViewer(spaceId: "a", after: .zero)+ await settle { s.stats().isEmpty }+ #expect(s.stats().isEmpty)+ await settle { held.status == .idle }+ #expect(held.status == .idle)+ }++ @Test func aHoldOnAStreamThatCannotOpenThrowsAndKeepsNothing() async {+ let host = Host()+ let s = surfaces(host) { _, _ in throw StreamError.noStream("no stream for this Space") }+ await #expect(throws: (any Error).self) { try await s.holdViewer(spaceId: "a") }+ #expect(s.stats().isEmpty)+ }++ // MARK: - Holes++ @Test func readsHolesAndMapsThemIntoTheClipContainer() throws {+ var u = update(rect: CGRect(x: 100, y: 100, width: 400, height: 300), clip: CGRect(x: 100, y: 120, width: 400, height: 280))+ u.holes = [CGRect(x: 420, y: 90, width: 160, height: 60), CGRect(x: 700, y: 0, width: 10, height: 10)]+ let l = VideoSurfaceLayout.make(u, zoom: 2, viewHeight: 1000, flipped: true)+ #expect(!l.hidden)+ // In the container (from 100,120, doubled), cut to it; the hole off the slot is dropped.+ #expect(l.holes == [CGRect(x: 640, y: 0, width: 160, height: 60)])+ #expect(l.inHole(CGPoint(x: 700, y: 10)))+ #expect(!l.inHole(CGPoint(x: 10, y: 10)))+ let mask = try #require(l.maskPath)+ #expect(!mask.contains(CGPoint(x: 700, y: 10)))+ #expect(mask.contains(CGPoint(x: 10, y: 10)))+ #expect(VideoSurfaceLayout.make(update(rect: u.rect, clip: u.clip), zoom: 1, viewHeight: 1000, flipped: true).maskPath == nil)++ let parsed = VideoSurfaceUpdate(json: ["surfaceId": "s", "spaceId": "a", "rect": ["x": 0, "y": 0, "width": 10, "height": 10],+ "holes": [["x": 1, "y": 2, "width": 3, "height": 4], "bad"]])+ #expect(parsed?.holes == [CGRect(x: 1, y: 2, width: 3, height: 4)])+ }++ /// Regression: the header's "⋯" menu turned the desktop black. A menu+ /// over the viewer is a hole now: the video stays shown and live, and+ /// clicks in the hole reach the page's menu.+ @Test func aMenuOverTheViewerCutsAHoleAndTheVideoStaysLive() async throws {+ let host = Host()+ let units = AccessUnit.split(Self.tinyH264)+ let s = surfaces(host) { _, _ in SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30) }+ s.handle(message([entry("v", space: "a")]))+ await settle { host.phases("v").contains("live") }+ var withMenu = entry("v", space: "a")+ withMenu["holes"] = [["x": 300, "y": 30, "width": 160, "height": 40]]+ s.handle(message([withMenu]))+ let view = try #require(s.surfaces["v"]?.view)+ #expect(!view.isHidden)+ #expect(view.layer?.mask != nil)+ #expect(view.layout.inHole(CGPoint(x: 330, y: 10)))+ #expect(host.phases("v").last == "live")+ // Closed: no mask.+ s.handle(message([entry("v", space: "a")]))+ #expect(view.layer?.mask == nil)+ s.removeAll()+ }+@Test func theHarnessAddsRunningFixtureSpaces() {#expect(FixtureSpacesBackend.rows(environment: [:]).count == FixtureSpacesBackend.sample.count)let rows = FixtureSpacesBackend.rows(environment: ["CUA_SPACES_FIXTURE_SPACES": "3"])diff --git a/apps/cua-spaces-macos/docs/native-video.md b/apps/cua-spaces-macos/docs/native-video.mdindex 97e8177a24..ce19e157ba 100644--- a/apps/cua-spaces-macos/docs/native-video.md+++ b/apps/cua-spaces-macos/docs/native-video.md@@ -29,17 +29,18 @@ The page keeps one reporter, with one set of observers and one animation frame.```{ type: "surfaces", update: [{ surfaceId, spaceId, tier: "tile" | "full", interactive,- rect, clip, radius, occluded, visible }], remove: [surfaceId] }+ rect, clip, radius, occluded, holes, visible }], remove: [surfaceId] }{ type: "focus", surfaceId | null }```- **`rect`** is the video area inside the slot's border, in CSS px from the web view's top left.- **`clip`** is the part of `rect` that the viewport and every clipping ancestor leave visible. For example, a tile scrolled halfway under the page's top edge is cut there.-- **`occluded`** is true when page UI covers the slot. Two checks feed it:- - an element matching `[role=dialog|alertdialog|menu|listbox|tooltip]` or `[data-video-occluder]` (toasts, tooltips) overlaps the slot;+- **`occluded`** is true when page UI covers the slot, and the host hides the video. Two checks feed it:+ - an element matching `[role=dialog|alertdialog]` overlaps the slot;- something else is on top at one of 9 sample points (a dialog's backdrop, for example).- The sample points sit inside the rounded corners.+ The sample points sit inside the rounded corners. Transparent click catchers (`[data-base-ui-inert]`, which Base UI puts under an open menu or popover) paint nothing and are looked through, and floating UI that gets a hole doesn't count.+- **`holes`** are the rects of floating UI over the slot, cut to `clip`: `[role=menu|listbox|tooltip]`, `[data-video-occluder]` (toasts, popovers) and `[data-video-hole]` (the viewer's own key bar, inside the slot). The host masks the video out there, so the menu shows and the rest of the desktop keeps playing, and clicks there go to the page. Hiding the whole video for a menu turned it black while the menu was open.- **`visible`** is false when the page is hidden or the slot is clipped away entirely.**When it measures.**@@ -77,7 +78,7 @@ CSS px become points through `pageZoom × magnification`. A web view that isn't**Visibility.** A surface shows only when the page says it can be seen and it has a frame.-**Pausing.** While the window is fully hidden (minimized, covered, or on another Space), every session stops. They open again when the window shows.+**Pausing.** While the window is fully hidden (minimized, covered, or on another Space), every session stops but the one the desktop's picture-in-picture panel shows. They open again when the window shows.**Lifecycle.** A page load (`didCommit`), the web content process ending, and the window closing all tear every surface and session down.@@ -88,7 +89,7 @@ CSS px become points through `pageZoom × magnification`. A web view that isn't- **Scroll:** scrolls go to the page until the viewer has the keyboard. After that they go to the Space.- **Getting the keyboard:** a click on the viewer gives it the keyboard (it becomes the first responder).- **While it has the keyboard:**- - the line under the viewer says "Keys go to this Space. Press and release ⌃⌥ to stop." with a **Stop controlling** button;+ - a small bar over the viewer's bottom edge (a hole in the video) says "Keys go to this Space. Press and release ⌃⌥ to stop." with a **Stop controlling** button;- every ⌘ chord (⌘Esc too) goes to the Space, because a local key monitor routes it to the view before the web view takes ⌘C and ⌘V (the view's `KeyCapture`, as in the Space window);- on a Linux or Windows Space, ⌘ goes as Control: ⌘C arrives as Ctrl+C and ⌘⇧C as Ctrl+Shift+C. Sent as Command, the Space would get Super, and Super+C types "c". A macOS Space keeps ⌘. The Space window does the same, since both send through `LiveStreamSession`, and so does the HTML5 viewer (`metaAsControl`);- plain Esc goes to the Space too. Remote apps need it.@@ -99,7 +100,7 @@ CSS px become points through `pageZoom × magnification`. A web view that isn't- the viewer being covered by page UI or leaving the screen.Keys then go back to the page, and the page hears it.-- **Without the keyboard:** "Click the desktop to control it." Open in window is always next to it.+- **Without the keyboard:** nothing under the viewer. The Space header's picture-in-picture button pops the desktop out.- **The pointer:** the system pointer is never hidden or replaced. Like the native window, the viewer also draws its small local cursor dot when the Space has no presence cursor.- **Input lease:** there is no input-lease UI in the native viewer yet, so there is none here either.@@ -170,20 +171,21 @@ Scroll tracking was checked by eye only: tiles follow a scroll and clip under thA live E2E should check:1. **Tiles.** Turn the experiment on and open New UI with 2 or more running local Spaces. Tiles go live within a few seconds. Clicking a tile opens the Space, and scrolling the grid moves and clips the video correctly.-2. **The viewer.** Open a Space. Its viewer goes live and "Click the desktop to control it." shows.+2. **The viewer.** Open a Space. Its viewer goes live, with nothing under it.- Click inside: the click lands in the Space at the right place.- Type: keys arrive, including ⌘C and ⌘V inside the Space.- - Control+Option pressed and released alone: the line goes back to "Click the desktop…".+ - Control+Option pressed and released alone: the key bar over the viewer goes.- Scroll: the page scrolls before you click, and the Space scrolls after.-3. **Covering.** Open the command palette (⌘K), the Stop dialog and a toast over the viewer. The video hides while each is open, keys go to the dialog, and the video comes back after.-4. **Failure.** Stop a Space while its viewer is open. You should see the stopped state, not a frozen frame. Then delete a Space with an open tile.-5. **Hidden window.** Minimize the window, then restore it. The streams pause, then come back.-6. **The pointer.** The system pointer stays visible throughout.-7. **Cost.** `top` on Cua Spaces with 8 to 10 live tiles stays near the harness numbers.+3. **Covering.** Open the command palette (⌘K) and the Stop dialog over the viewer. The video hides while each is open, keys go to the dialog, and the video comes back after. Open the header's "⋯" menu and show a toast: the video stays live, with only the part under the menu or toast cut out.+4. **Picture in picture.** Pop the desktop out from the header, then close the panel (its own button or the header's): the inline desktop is live again at once, with no "Connecting…" and no error.+5. **Failure.** Stop a Space while its viewer is open. You should see the stopped state, not a frozen frame. Then delete a Space with an open tile.+6. **Hidden window.** Minimize the window, then restore it. The streams pause, then come back. A desktop popped out to picture in picture keeps playing in its panel.+7. **The pointer.** The system pointer stays visible throughout.+8. **Cost.** `top` on Cua Spaces with 8 to 10 live tiles stays near the harness numbers.## Not done yet-- The viewer has no window switcher and no picture-in-picture of its own. The Stream section's PiP buttons still open native panels.+- The viewer has no window switcher. Picture in picture opens native panels: the desktop's panel shows the viewer's own `LiveStreamSession` (`WebUIVideoSurfaces.holdViewer`), held while it is open and for `handBackGrace` after, so popping out and back in never closes or reopens the stream and the inline desktop is live again at once. The host tells the page when a panel closes by its own button (`stream.pipChanged`). A window's panel opens a session of its own.- Presence cursors of other participants aren't drawn in the embedded viewer. The native window draws them in SwiftUI (`PresenceOverlay`).- A tile and the viewer of the same Space open two sessions. That only happens with two windows open.- Windows and Linux (Electron, WebCodecs): see `apps/cua-spaces-desktop/README.md`, "Live video".diff --git a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.tsindex 3dbf0487dd..ffbcdc72b9 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.+import { readFileSync } from "node:fs";+import { resolve } from "node:path";import { describe, expect, it, vi } from "vitest";import { HostError } from "../adapter";import { createDemoAdapter } from "../adapters/demo";@@ -9,7 +11,7 @@ import { sanitizeSignals } from "../ops/telemetry";import { TelemetryForwarder, telemetryAllowed } from "../telemetry";import { toMachineRows } from "../adapters/webkit";import { machineIdOf, rowsToSpaces, toMachines } from "../derive";-import { agentRunLines, desktopCover, SpaceDetailStore, spaceDetail } from "../space-detail";+import { agentRunLines, desktopCover, PIP_CHANGED_EVENT, SpaceDetailStore, spaceDetail } from "../space-detail";import type { CoreClient } from "../core";import { parseDropped, sendFiles, splitDrop } from "../space-files";import type { MachineAccessNotice } from "../contracts/devices";@@ -108,6 +110,36 @@ describe("demo host: Space detail and This machine", () => {demo.dispose?.();});+ // Regression: a picture-in-picture panel closed by its own button left+ // "Playing in a floating window" on the page until the next windows read+ // (up to WINDOWS_REFRESH_MS), and the inline desktop came back late. The+ // host says so at once (`stream.pipChanged`).+ it("hears a panel the host closed by itself at once, without waiting for a windows read", () => {+ const demo = createDemoAdapter({ latencyMs: 0 });+ const core = { tryCall: () => null } as unknown as CoreClient;+ const store = new SpaceDetailStore(demo, core);+ const id = "local:design-review";+ const say = (payload: unknown) => window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: PIP_CHANGED_EVENT, payload } }));+ say({ spaceId: id, open: ["desktop"] });+ expect(store.get(id).open).toEqual(["desktop"]);+ say({ spaceId: id, open: [] });+ expect(store.get(id).open).toEqual([]);+ // Malformed: ignored.+ say({ spaceId: id, open: "desktop" });+ say({ open: ["desktop"] });+ expect(store.get(id).open).toEqual([]);+ store.dispose();+ say({ spaceId: id, open: ["desktop"] });+ expect(store.get(id).open).toEqual([]);+ demo.dispose?.();+ });++ // Drift guard: the SwiftUI host sends the event the page listens for.+ it("listens for the event the SwiftUI host sends when its panels change", () => {+ const swift = readFileSync(resolve(__dirname, "../../../../cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift"), "utf8");+ expect(swift).toContain(`static let pipChangedEvent = "${PIP_CHANGED_EVENT}"`);+ });+it("sets this machine up, stops sharing and removes the setup", async () => {const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });expect((await demo.call("host.action", { action: "stop-sharing" })).sharing).toBe(false);diff --git a/apps/cua-spaces-web/src/bridge/space-detail.ts b/apps/cua-spaces-web/src/bridge/space-detail.tsindex 1195a679e1..d1ce26bf24 100644--- a/apps/cua-spaces-web/src/bridge/space-detail.ts+++ b/apps/cua-spaces-web/src/bridge/space-detail.ts@@ -41,6 +41,9 @@ export const THIS_MACHINE_ID = "this-mac";export const USAGE_REFRESH_MS = 10_000;export const WINDOWS_REFRESH_MS = 5_000;+/** The host's raw `cua:event` when its picture-in-picture panels change by+ * themselves (`{ spaceId, open: rows }`; the SwiftUI app's `stream.pipChanged`). */+export const PIP_CHANGED_EVENT = "stream.pipChanged";/** How often a shown Space's agent runs are read (`AgentRunsModel.poll`). */export const RUNS_REFRESH_MS = 4_000;@@ -189,7 +192,24 @@ export class SpaceDetailStore {constructor(private readonly adapter: DataAdapter,private readonly core: CoreClient,- ) {}+ ) {+ globalThis.window?.addEventListener?.("cua:event", this.onHostEvent);+ }++ /**+ * The host closed or opened a picture-in-picture panel by itself (the+ * panel's own close button): the page hears it now, not on the next+ * windows read (`WINDOWS_REFRESH_MS`), so the inline desktop is back at+ * once (`PIP_CHANGED_EVENT`).+ */+ private onHostEvent = (e: Event): void => {+ const detail = (e as CustomEvent<{ event?: string; payload?: { spaceId?: unknown; open?: unknown } | null }>).detail;+ if (detail?.event !== PIP_CHANGED_EVENT) return;+ const { spaceId, open } = detail.payload ?? {};+ if (typeof spaceId !== "string" || !Array.isArray(open) || this.held.has(spaceId)) return;+ const rows = open.filter((r): r is string => typeof r === "string");+ this.patch(spaceId, { open: pipReduce(this.core, this.get(spaceId).open, { type: "synced", rows }) });+ };subscribe = (l: () => void): (() => void) => {this.listeners.add(l);@@ -298,6 +318,7 @@ export class SpaceDetailStore {dispose(): void {this.disposed = true;+ globalThis.window?.removeEventListener?.("cua:event", this.onHostEvent);for (const w of this.watched.values()) w.timers.forEach(clearTimeout);this.watched.clear();this.listeners.clear();diff --git a/apps/cua-spaces-web/src/components/space-detail/stream-surface.tsx b/apps/cua-spaces-web/src/components/space-detail/stream-surface.tsxindex 7988d33300..fa728e2719 100644--- a/apps/cua-spaces-web/src/components/space-detail/stream-surface.tsx+++ b/apps/cua-spaces-web/src/components/space-detail/stream-surface.tsx@@ -34,9 +34,12 @@ import { cn, isMacPlatform } from "@/lib/utils";* registers the `cuaVideo` handler (the SwiftUI shell, unless its* `WebUINativeVideo` default is NO) and the Space can stream, the host draws* the Space's desktop over the block and sends it pointer, scroll and keys.- * A line under the block says where keys go and how to take them back- * (Control+Option pressed and released alone, or a click outside). Anywhere else it is the placeholder, and the- * desktop opens in its own native window.+ * Nothing sits under the block (the header's picture-in-picture button is+ * the way out to a window of its own): while the desktop has the keyboard,+ * a small bar over its bottom edge says how to take keys back (Control+Option+ * pressed and released alone, a click outside, or Stop controlling), and+ * the host cuts the video out under that bar (`data-video-hole`). Anywhere+ * else it is the placeholder, and the desktop opens in its own native window.*/export interface StreamSurfaceProps {spaceId: string;@@ -77,7 +80,12 @@ export const CONNECT_TIMEOUT_REASON = "No picture arrived from the desktop withifunction useTimedOut(waiting: boolean, ms: number, key: string): boolean {const [over, setOver] = useState<string | null>(null);useEffect(() => {- if (!waiting) return;+ // A wait that ended (a picture came, or the slot went away) is forgotten:+ // the next wait under the same key starts from zero, never already over.+ if (!waiting) {+ setOver(null);+ return;+ }const t = setTimeout(() => setOver(key), ms);return () => clearTimeout(t);}, [waiting, ms, key]);@@ -150,82 +158,72 @@ export function StreamSurface({ spaceId, os, aspectRatio = 16 / 10, canStream, pconst reason = timedOut ? CONNECT_TIMEOUT_REASON : slot?.phase === "failed" ? (slot.reason ?? null) : null;const dark = covered && (Boolean(thumbnail) || cover.kind !== "status");return (- <>- <div- ref={ref}- data-stream-surface={spaceId}- data-stream-state={state}- data-aspect={aspectRatio.toFixed(4)}- className={cn("relative w-full overflow-hidden rounded-lg", dark ? "bg-black" : "bg-muted/40", className)}- >- {covered ? (- cover.kind === "stream" ? null : (- <DesktopCoverView- os={os}- cover={cover}- thumbnail={access ? null : thumbnail}- reason={cover.kind === "status" ? reason : null}- onButton={press}- onAction={onAccessAction}- onOpen={slot?.phase === "failed" ? () => void open() : undefined}- />- )- ) : (- <div className="absolute inset-0 flex flex-col items-center justify-center px-6 text-center">- {children ?? (- <>- <OsIcon os={os} className="mb-4 size-8 text-muted-foreground/30" />- {canStream ? (- <>- <p className="text-[13px] text-muted-foreground">{windowId && windowName ? `${windowName} opens in its own window.` : "The desktop opens in its own window."}</p>- <Button className="mt-4" onClick={() => void open()}>- <AppWindowIcon /> Open window- </Button>- </>- ) : (- <p data-preview-text className="text-[13px] text-muted-foreground">- {previewText}- </p>- )}- </>- )}- </div>- )}- </div>- {slot ? (- <div data-video-focus={slot.focused ? "space" : "page"} className="mt-2 flex h-7 items-center justify-between gap-3 px-1 text-xs text-muted-foreground">+ <div+ ref={ref}+ data-stream-surface={spaceId}+ data-stream-state={state}+ data-aspect={aspectRatio.toFixed(4)}+ className={cn("relative w-full overflow-hidden rounded-lg", dark ? "bg-black" : "bg-muted/40", className)}+ >+ {covered ? (+ cover.kind === "stream" ? null : (+ <DesktopCoverView+ os={os}+ cover={cover}+ thumbnail={access ? null : thumbnail}+ reason={cover.kind === "status" ? reason : null}+ onButton={press}+ onAction={onAccessAction}+ onOpen={slot?.phase === "failed" ? () => void open() : undefined}+ />+ )+ ) : (+ <div className="absolute inset-0 flex flex-col items-center justify-center px-6 text-center">+ {children ?? (+ <>+ <OsIcon os={os} className="mb-4 size-8 text-muted-foreground/30" />+ {canStream ? (+ <>+ <p className="text-[13px] text-muted-foreground">{windowId && windowName ? `${windowName} opens in its own window.` : "The desktop opens in its own window."}</p>+ <Button className="mt-4" onClick={() => void open()}>+ <AppWindowIcon /> Open window+ </Button>+ </>+ ) : (+ <p data-preview-text className="text-[13px] text-muted-foreground">+ {previewText}+ </p>+ )}+ </>+ )}+ </div>+ )}+ {slot?.phase === "live" && slot.focused ? (+ // While the desktop has the keyboard: how to give it back, over the+ // video's bottom edge. The host cuts the video out under it+ // (`data-video-hole`), so no strip under the stream is needed.+ <div+ data-video-focus="space"+ data-video-hole=""+ className="glass absolute bottom-2 left-1/2 flex max-w-[calc(100%-1rem)] -translate-x-1/2 items-center gap-2 rounded-lg py-1 pr-1 pl-3 text-xs text-muted-foreground shadow-float"+ ><p className="min-w-0 truncate">- {slot.phase !== "live" ? null : slot.focused ? (+ {isMacPlatform() ? (<>- {isMacPlatform() ? (- <>- Keys go to this Space. Press and release <Kbd>⌃⌥</Kbd> to stop.- </>- ) : (- <>- Keys go to this Space. Press <Kbd>Ctrl+Shift+F12</Kbd> to stop.- </>- )}+ Keys go to this Space. Press and release <Kbd>⌃⌥</Kbd> to stop.</>) : (- "Click the desktop to control it."+ <>+ Keys go to this Space. Press <Kbd>Ctrl+Shift+F12</Kbd> to stop.+ </>)}</p>- <div className="flex shrink-0 items-center gap-1">- {slot.phase === "live" && slot.focused ? (- <Button variant="ghost" size="sm" onClick={() => slot.setFocus(false)}>- Stop controlling- </Button>- ) : null}- {slot.phase !== "failed" ? (- <Button variant="ghost" size="sm" onClick={() => void open()}>- <AppWindowIcon /> Open in window- </Button>- ) : null}- </div>+ <Button variant="ghost" size="sm" onClick={() => slot.setFocus(false)}>+ Stop controlling+ </Button></div>) : null}- </>+ </div>);}diff --git a/apps/cua-spaces-web/src/components/space-thread/call-split.test.tsx b/apps/cua-spaces-web/src/components/space-thread/call-split.test.tsxnew file mode 100644index 0000000000..c87e04e28a--- /dev/null+++ b/apps/cua-spaces-web/src/components/space-thread/call-split.test.tsx@@ -0,0 +1,56 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { CallSplit, DEFAULT_SPLIT, DIVIDER_HIT_PX } from "./call-split";++class FakeResizeObserver {+ observe() {}+ disconnect() {}+}++beforeEach(() => {+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);+ localStorage.clear();+ HTMLElement.prototype.setPointerCapture = () => {};+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("<CallSplit>", () => {+ // The owner asked for an easier grab: a taller hit area, the same small bar.+ it("takes the drag on a row taller than its bar, with the row-resize cursor", () => {+ const { container } = render(<CallSplit stage={<div />} below={<div />} />);+ const divider = container.querySelector<HTMLElement>("[data-call-divider]")!;+ expect(DIVIDER_HIT_PX).toBeGreaterThanOrEqual(16);+ expect(divider.className).toContain(`h-${DIVIDER_HIT_PX / 4}`);+ expect(divider.className).toContain("cursor-row-resize");+ const bar = divider.querySelector("[data-call-divider-bar]")!;+ // The bar stays quiet: 4 px tall, a hover and a drag state.+ expect(bar.className).toContain("h-1");+ expect(bar.className).toContain("group-hover:");+ });++ it("follows a drag and remembers the split", () => {+ const { container } = render(<CallSplit stage={<div />} below={<div />} />);+ const root = container.querySelector<HTMLElement>("[data-call-split]")!;+ root.getBoundingClientRect = () => ({ x: 0, y: 0, top: 0, left: 0, width: 800, height: 1000, right: 800, bottom: 1000, toJSON: () => ({}) }) as DOMRect;+ const divider = container.querySelector<HTMLElement>("[data-call-divider]")!;+ expect(root.dataset.callSplit).toBe(DEFAULT_SPLIT.toFixed(2));+ fireEvent.pointerDown(divider, { button: 0, pointerId: 1, clientY: 520 });+ const bar = divider.querySelector("[data-call-divider-bar]")!;+ expect(bar.className).toContain("bg-ring");+ fireEvent.pointerMove(divider, { pointerId: 1, clientY: 700 });+ fireEvent.pointerUp(divider, { pointerId: 1, clientY: 700 });+ expect(root.dataset.callSplit).toBe("0.70");+ expect(localStorage.getItem("cua-spaces:call-split")).toBe("0.7");+ cleanup();+ const again = render(<CallSplit stage={<div />} below={<div />} />);+ expect(again.container.querySelector<HTMLElement>("[data-call-split]")!.dataset.callSplit).toBe("0.70");+ });+});diff --git a/apps/cua-spaces-web/src/components/space-thread/call-split.tsx b/apps/cua-spaces-web/src/components/space-thread/call-split.tsxindex a596eda9c8..78acf08dab 100644--- a/apps/cua-spaces-web/src/components/space-thread/call-split.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/call-split.tsx@@ -11,6 +11,8 @@ export const DEFAULT_SPLIT = 0.52;const MIN_STAGE = 160;const MIN_BELOW = 200;const KEY = "cua-spaces:call-split";+/** The divider's grab area (px, its `h-5`): taller than the bar, so it is easy to hit. */+export const DIVIDER_HIT_PX = 20;function savedSplit(): number {try {@@ -102,9 +104,16 @@ export function CallSplit({ stage, below, className }: { stage: ReactNode; belowonPointerCancel={onPointerUp}onDoubleClick={() => set(DEFAULT_SPLIT)}onKeyDown={onKeyDown}- className="group flex h-3 shrink-0 cursor-row-resize touch-none items-center justify-center outline-none"+ className="group flex h-5 shrink-0 cursor-row-resize touch-none items-center justify-center outline-none">- <span className={cn("h-1 w-10 rounded-full bg-border transition-colors group-hover:bg-muted-foreground/40 group-focus-visible:bg-ring", dragging && "bg-ring")} />+ {/* The bar stays small and quiet; the whole row (DIVIDER_HIT_PX) takes the drag. */}+ <span+ data-call-divider-bar=""+ className={cn(+ "h-1 w-10 rounded-full bg-border transition-[width,background-color] duration-150 group-hover:w-14 group-hover:bg-muted-foreground/40 group-focus-visible:bg-ring",+ dragging && "w-14 bg-ring group-hover:bg-ring",+ )}+ /></div><div className="flex min-h-0 flex-1 flex-col">{below}</div></div>diff --git a/apps/cua-spaces-web/src/components/video/use-video-slot.ts b/apps/cua-spaces-web/src/components/video/use-video-slot.tsindex e6968cf8c0..fd702aa631 100644--- a/apps/cua-spaces-web/src/components/video/use-video-slot.ts+++ b/apps/cua-spaces-web/src/components/video/use-video-slot.ts@@ -81,6 +81,10 @@ export function useVideoSlot(return () => {stop();setId(null);+ // The slot's last word dies with it: a slot that comes back (picture in+ // picture closed, Try again) starts at connecting, never flashing the+ // old one's failure or live state.+ setStatus(CONNECTING);};}, [ref, on, slots, spaceId, tier, interactive, radius, inset, os, windowId, epoch, attempt]);diff --git a/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx b/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsxindex 8b08f3f9dd..bb9a037159 100644--- a/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx+++ b/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx@@ -340,7 +340,7 @@ describe("<StreamSurface> in the Electron shell", () => {act(() => sessions[0]!.options.onFrame?.(1280, 800));await waitFor(() => expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy());expect(container.querySelector('[data-stream-surface="local:a"] canvas[data-webcodecs="full"]')).toBeTruthy();- expect(getByText("Click the desktop to control it.")).toBeTruthy();+ expect(container.querySelector("[data-video-focus]")).toBeNull();// A click gives it the keyboard; the line says how to give it back, in this platform's keys.vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");diff --git a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx b/apps/cua-spaces-web/src/lib/stream-surface.test.tsxindex d85a497574..b4ecdda631 100644--- a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx+++ b/apps/cua-spaces-web/src/lib/stream-surface.test.tsx@@ -12,7 +12,7 @@ import { ToastProvider } from "@/components/ui/toast";import { canStreamTile } from "@/components/video/tile-video";import { resetVideoSlotLoader } from "@/components/video/use-video-slot";import { nativeVideoHandler, type StreamSurfaceMessage, type SurfaceState } from "@/lib/stream-surface";-import { intersect, isOccluded, resetVideoSlots, roundRect, sameSurface, visiblePart, VideoSlotReporter, type SlotStatus } from "@/lib/video-slots";+import { intersect, isOccluded, resetVideoSlots, roundRect, sameSurface, videoHoles, visiblePart, VideoSlotReporter, type SlotStatus } from "@/lib/video-slots";type Win = typeof window & { webkit?: unknown };@@ -57,6 +57,9 @@ afterEach(() => {vi.unstubAllGlobals();vi.restoreAllMocks();resetVideoSlots();+ // jsdom has neither: tests stub them per case.+ delete (document as { elementsFromPoint?: unknown }).elementsFromPoint;+ delete (document as { elementFromPoint?: unknown }).elementFromPoint;document.body.innerHTML = "";delete (document as { elementFromPoint?: unknown }).elementFromPoint;});@@ -103,7 +106,7 @@ describe("stream surface helpers", () => {expect(visiblePart(slot, { x: 0, y: 650, width: 100, height: 100 })).toEqual({ x: 0, y: 650, width: 100, height: 50 });});- it("calls a slot occluded when a dialog, menu or toast overlaps it", () => {+ it("calls a slot occluded when a dialog overlaps it, and cuts holes for menus, popovers and toasts", () => {const slot = document.createElement("div");const dialog = document.createElement("div");dialog.setAttribute("role", "dialog");@@ -113,13 +116,58 @@ describe("stream surface helpers", () => {expect(isOccluded(slot, clip)).toBe(false);box(dialog, { x: 350, y: 250, width: 100, height: 100 });expect(isOccluded(slot, clip)).toBe(true);- // A toast (marked `data-video-occluder`) too.- dialog.removeAttribute("role");+ expect(videoHoles(slot, clip)).toEqual([]);+ // A menu (or a toast, marked `data-video-occluder`) over it: a hole, clipped to the slot; the video stays.+ for (const mark of [["role", "menu"], ["data-video-occluder", ""]] as const) {+ dialog.removeAttribute("role");+ dialog.removeAttribute("data-video-occluder");+ dialog.setAttribute(mark[0], mark[1]);+ expect(isOccluded(slot, clip)).toBe(false);+ expect(videoHoles(slot, clip)).toEqual([{ x: 350, y: 250, width: 50, height: 50 }]);+ }+ });++ // Regression: the Space header's "⋯" menu turned the desktop black. Base+ // UI puts a transparent full-page click catcher (`data-base-ui-inert`)+ // under an open menu; it hit every sample point, so the whole video hid.+ it("looks through transparent click catchers: an open menu never blacks out the video", () => {+ const slot = document.createElement("div");+ const inner = document.createElement("span");+ slot.append(inner);+ const catcher = document.createElement("div");+ catcher.setAttribute("data-base-ui-inert", "");+ const menu = document.createElement("div");+ menu.setAttribute("role", "menu");+ document.body.append(slot, catcher, menu);+ box(menu, { x: 300, y: -40, width: 160, height: 60 });+ const clip = { x: 0, y: 0, width: 400, height: 300 };+ document.elementsFromPoint = (x, y) => (x > 300 && y < 20 ? [menu, catcher, inner, slot] : [catcher, inner, slot]);+ expect(isOccluded(slot, clip)).toBe(false);+ expect(videoHoles(slot, clip)).toEqual([{ x: 300, y: 0, width: 100, height: 20 }]);+ // The modal menu made the page `inert`: hit-testing skips the slot and+ // reaches its ancestors, which paint nothing over it.+ document.elementsFromPoint = () => [catcher, document.body, document.documentElement];expect(isOccluded(slot, clip)).toBe(false);- dialog.setAttribute("data-video-occluder", "");+ // Something that paints over it still hides it.+ const sheet = document.createElement("div");+ document.body.append(sheet);+ document.elementsFromPoint = () => [sheet, catcher, inner, slot];expect(isOccluded(slot, clip)).toBe(true);});+ it("cuts a hole for the viewer's own key bar, but not for other UI inside the slot", () => {+ const slot = document.createElement("div");+ const bar = document.createElement("div");+ bar.setAttribute("data-video-hole", "");+ const tip = document.createElement("div");+ tip.setAttribute("role", "tooltip");+ slot.append(bar, tip);+ document.body.append(slot);+ box(bar, { x: 100, y: 260, width: 200, height: 30 });+ box(tip, { x: 10, y: 10, width: 50, height: 20 });+ expect(videoHoles(slot, { x: 0, y: 0, width: 400, height: 300 })).toEqual([{ x: 100, y: 260, width: 200, height: 30 }]);+ });+it("calls a slot occluded when something else is on top of it (a backdrop)", () => {const slot = document.createElement("div");const inner = document.createElement("span");@@ -155,6 +203,7 @@ describe("VideoSlotReporter", () => {const viewer = document.createElement("div");document.body.append(tile, viewer);document.elementFromPoint = () => null;+ document.elementsFromPoint = () => [];box(tile, { x: 10, y: 20, width: 232, height: 145 });box(viewer, { x: 10, y: 200, width: 640, height: 400 });const tileStatus: SlotStatus[] = [];@@ -177,6 +226,7 @@ describe("VideoSlotReporter", () => {clip: { x: 11, y: 201, width: 638, height: 398 },radius: 11,occluded: false,+ holes: [],visible: true,},]);@@ -253,9 +303,15 @@ describe("<StreamSurface> native video", () => {act(() => hostEvent("video.surface", { surfaceId: first.surfaceId, state: "live" }));expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy();- expect(getByText("Click the desktop to control it.")).toBeTruthy();+ // Nothing under the stream: no hint line, no Open in window (the header's PiP button replaces both).+ expect(queryByText("Click the desktop to control it.")).toBeNull();+ expect(queryByText("Open in window")).toBeNull();+ expect(container.querySelector("[data-video-focus]")).toBeNull();+ // With the keyboard: a bar over the video's bottom edge (a hole in the video) says how to stop.act(() => hostEvent("video.focus", { surfaceId: first.surfaceId }));- expect(container.querySelector('[data-video-focus="space"]')?.textContent).toContain("Press and release ⌃⌥ to stop.");+ const bar = container.querySelector('[data-stream-surface="sp-1"] [data-video-focus="space"]');+ expect(bar?.textContent).toContain("Press and release ⌃⌥ to stop.");+ expect(bar?.hasAttribute("data-video-hole")).toBe(true);act(() => getByText("Stop controlling").click());expect(posted.at(-1)).toEqual({ type: "focus", surfaceId: null });@@ -263,6 +319,42 @@ describe("<StreamSurface> native video", () => {expect(posted.at(-1)).toEqual({ type: "surfaces", update: [], remove: [first.surfaceId] });});+ // Regression: closing picture in picture showed "Could not connect to the+ // desktop" before the inline desktop came back. The slot that comes back+ // must start at connecting: no failure or timeout left from the slot (or+ // the wait) before it.+ it("comes back from picture in picture without the old slot's failure or timeout", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ hostDrawsVideo();+ const tree = (children?: React.ReactNode) => (+ <BridgeProvider adapter={createDemoAdapter({ latencyMs: 1 })} core={noCore}>+ <StreamSurface spaceId="sp-1" os="linux" canStream previewText="Not reachable">+ {children}+ </StreamSurface>+ </BridgeProvider>+ );+ const { container, rerender, queryByText } = render(tree());+ await waitFor(() => expect(updates()).not.toHaveLength(0));+ // The first picture was slow: the wait ran out once.+ act(() => void vi.advanceTimersByTime(CONNECT_TIMEOUT_MS));+ expect(container.querySelector('[data-stream-state="failed"]')).toBeTruthy();+ const first = updates()[0]!;+ act(() => hostEvent("video.surface", { surfaceId: first.surfaceId, state: "live" }));+ expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy();+ // Popped out: the page's "Playing in a floating window" replaces the stream.+ rerender(tree(<p>Playing in a floating window</p>));+ expect(posted.some((m) => m.type === "surfaces" && m.remove.includes(first.surfaceId))).toBe(true);+ // Popped back in: connecting at once, never the old failure.+ rerender(tree());+ expect(container.querySelector('[data-stream-state="failed"]')).toBeNull();+ expect(queryByText("Could not connect to the desktop")).toBeNull();+ await waitFor(() => expect(updates().some((u) => u.surfaceId !== first.surfaceId)).toBe(true));+ const back = updates().at(-1)!;+ expect(container.querySelector('[data-stream-state="connecting"]')).toBeTruthy();+ act(() => hostEvent("video.surface", { surfaceId: back.surfaceId, state: "live" }));+ expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy();+ });+it("says it could not connect, with Try again (which opens it again) and Open window", async () => {hostDrawsVideo();const { container, getByText } = mount();diff --git a/apps/cua-spaces-web/src/lib/stream-surface.ts b/apps/cua-spaces-web/src/lib/stream-surface.tsindex cb7b6ef265..a8d7feb218 100644--- a/apps/cua-spaces-web/src/lib/stream-surface.ts+++ b/apps/cua-spaces-web/src/lib/stream-surface.ts@@ -8,8 +8,9 @@* On macOS the SwiftUI host draws live Space video itself, as native views* over the web view. The page only says where, and whether the slot can be* seen: each mounted slot (a Space tile, the Space viewer) reports its rect,- * the part of it its scroll containers leave visible (`clip`), and whether- * page UI covers it (`occluded`: a dialog, a menu, a toast), all in CSS px+ * the part of it its scroll containers leave visible (`clip`), whether+ * page UI covers it (`occluded`: a dialog), and where floating UI sits over+ * it (`holes`: a menu, a popover, a tooltip, a toast), all in CSS px* relative to the web view's viewport, on the `cuaVideo` script message* handler. The host registers that handler unless native video is turned* off (`WebUINativeVideo` NO), so the handler's presence is the flag. No handler: the@@ -54,8 +55,11 @@ export interface SurfaceState {/** The part of `rect` its scroll containers and the viewport leave visible; null when none is. */clip: SurfaceRect | null;radius: number;- /** Page UI (a dialog, a menu, a toast) covers part of the slot: the host hides the video. */+ /** A dialog (or anything else on top, but floating UI) covers part of the slot: the host hides the video. */occluded: boolean;+ /** Floating page UI over the slot (a menu, a popover, a tooltip, a toast), in the same coordinates,+ * inside `clip`: the host cuts the video out there and keeps the rest playing. */+ holes?: SurfaceRect[];/** On screen at all: the page is visible, the slot is laid out and not clipped away. */visible: boolean;}diff --git a/apps/cua-spaces-web/src/lib/video-slots.ts b/apps/cua-spaces-web/src/lib/video-slots.tsindex 3e03afc919..bfa24bdb94 100644--- a/apps/cua-spaces-web/src/lib/video-slots.ts+++ b/apps/cua-spaces-web/src/lib/video-slots.ts@@ -29,6 +29,10 @@ function sameRect(a: SurfaceRect | null, b: SurfaceRect | null): boolean {return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;}+function sameRects(a: readonly SurfaceRect[], b: readonly SurfaceRect[]): boolean {+ return a.length === b.length && a.every((r, i) => sameRect(r, b[i] ?? null));+}+/** Whether a surface report changes anything the host draws. */export function sameSurface(a: SurfaceState | null, b: SurfaceState): boolean {return (@@ -40,21 +44,35 @@ export function sameSurface(a: SurfaceState | null, b: SurfaceState): boolean {a.occluded === b.occluded &&a.radius === b.radius &&sameRect(a.rect, b.rect) &&- sameRect(a.clip, b.clip)+ sameRect(a.clip, b.clip) &&+ sameRects(a.holes ?? [], b.holes ?? []));}-/** Page UI that covers video when it overlaps a slot (portals: dialogs, menus, popovers, toasts). */-export const OCCLUDER_SELECTOR = [+/** Page UI that hides the video entirely when it overlaps a slot: a dialog+ * takes the keyboard and dims the page, so the video under it goes. */+export const OCCLUDER_SELECTOR = ['[role="dialog"]', '[role="alertdialog"]'].join(",");++/**+ * Small page UI that floats over a slot (menus, popovers, tooltips, toasts,+ * the viewer's own key bar): the host cuts the video out under each one+ * (`holes`) and the rest keeps playing. Hiding the whole video for a menu+ * turned the desktop black while the menu was open.+ */+export const HOLE_SELECTOR = ["[data-video-occluder]",- '[role="dialog"]',- '[role="alertdialog"]',+ "[data-video-hole]",'[role="menu"]','[role="listbox"]','[role="tooltip"]',"[data-toast]",].join(",");+/** Transparent layers that only catch outside clicks (Base UI's+ * `InternalBackdrop` under an open menu or popover): they paint nothing, so+ * they never cover video. */+export const INERT_SELECTOR = "[data-base-ui-inert]";+/*** Reports every mounted video slot to the host in one message per frame* (see `stream-surface.ts` for the protocol).@@ -215,6 +233,7 @@ export class VideoSlotReporter {clip,radius: Math.max(0, slot.radius - inset),occluded: shown && clip ? isOccluded(slot.el, clip, this.win.document, slot.radius) : false,+ holes: shown && clip ? videoHoles(slot.el, clip, this.win.document).map(roundRect) : [],visible: shown,};}@@ -309,9 +328,12 @@ export function visiblePart(el: Element, rect: SurfaceRect, win: Window = window}/**- * Whether page UI covers any of `clip`: an open dialog, menu, popover or- * toast overlapping it, or anything else on top at a few sample points (a- * dialog's backdrop, a sticky bar).+ * Whether page UI covers `clip` so the video must go: an open dialog+ * overlapping it, or anything else on top at a few sample points (a+ * dialog's backdrop, a sticky bar). Floating UI that gets a hole instead+ * (`HOLE_SELECTOR`), click-catching layers that paint nothing+ * (`INERT_SELECTOR`) and the slot's own ancestors (hit when an open modal+ * menu made the page `inert`) don't count.*/export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = document, radius = 0): boolean {for (const o of doc.querySelectorAll(OCCLUDER_SELECTOR)) {@@ -319,7 +341,7 @@ export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = documconst r = o.getBoundingClientRect();if (r.width > 0 && r.height > 0 && intersect(clip, { x: r.x, y: r.y, width: r.width, height: r.height })) return true;}- if (typeof doc.elementFromPoint !== "function") return false;+ if (typeof doc.elementsFromPoint !== "function" && typeof doc.elementFromPoint !== "function") return false;// Inside the rounded corners, which hit-test as the element's parent.const dx = Math.min(clip.width / 2, Math.ceil(radius * 0.3) + 2);const dy = Math.min(clip.height / 2, Math.ceil(radius * 0.3) + 2);@@ -327,13 +349,46 @@ export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = documconst ys = [clip.y + dy, clip.y + clip.height / 2, clip.y + clip.height - dy];for (const x of xs) {for (const y of ys) {- const hit = doc.elementFromPoint(x, y);- if (hit && hit !== el && !el.contains(hit)) return true;+ const hit = topmostPainted(doc, x, y);+ // An ancestor of the slot can't paint over it: it is what hit-testing+ // reaches when the slot itself takes no hits (a modal menu makes the+ // rest of the page `inert`).+ if (hit && !hit.contains(el) && !el.contains(hit) && !hit.closest(HOLE_SELECTOR)) return true;}}return false;}+/** The topmost element at a point that paints: inert click catchers are looked through. */+function topmostPainted(doc: Document, x: number, y: number): Element | null {+ const all = typeof doc.elementsFromPoint === "function" ? doc.elementsFromPoint(x, y) : [doc.elementFromPoint(x, y)];+ for (const hit of all) {+ if (!hit) continue;+ if (hit.closest(INERT_SELECTOR)) continue;+ return hit;+ }+ return null;+}++/**+ * The floating UI over `clip` (menus, popovers, tooltips, toasts, the+ * viewer's key bar), each clipped to it: the host draws no video there.+ */+export function videoHoles(el: Element, clip: SurfaceRect, doc: Document = document): SurfaceRect[] {+ const holes: SurfaceRect[] = [];+ for (const o of doc.querySelectorAll(HOLE_SELECTOR)) {+ // Floating UI inside the slot counts only when it asks (`data-video-hole`).+ if (o.contains(el) || (el.contains(o) && !o.hasAttribute("data-video-hole"))) continue;+ // One hole for a nested pair (a menu inside a marked popup).+ if (o.parentElement?.closest(HOLE_SELECTOR)) continue;+ const r = o.getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) continue;+ const hole = intersect(clip, { x: r.x, y: r.y, width: r.width, height: r.height });+ if (hole) holes.push(hole);+ }+ return holes;+}+let shared: VideoSlotReporter | null | undefined;/** The page's reporter, or null when the host draws no native video. */