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
feat(spaces): thread view with a floating mini-player on the Space page (CUA-2480) (#6059)
ddupont6cd675e8ce2c
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swiftindex 295dfa1771..9c5bc71bef 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift@@ -144,7 +144,9 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {case let .surfaces(update, remove):CATransaction.begin()CATransaction.setDisableActions(true)- for id in remove { self.remove(id) }+ // A viewer the page moves (the Space page's call and thread layouts)+ // comes back to the same live session (`slotGrace`).+ for id in remove { self.remove(id, grace: true) }for u in update { place(u) }CATransaction.commit()case let .focus(id):@@ -157,6 +159,12 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {/// Tears every surface and session down (window closed, page replaced).func removeAll() {for id in Array(surfaces.keys) { remove(id) }+ // A viewer still in its `slotGrace` has no page to come back to:+ // stop it now (a picture-in-picture hold keeps its own).+ for (key, stream) in streams where stream.holds == 0 {+ stream.users = 1+ letGo(stream, key: key)+ }}// MARK: - Surfaces@@ -321,7 +329,7 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {surface.view.isHidden = surface.layout.hidden || surface.phase != .live}- private func remove(_ surfaceId: String) {+ private func remove(_ surfaceId: String, grace: Bool = false) {guard let surface = surfaces.removeValue(forKey: surfaceId) else { return }if focusedId == surfaceId { focus(nil) }surface.view.input.keyboardReturn.forget()@@ -335,9 +343,22 @@ 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)+ guard grace, surface.key.tier == .full, stream.session != nil, slotGrace > .zero else {+ return letGo(stream, key: surface.key)+ }+ let key = surface.key+ Task { @MainActor [weak self, weak stream] in+ try? await Task.sleep(for: self?.slotGrace ?? .zero)+ guard let self, let stream else { return }+ self.letGo(stream, key: key)+ }}+ /// How long a viewer's session outlives its slot: the page that moves+ /// the viewer (call view to thread view and back) mounts its new slot+ /// in that time, and it binds to the same live session.+ var slotGrace: Duration = .milliseconds(1500)+/// One user fewer; the last one stops the session.private func letGo(_ stream: Stream, key: StreamKey) {stream.users -= 1diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swiftindex 129f9546f9..1e4298ef95 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift@@ -486,6 +486,8 @@ struct WebUIVideoSurfacesTests {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) }+ // Only the panel's hold keeps the session here (no slot grace).+ s.slotGrace = .zeros.handle(message([entry("v1", space: "a")]))await settle { host.phases("v1").contains("live") }let first = try #require(s.surfaces["v1"])@@ -541,6 +543,67 @@ struct WebUIVideoSurfacesTests {#expect(s.stats().isEmpty)}+ // MARK: - Moving the viewer (call view and thread view)++ /// The Space page moves its viewer between the call view's stage and+ /// thread view's mini-player: the old slot goes and a new one comes.+ /// The new slot binds to the same live session (no second open, no+ /// "Connecting…"), as long as it comes within `slotGrace`.+ @Test func aViewerMovedToANewSlotKeepsItsLiveSession() 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("call", space: "a")]))+ await settle { host.phases("call").contains("live") }+ let callSlot = try #require(s.surfaces["call"])+ let session = try #require(s.sessionFor(callSlot))++ // One message: the stage's slot goes, the mini-player's comes.+ var mini = entry("mini", space: "a", interactive: false)+ mini["rect"] = ["x": 500, "y": 400, "width": 320, "height": 200]+ s.handle(message([mini], remove: ["call"]))+ await settle(tries: 5) { !host.phases("mini").isEmpty }+ #expect(host.phases("mini") == ["live"])+ let miniSlot = try #require(s.surfaces["mini"])+ #expect(s.sessionFor(miniSlot) === session)+ // And back again, after the grace has passed for the first move.+ try? await Task.sleep(for: s.slotGrace + .milliseconds(200))+ s.handle(message([entry("call2", space: "a")], remove: ["mini"]))+ await settle(tries: 5) { !host.phases("call2").isEmpty }+ #expect(host.phases("call2") == ["live"])+ let back = try #require(s.surfaces["call2"])+ #expect(s.sessionFor(back) === session)+ #expect(host.opened.count == 1)+ #expect(session.status == .streaming)+ s.removeAll()+ }++ @Test func aViewerSlotThatDoesNotComeBackStopsItsSessionAfterTheGrace() 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.slotGrace = .milliseconds(150)+ s.handle(message([entry("v", space: "a")]))+ await settle { host.phases("v").contains("live") }+ let slot = try #require(s.surfaces["v"])+ let session = try #require(s.sessionFor(slot))+ s.handle(message([], remove: ["v"]))+ // Still there during the grace...+ #expect(s.stats().count == 1)+ // ...then gone, and the session stopped.+ await settle { s.stats().isEmpty }+ #expect(s.stats().isEmpty)+ await settle { session.status == .idle }+ #expect(session.status == .idle)+ // A page that goes away (removeAll) stops at once, and tiles never wait.+ s.handle(message([entry("t", space: "b", tier: "tile", interactive: false), entry("w", space: "c")]))+ await settle { host.opened.count == 3 }+ s.handle(message([], remove: ["t"]))+ #expect(s.stats().count == 1)+ s.removeAll()+ #expect(s.stats().isEmpty)+ }+// MARK: - Holes@Test func readsHolesAndMapsThemIntoTheClipContainer() throws {diff --git a/apps/cua-spaces-macos/docs/native-video.md b/apps/cua-spaces-macos/docs/native-video.mdindex ce19e157ba..52d3874a11 100644--- a/apps/cua-spaces-macos/docs/native-video.md+++ b/apps/cua-spaces-macos/docs/native-video.md@@ -80,7 +80,7 @@ CSS px become points through `pageZoom × magnification`. A web view that isn't**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.+**Lifecycle.** A page load (`didCommit`), the web content process ending, and the window closing all tear every surface and session down. A viewer slot the page removes keeps its session for `slotGrace` (1.5 s): the Space page moves its viewer between call view's stage and thread view's mini-player by removing one slot and adding another, and the new slot binds to the same live session, with no reconnect.### Input and keyboard focusdiff --git a/apps/cua-spaces-web/src/__tests__/thread-view-toggle.test.tsx b/apps/cua-spaces-web/src/__tests__/thread-view-toggle.test.tsxnew file mode 100644index 0000000000..e355e77641--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/thread-view-toggle.test.tsx@@ -0,0 +1,73 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// A Space's page in call view (the desktop leads) and thread view (the+// thread leads, the desktop in a floating mini-player): the hover-only+// toggle on the divider row, ⌘⇧T, the mini-player's expand arrows, and the+// view remembered per Space.++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";+import { mountApp, stubBrowserApis } from "./app-harness";++afterEach(cleanup);+stubBrowserApis();+beforeEach(() => localStorage.removeItem(`cua-spaces:layout:${DEMO_THREAD_SPACE}`));++const q = (s: string) => document.querySelector<HTMLElement>(s);+const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;++describe("call view and thread view", () => {+ it("toggles from the divider row, the mini-player and ⌘⇧T, and remembers the view per Space", async () => {+ await mountApp(path, { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(q("[data-call-layout]")).not.toBeNull());+ // Call view: the shrink button sits at the left of the divider's row, shown only on hover or focus.+ const toggle = await waitFor(() => {+ const t = q("[data-call-divider-row] [data-layout-toggle='thread']");+ expect(t).not.toBeNull();+ return t!;+ });+ expect(toggle.getAttribute("aria-label")).toBe("Thread view");+ const holder = q("[data-call-divider-leading]")!;+ expect(holder.className).toContain("opacity-0");+ expect(holder.className).toContain("group-hover/divider:opacity-100");+ expect(holder.className).toContain("focus-within:opacity-100");+ // Pressing it never starts a divider drag.+ fireEvent.pointerDown(holder, { button: 0, pointerId: 1 });+ expect(q("[data-call-divider-bar]")!.className.split(" ")).not.toContain("bg-ring");+ // Nothing in the header for it.+ expect(q("[data-call-header] [data-layout-toggle]")).toBeNull();++ act(() => toggle.click());+ await waitFor(() => expect(q("[data-thread-layout]")).not.toBeNull());+ expect(q("[data-call-divider]")).toBeNull();+ expect(q("[data-mini-player]")).not.toBeNull();+ // The player floats over the thread only: the composer is outside its area.+ const area = q("[data-mini-player-area]")!;+ const composer = q("[data-composer]")!;+ expect(area.parentElement!.contains(composer)).toBe(false);+ expect(localStorage.getItem(`cua-spaces:layout:${DEMO_THREAD_SPACE}`)).toBe("thread");+ // In its default bottom-right corner, the thread keeps the player's height clear at its end,+ // so the newest message sits above it.+ const player = q("[data-mini-player]")!;+ expect(player.dataset.miniPlayer).toBe("br");+ const end = q("[data-thread] > div")!;+ await waitFor(() => expect(parseFloat(end.style.paddingBottom)).toBe(parseFloat(player.style.height) + 12 + 16));++ // Its expand arrows go back.+ act(() => q("[data-mini-player-expand]")!.click());+ await waitFor(() => expect(q("[data-call-divider]")).not.toBeNull());+ expect(localStorage.getItem(`cua-spaces:layout:${DEMO_THREAD_SPACE}`)).toBe("call");++ // ⌘⇧T (Ctrl+Shift+T elsewhere) toggles.+ act(() => void window.dispatchEvent(new KeyboardEvent("keydown", { key: "T", metaKey: true, ctrlKey: true, shiftKey: true })));+ await waitFor(() => expect(q("[data-thread-layout]")).not.toBeNull());++ // Remembered: the page opens again in thread view.+ cleanup();+ await mountApp(path, { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(q("[data-thread-layout]")).not.toBeNull());+ });+});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 78acf08dab..477f1b914e 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@@ -43,7 +43,18 @@ export function clampSplit(fraction: number, height: number): number {* to snap back; arrow keys move it when it has focus. The split is* remembered on this device.*/-export function CallSplit({ stage, below, className }: { stage: ReactNode; below: ReactNode; className?: string }) {+export function CallSplit({+ stage,+ below,+ className,+ leading,+}: {+ stage: ReactNode;+ below: ReactNode;+ className?: string;+ /** On the divider's row, at its left edge: shown on the row's hover or keyboard focus only (Thread view). */+ leading?: ReactNode;+}) {const ref = useRef<HTMLDivElement | null>(null);const [height, setHeight] = useState(0);const [split, setSplit] = useState(savedSplit);@@ -89,31 +100,43 @@ export function CallSplit({ stage, below, className }: { stage: ReactNode; below<div data-call-stage="" className="relative min-h-0 shrink-0" style={{ height: `${fraction * 100}%` }}>{stage}</div>- <div- role="separator"- aria-orientation="horizontal"- aria-label="Resize the desktop and the thread"- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={Math.round(fraction * 100)}- tabIndex={0}- data-call-divider=""- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={onPointerUp}- onPointerCancel={onPointerUp}- onDoubleClick={() => set(DEFAULT_SPLIT)}- onKeyDown={onKeyDown}- className="group flex h-5 shrink-0 cursor-row-resize touch-none items-center justify-center outline-none"- >- {/* 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 data-call-divider-row="" className="group/divider relative shrink-0">+ {leading ? (+ // Its own control on the row: pressing it never starts a drag.+ <div+ data-call-divider-leading=""+ onPointerDown={(e) => e.stopPropagation()}+ className="absolute top-1/2 left-5 z-10 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/divider:opacity-100 focus-within:opacity-100"+ >+ {leading}+ </div>+ ) : null}+ <div+ role="separator"+ aria-orientation="horizontal"+ aria-label="Resize the desktop and the thread"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(fraction * 100)}+ tabIndex={0}+ data-call-divider=""+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ onDoubleClick={() => set(DEFAULT_SPLIT)}+ onKeyDown={onKeyDown}+ className="group flex h-5 shrink-0 cursor-row-resize touch-none items-center justify-center outline-none"+ >+ {/* 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><div className="flex min-h-0 flex-1 flex-col">{below}</div></div>diff --git a/apps/cua-spaces-web/src/components/space-thread/layout-mode.ts b/apps/cua-spaces-web/src/components/space-thread/layout-mode.tsnew file mode 100644index 0000000000..e2b58e9c47--- /dev/null+++ b/apps/cua-spaces-web/src/components/space-thread/layout-mode.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useCallback, useState } from "react";++/**+ * How a Space's page is laid out:+ * - `call`: the desktop is the main area, the thread under it (the call storyboard);+ * - `thread`: the thread is the main area and the desktop shrinks into a+ * floating mini-player (`MiniPlayer`).+ *+ * Remembered per Space on this device.+ */+export type SpaceLayout = "call" | "thread";++const key = (spaceId: string) => `cua-spaces:layout:${spaceId}`;++function read(k: string): string | null {+ try {+ return globalThis.localStorage?.getItem(k) ?? null;+ } catch {+ return null;+ }+}++function write(k: string, v: string) {+ try {+ globalThis.localStorage?.setItem(k, v);+ } catch {+ // Blocked storage: the choice just isn't remembered.+ }+}++export function savedLayout(spaceId: string): SpaceLayout {+ return read(key(spaceId)) === "thread" ? "thread" : "call";+}++/** The Space's layout and its setter (remembered per Space). */+export function useSpaceLayout(spaceId: string): [SpaceLayout, (next: SpaceLayout) => void] {+ const [state, setState] = useState<{ spaceId: string; layout: SpaceLayout }>(() => ({ spaceId, layout: savedLayout(spaceId) }));+ const layout = state.spaceId === spaceId ? state.layout : savedLayout(spaceId);+ const set = useCallback(+ (next: SpaceLayout) => {+ write(key(spaceId), next);+ setState({ spaceId, layout: next });+ },+ [spaceId],+ );+ return [layout, set];+}diff --git a/apps/cua-spaces-web/src/components/space-thread/mini-player.test.tsx b/apps/cua-spaces-web/src/components/space-thread/mini-player.test.tsxnew file mode 100644index 0000000000..c38eabcd42--- /dev/null+++ b/apps/cua-spaces-web/src/components/space-thread/mini-player.test.tsx@@ -0,0 +1,127 @@+// 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 { clampWidth, DEFAULT_WIDTH, MiniPlayer, MIN_WIDTH, nearestCorner } from "./mini-player";+import { savedLayout } from "./layout-mode";++class FakeResizeObserver {+ observe() {}+ disconnect() {}+}++const AREA = { w: 900, h: 600 };++beforeEach(() => {+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);+ localStorage.clear();+ HTMLElement.prototype.setPointerCapture = () => {};+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(AREA.w);+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(AREA.h);+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++const mount = (props: { onExpand?: () => void; onReserve?: (px: number) => void } = {}) =>+ render(+ <MiniPlayer spaceId="local:a" label="Desktop" aspect={16 / 10} onExpand={props.onExpand ?? (() => {})} onReserve={props.onReserve}>+ <div data-stage="" />+ </MiniPlayer>,+ );++const player = (c: HTMLElement) => c.querySelector<HTMLElement>("[data-mini-player]")!;+const surface = (c: HTMLElement) => player(c).querySelector<HTMLElement>('[role="button"]')!;++describe("thread view's mini-player", () => {+ it("snaps to the nearest corner and keeps its width inside the thread", () => {+ expect(nearestCorner(10, 10, 900, 600)).toBe("tl");+ expect(nearestCorner(890, 10, 900, 600)).toBe("tr");+ expect(nearestCorner(10, 590, 900, 600)).toBe("bl");+ expect(nearestCorner(890, 590, 900, 600)).toBe("br");+ expect(clampWidth(5000, 900, 600, 1.6)).toBeLessThanOrEqual(900 - 24);+ expect(clampWidth(10, 900, 600, 1.6)).toBe(MIN_WIDTH);+ // Never taller than the thread it floats in.+ expect(clampWidth(640, 900, 300, 1.6) / 1.6).toBeLessThanOrEqual(300);+ });++ it("starts in the bottom-right corner, then follows a drag to the corner it is dropped nearest", () => {+ const { container } = mount();+ expect(player(container).dataset.miniPlayer).toBe("br");+ expect(player(container).style.width).toBe(`${DEFAULT_WIDTH}px`);+ const el = surface(container);+ fireEvent.pointerDown(el, { button: 0, pointerId: 1, clientX: 800, clientY: 500 });+ fireEvent.pointerMove(el, { pointerId: 1, clientX: 200, clientY: 120 });+ fireEvent.pointerUp(el, { pointerId: 1, clientX: 200, clientY: 120 });+ expect(player(container).dataset.miniPlayer).toBe("tl");+ // Remembered per Space: a new mount comes back there.+ cleanup();+ expect(player(mount().container).dataset.miniPlayer).toBe("tl");+ expect(JSON.parse(localStorage.getItem("cua-spaces:mini-player:local:a")!)).toMatchObject({ corner: "tl" });+ });++ it("grows from its grip and remembers its size", () => {+ const { container } = mount();+ const grip = container.querySelector<HTMLElement>("[data-mini-player-grip]")!;+ // Bottom-right: the grip is on the bar's left end; dragging it left (toward the middle) grows the player.+ fireEvent.pointerDown(grip, { button: 0, pointerId: 2, clientX: 600, clientY: 590 });+ fireEvent.pointerMove(grip, { pointerId: 2, clientX: 520, clientY: 590 });+ fireEvent.pointerMove(grip, { pointerId: 2, clientX: 500, clientY: 590 });+ fireEvent.pointerUp(grip, { pointerId: 2, clientX: 500, clientY: 590 });+ expect(player(container).style.width).toBe(`${DEFAULT_WIDTH + 100}px`);+ cleanup();+ expect(player(mount().container).style.width).toBe(`${DEFAULT_WIDTH + 100}px`);+ });++ it("goes back to the call view on a click (or its expand arrows), not on a drag", () => {+ const onExpand = vi.fn();+ const { container } = mount({ onExpand });+ const el = surface(container);+ fireEvent.pointerDown(el, { button: 0, pointerId: 1, clientX: 700, clientY: 500 });+ fireEvent.pointerUp(el, { pointerId: 1, clientX: 701, clientY: 500 });+ expect(onExpand).toHaveBeenCalledTimes(1);+ fireEvent.pointerDown(el, { button: 0, pointerId: 1, clientX: 700, clientY: 500 });+ fireEvent.pointerMove(el, { pointerId: 1, clientX: 600, clientY: 400 });+ fireEvent.pointerUp(el, { pointerId: 1, clientX: 600, clientY: 400 });+ expect(onExpand).toHaveBeenCalledTimes(1);+ fireEvent.click(container.querySelector("[data-mini-player-expand]")!);+ expect(onExpand).toHaveBeenCalledTimes(2);+ // Keyboard and accessibility clicks expand too.+ fireEvent.keyDown(el, { key: "Enter" });+ expect(onExpand).toHaveBeenCalledTimes(3);+ });++ it("centres its title on the bar", () => {+ const { container } = mount();+ const label = container.querySelector<HTMLElement>("[data-mini-player-label]")!;+ expect(label.textContent).toBe("Desktop");+ expect(label.className).toContain("text-center");+ expect(label.className).toContain("absolute");+ });++ // Never over the newest message: at the bottom it asks the thread to keep its own height clear.+ it("asks the thread to keep room for it at the bottom, and none at the top", () => {+ const onReserve = vi.fn();+ const { container } = mount({ onReserve });+ const height = parseFloat(player(container).style.height);+ expect(onReserve).toHaveBeenLastCalledWith(height + 12);+ const el = surface(container);+ fireEvent.pointerDown(el, { button: 0, pointerId: 1, clientX: 800, clientY: 500 });+ fireEvent.pointerMove(el, { pointerId: 1, clientX: 800, clientY: 100 });+ fireEvent.pointerUp(el, { pointerId: 1, clientX: 800, clientY: 100 });+ expect(player(container).dataset.miniPlayer).toBe("tr");+ expect(onReserve).toHaveBeenLastCalledWith(0);+ });++ it("remembers the view per Space", () => {+ expect(savedLayout("local:a")).toBe("call");+ localStorage.setItem("cua-spaces:layout:local:a", "thread");+ expect(savedLayout("local:a")).toBe("thread");+ expect(savedLayout("local:b")).toBe("call");+ });+});diff --git a/apps/cua-spaces-web/src/components/space-thread/mini-player.tsx b/apps/cua-spaces-web/src/components/space-thread/mini-player.tsxnew file mode 100644index 0000000000..d68925a693--- /dev/null+++ b/apps/cua-spaces-web/src/components/space-thread/mini-player.tsx@@ -0,0 +1,217 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { Maximize2Icon } from "lucide-react";+import { useLayoutEffect, useRef, useState, type PointerEvent, type ReactNode } from "react";++import { Tooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";++export type Corner = "tl" | "tr" | "bl" | "br";++/** Gap to the thread's edges (px). */+const MARGIN = 12;+/** The bar under the picture (px, its `h-7`). */+const BAR = 28;+export const MIN_WIDTH = 220;+const MAX_WIDTH = 640;+export const DEFAULT_WIDTH = 320;+/** Movement (px) under which a press is a click (expand), not a drag. */+const CLICK_SLOP = 4;++interface Placement {+ corner: Corner;+ width: number;+}++const key = (spaceId: string) => `cua-spaces:mini-player:${spaceId}`;++function saved(spaceId: string): Placement {+ try {+ const v = JSON.parse(globalThis.localStorage?.getItem(key(spaceId)) ?? "null") as Partial<Placement> | null;+ const corner = v?.corner && ["tl", "tr", "bl", "br"].includes(v.corner) ? v.corner : "br";+ const width = typeof v?.width === "number" && v.width >= MIN_WIDTH ? v.width : DEFAULT_WIDTH;+ return { corner, width };+ } catch {+ return { corner: "br", width: DEFAULT_WIDTH };+ }+}++function save(spaceId: string, p: Placement) {+ try {+ globalThis.localStorage?.setItem(key(spaceId), JSON.stringify(p));+ } catch {+ // Blocked storage: not remembered.+ }+}++/** The corner nearest to a point in a `w`×`h` area. */+export function nearestCorner(x: number, y: number, w: number, h: number): Corner {+ return `${y < h / 2 ? "t" : "b"}${x < w / 2 ? "l" : "r"}` as Corner;+}++/** The player's width, kept inside the area it floats in. */+export function clampWidth(width: number, areaWidth: number, areaHeight: number, aspect: number): number {+ const byWidth = areaWidth - 2 * MARGIN;+ const byHeight = (areaHeight - 2 * MARGIN - BAR) * aspect;+ return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, byWidth, byHeight, width));+}++/**+ * Thread mode's mini-player (option A): the Space's live desktop, small,+ * floating in a corner of the thread. Drag it anywhere and it snaps to the+ * nearest corner; drag its grip to resize; click it (or its expand button)+ * to go back to the call layout. Corner and size are remembered per Space.+ * It floats over the thread only, never the composer, and `onReserve`+ * tells the thread how much room to keep clear at its end when it sits at+ * the bottom, so the newest message stays in view.+ */+export function MiniPlayer({+ spaceId,+ label,+ aspect,+ children,+ onExpand,+ onReserve,+}: {+ spaceId: string;+ /** Under the picture ("Desktop", or the window shown). */+ label: string;+ aspect: number;+ /** The stream (a view-only `StreamSurface`, `h-full`). */+ children: ReactNode;+ onExpand: () => void;+ /** Room to keep clear at the thread's end (px; 0 at the top corners). */+ onReserve?: (px: number) => void;+}) {+ const area = useRef<HTMLDivElement | null>(null);+ const [size, setSize] = useState({ w: 0, h: 0 });+ const [place, setPlace] = useState<Placement>(() => saved(spaceId));+ const [drag, setDrag] = useState<{ x: number; y: number; dx: number; dy: number; moved: boolean } | null>(null);+ const [resize, setResize] = useState<{ x: number; start: number; width: number } | null>(null);++ useLayoutEffect(() => {+ const el = area.current;+ if (!el) return;+ const read = () => setSize({ w: el.clientWidth, h: el.clientHeight });+ read();+ const ro = new ResizeObserver(read);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ const width = size.w ? clampWidth(resize ? resize.width : place.width, size.w, size.h, aspect) : place.width;+ const height = Math.round(width / aspect) + BAR;+ const left = place.corner.endsWith("l") ? MARGIN : size.w - MARGIN - width;+ const top = place.corner.startsWith("t") ? MARGIN : size.h - MARGIN - height;+ const bottom = place.corner.startsWith("b");++ useLayoutEffect(() => {+ onReserve?.(bottom ? height + MARGIN : 0);+ }, [bottom, height, onReserve]);++ const commit = (next: Placement) => {+ setPlace(next);+ save(spaceId, next);+ };++ const onDown = (e: PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) return;+ e.currentTarget.setPointerCapture(e.pointerId);+ setDrag({ x: e.clientX, y: e.clientY, dx: 0, dy: 0, moved: false });+ };+ const onMove = (e: PointerEvent<HTMLDivElement>) => {+ if (!drag) return;+ const dx = e.clientX - drag.x;+ const dy = e.clientY - drag.y;+ setDrag({ ...drag, dx, dy, moved: drag.moved || Math.hypot(dx, dy) > CLICK_SLOP });+ };+ const onUp = () => {+ if (!drag) return;+ setDrag(null);+ if (!drag.moved) return onExpand();+ const cx = left + drag.dx + width / 2;+ const cy = top + drag.dy + height / 2;+ commit({ ...place, corner: nearestCorner(cx, cy, size.w, size.h) });+ };++ // The grip sits on the bar's inner end (toward the thread's middle):+ // dragging it away from the corner makes the player bigger.+ const inward = place.corner.endsWith("r") ? -1 : 1;+ const onGripDown = (e: PointerEvent<HTMLButtonElement>) => {+ e.stopPropagation();+ e.currentTarget.setPointerCapture(e.pointerId);+ setResize({ x: e.clientX, start: width, width });+ };+ const onGripMove = (e: PointerEvent<HTMLButtonElement>) => {+ if (!resize) return;+ // Toward the thread's middle grows it, toward its corner shrinks it.+ setResize({ ...resize, width: resize.start + (e.clientX - resize.x) * inward });+ };+ const onGripUp = (e: PointerEvent<HTMLButtonElement>) => {+ e.stopPropagation();+ if (!resize) return;+ setResize(null);+ commit({ ...place, width: clampWidth(width, size.w, size.h, aspect) });+ };++ return (+ <div ref={area} data-mini-player-area="" className="pointer-events-none absolute inset-0">+ <div+ data-mini-player={place.corner}+ style={{ left: left + (drag?.dx ?? 0), top: top + (drag?.dy ?? 0), width, height }}+ className={cn(+ "pointer-events-auto absolute flex flex-col overflow-hidden rounded-lg bg-chrome shadow-float select-none",+ drag?.moved ? "cursor-grabbing" : "transition-[left,top] duration-200 ease-out",+ )}+ >+ <div+ role="button"+ tabIndex={0}+ aria-label={`${label}: click to go back to the call view, drag to move`}+ onPointerDown={onDown}+ onPointerMove={onMove}+ onPointerUp={onUp}+ onPointerCancel={() => setDrag(null)}+ // A click with no pointer behind it (keyboard, accessibility): expand.+ onClick={(e) => e.detail === 0 && onExpand()}+ onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), onExpand())}+ className="min-h-0 flex-1 cursor-pointer touch-none outline-none"+ >+ {children}+ </div>+ <div className={cn("relative flex h-7 shrink-0 items-center justify-between px-2 text-xs text-muted-foreground", inward > 0 && "flex-row-reverse")}>+ <button+ type="button"+ aria-label="Resize"+ data-mini-player-grip=""+ onPointerDown={onGripDown}+ onPointerMove={onGripMove}+ onPointerUp={onGripUp}+ className={cn("size-4 shrink-0 touch-none outline-none", inward < 0 ? "cursor-nesw-resize" : "cursor-nwse-resize")}+ >+ <svg viewBox="0 0 16 16" className={cn("size-4 text-muted-foreground/60", inward < 0 && "-scale-x-100")} aria-hidden>+ <path d="M5 15 15 5M10 15l5-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />+ </svg>+ </button>+ {/* Centred on the bar, whatever sits at its ends. */}+ <span data-mini-player-label="" className="pointer-events-none absolute inset-x-8 truncate text-center">+ {label}+ </span>+ <Tooltip content="Call view">+ <button+ type="button"+ aria-label="Call view"+ data-mini-player-expand=""+ onPointerDown={(e) => e.stopPropagation()}+ onClick={onExpand}+ className="inline-flex size-5 shrink-0 cursor-default items-center justify-center rounded-lg outline-none hover:bg-accent hover:text-foreground"+ >+ <Maximize2Icon className="size-3.5" />+ </button>+ </Tooltip>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx b/apps/cua-spaces-web/src/components/space-thread/space-call.tsxindex 2960d6247b..761a122f5c 100644--- a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx@@ -4,6 +4,11 @@import { XIcon } from "lucide-react";import { useEffect, useMemo, useState, type ReactNode } from "react";+import { Minimize2Icon } from "lucide-react";++import { Tooltip } from "@/components/ui/tooltip";+import { isMacPlatform } from "@/lib/utils";+import { harnessName, useBridge, type SpaceFact, type SpaceThread, type StreamRow, type ThreadAttachment, type ThreadView as PostView } from "@/bridge";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { toast } from "@/components/ui/toast";@@ -15,6 +20,8 @@ import { CallSplit } from "./call-split";import { Composer } from "./composer";import { MembersPanel, type MemberPresence } from "./members-panel";import { panelFacts } from "./rail";+import type { SpaceLayout } from "./layout-mode";+import { MiniPlayer } from "./mini-player";import { GUEST_COMPOSER } from "./rights";import { buildRoster } from "./roster";import { ThreadView } from "./thread-view";@@ -44,7 +51,21 @@ export function SpaceCall({onStream,presence,onShare,+ layout = "call",+ onLayout,+ smallStage,+ aspect = 16 / 10,+ stageLabel = "Desktop",}: {+ /** Call mode (the desktop is the main area) or thread mode (the thread is, and the desktop shrinks). */+ layout?: SpaceLayout;+ onLayout?: (next: SpaceLayout) => void;+ /** The desktop for thread mode: view only, `h-full` (the same live session as the stage). */+ smallStage?: ReactNode;+ /** The desktop's aspect ratio (the mini-player keeps it). */+ aspect?: number;+ /** What the mini-player's bar says ("Desktop", or the window shown). */+ stageLabel?: string;/** The Space's id (Add an agent joins agents to it). */spaceId: string;spaceName: string;@@ -85,6 +106,21 @@ export function SpaceCall({const canAddAgent = thread.status === "ready" && thread.role !== "guest";// Share's "Add an agent" opens this page's sheet for this Space.useEffect(() => (canAddAgent ? registerAddAgent(spaceId, () => setAddOpen(true)) : undefined), [canAddAgent, spaceId]);+ const [reserve, setReserve] = useState(0);+ const threadMode = layout === "thread" && Boolean(smallStage);+ // ⌘⇧T (Ctrl+Shift+T): thread view and back.+ useEffect(() => {+ if (!onLayout) return;+ const onKey = (e: KeyboardEvent) => {+ const mod = isMacPlatform() ? e.metaKey : e.ctrlKey;+ if (mod && e.shiftKey && !e.altKey && e.key.toLowerCase() === "t") {+ e.preventDefault();+ onLayout(layout === "thread" ? "call" : "thread");+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [layout, onLayout]);const harnessOf = (handle: string) => roster.agents.find((a) => a.name === handle)?.harness ?? "";// Attachments are Cua Volume paths: show the file where the Volume is mounted.const openAttachment = (a: ThreadAttachment) => {@@ -93,46 +129,84 @@ export function SpaceCall({toast(`Couldn't show ${a.name}`, { description: e instanceof Error ? e.message : String(e), type: "error" }),);};+ const threadView = (endInset: number) => (+ <ThreadView+ className="min-h-0 flex-1"+ endInset={endInset}+ items={thread.items}+ roster={roster}+ onAnswer={thread.answer}+ onOpenAttachment={openAttachment}+ onRemoveAgent={thread.removeAgent ?? undefined}+ onReachTop={thread.hasMoreBefore ? thread.loadEarlier : undefined}+ empty={+ thread.status === "loading" ? null : (+ <p className="text-[13px] text-muted-foreground" data-thread-empty="">+ {thread.error ? `Couldn't read the thread: ${thread.error}` : `Nothing here yet. Write to everyone in ${spaceName}, or @mention an agent to give it a task.`}+ </p>+ )+ }+ />+ );+ const composer = (+ <>+ {thread.error && thread.items.length ? <p className="px-6 pb-1 text-xs text-muted-foreground">Reconnecting to the thread…</p> : null}+ <div className="px-5 pb-4">+ <Composer+ placeholder={`Message ${spaceName}`}+ candidates={roster.candidates}+ handles={roster.handles}+ agentHarness={harnessOf}+ onSend={(text) => thread.post(text, view ?? null)}+ disabled={thread.status !== "ready"}+ disabledReason={thread.role === "guest" ? GUEST_COMPOSER : null}+ />+ </div>+ </>+ );return (<div data-call-layout="" className="flex h-full flex-col">{header}{notice}<div className="flex min-h-0 flex-1">- <CallSplit- stage={<div className="h-full px-5 pt-4">{stage}</div>}- below={- <>- <ThreadView- className="min-h-0 flex-1"- items={thread.items}- roster={roster}- onAnswer={thread.answer}- onOpenAttachment={openAttachment}- onRemoveAgent={thread.removeAgent ?? undefined}- onReachTop={thread.hasMoreBefore ? thread.loadEarlier : undefined}- empty={- thread.status === "loading" ? null : (- <p className="text-[13px] text-muted-foreground" data-thread-empty="">- {thread.error ? `Couldn't read the thread: ${thread.error}` : `Nothing here yet. Write to everyone in ${spaceName}, or @mention an agent to give it a task.`}- </p>- )- }- />- {thread.error && thread.items.length ? <p className="px-6 pb-1 text-xs text-muted-foreground">Reconnecting to the thread…</p> : null}- <div className="px-5 pb-4">- <Composer- placeholder={`Message ${spaceName}`}- candidates={roster.candidates}- handles={roster.handles}- agentHarness={harnessOf}- onSend={(text) => thread.post(text, view ?? null)}- disabled={thread.status !== "ready"}- disabledReason={thread.role === "guest" ? GUEST_COMPOSER : null}- />- </div>- </>- }- />+ {threadMode ? (+ // Thread view: the thread is the main area; the desktop shrinks+ // into a floating mini-player over it, never over the composer.+ <div data-thread-layout="" className="flex min-h-0 min-w-0 flex-1 flex-col">+ <div className="relative flex min-h-0 flex-1 flex-col">+ {threadView(reserve)}+ <MiniPlayer spaceId={spaceId} label={stageLabel} aspect={aspect} onExpand={() => onLayout?.("call")} onReserve={setReserve}>+ {smallStage}+ </MiniPlayer>+ </div>+ {composer}+ </div>+ ) : (+ <CallSplit+ leading={+ onLayout && smallStage ? (+ <Tooltip content={`Thread view (${isMacPlatform() ? "⌘⇧T" : "Ctrl+Shift+T"})`}>+ <button+ type="button"+ aria-label="Thread view"+ data-layout-toggle="thread"+ onClick={() => onLayout("thread")}+ className="inline-flex size-5 cursor-default items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <Minimize2Icon className="size-3.5" />+ </button>+ </Tooltip>+ ) : undefined+ }+ stage={<div className="h-full px-5 pt-4">{stage}</div>}+ below={+ <>+ {threadView(0)}+ {composer}+ </>+ }+ />+ )}<MembersPanelroster={roster}presence={presence}diff --git a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsxindex 5431b9762b..0f1b3a55ff 100644--- a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx@@ -31,8 +31,11 @@ export function ThreadView({onRemoveAgent,empty,className,+ endInset = 0,}: {items: ThreadItem[];+ /** Room kept clear at the end (px): thread mode's mini-player sits there, never over the newest message. */+ endInset?: number;/** Removes an agent member from its card (absent: the host can't). */onRemoveAgent?: (handle: string) => Promise<void>;/** Scrolled to the top: read the page before (when there is one). */@@ -74,6 +77,11 @@ export function ThreadView({// Follows the first and last items, not every render.// eslint-disable-next-line react-hooks/exhaustive-deps}, [first, last, items.length]);+ // The mini-player moved to (or grew at) the bottom: keep the newest entry in view above it.+ useLayoutEffect(() => {+ const el = ref.current;+ if (el && atEnd.current) el.scrollTop = el.scrollHeight;+ }, [endInset]);return (<divref={ref}@@ -97,7 +105,7 @@ export function ThreadView({{items.length === 0 ? (<div className="flex h-full items-end px-8 pb-4">{empty}</div>) : (- <div className="flex min-h-full flex-col justify-end gap-1 px-8 pt-5 pb-4">+ <div className="flex min-h-full flex-col justify-end gap-1 px-8 pt-5 pb-4" style={endInset ? { paddingBottom: endInset + 16 } : undefined}>{items.map((item) => (<ThreadItemView key={item.key} item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} />))}diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsxindex 8894ca27c3..3d30d5c31e 100644--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx@@ -28,6 +28,7 @@ import { cn } from "@/lib/utils";import { volumeUnavailableNote } from "@/lib/volume-notes";import { canDelete, canPower, createError, createProgress, machineName, powerLabel, powerPending, spacePlace, spaceState } from "@/lib/spaces";import { useFlag } from "@/bridge/flags";+import { useSpaceLayout } from "@/components/space-thread/layout-mode";import { LegacySpacePage } from "@/legacy/routes/spaces/$spaceId";export const Route = createFileRoute("/spaces/$spaceId")({@@ -96,6 +97,8 @@ function SpaceDetailPage() {const access = thisMachine?.accessNotice ?? null;const devices = useDevices();const { detail, stream, windowsUnsupported, pip, query, setQuery, agents, copy } = useSpaceDetail(space, hostArch, { experiments, access });+ // Call view or thread view, remembered per Space.+ const [layout, setLayout] = useSpaceLayout(space?.id ?? "");const volumeError = useSpaceVolumeError(space, space ? spaceState(space) === "running" : false);// The Space's thread (CUA-2155). A daemon without it answers unsupported,// and the page keeps its classic layout; a create still in progress has none yet.@@ -289,8 +292,9 @@ function SpaceDetailPage() {<OsIcon os={space.os} className="size-4.5 text-muted-foreground" /></div>);- const surface = (className: string, windowId?: string | null, windowName?: string | null) => (+ const surface = (className: string, windowId?: string | null, windowName?: string | null, interactive = true) => (<StreamSurface+ interactive={interactive}spaceId={space.id}windowId={windowId}windowName={windowName}@@ -442,6 +446,11 @@ function SpaceDetailPage() {</>}stage={surface("h-full", shownRow?.id ?? null, shownView?.app ?? null)}+ layout={layout}+ onLayout={setLayout}+ smallStage={surface("h-full", shownRow?.id ?? null, shownView?.app ?? null, false)}+ aspect={aspect}+ stageLabel={shownRow?.label ?? "Desktop"}thread={thread}facts={detail.facts}more={sections}