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
perf(spaces): reconnect to a Space's desktop in under a second (CUA-2850) (#6176)
ddupont8aa59c7eb48b
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swiftindex 8247494b3a..f287191e1a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift@@ -592,7 +592,9 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {}public func streamProvider(id: String) async throws -> SpaceStreamSourceProviding {- let space = try await connection.attach(to: SpaceID(id), requireReady: false)+ // Not `attach(to:)`: that lists every Space on every machine (and+ // waits for the relay) before the stream is even asked for.+ let space = try await connection.attachForStream(to: SpaceID(id))return SpaceStreamProvider(space: space)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/SyntheticStreamProvider.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/SyntheticStreamProvider.swiftindex 6f76988af4..add9b2f33a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/SyntheticStreamProvider.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/SyntheticStreamProvider.swift@@ -201,6 +201,12 @@ final class SyntheticMedia: SpaceStreamSession, @unchecked Sendable {lock.lock(); jumpToKeyframe = true; lock.unlock()}+ /// The transport ends under the session (the Space stopped, the machine+ /// went away): the socket's close, as the media client reports it.+ func dropTransport() {+ sink.onEvent(event: MediaEvent(kind: "closed", json: #"{"code":1006,"reason":"reset"}"#))+ }+override func sendText(json: String) throws {lock.lock()inputBatches += 1diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swiftindex b18b2e9df1..92cf88ea8a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift@@ -165,6 +165,7 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {stream.users = 1letGo(stream, key: key)}+ warm.removeAll()}// MARK: - Surfaces@@ -203,6 +204,7 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {let stream = streams[surface.key] ?? Stream()streams[surface.key] = streamstream.users += 1+ warm.removeAll { $0 == surface.key }if let failure = stream.failure {setPhase(surface, .failed(failure, opening: true))} else if let session = stream.session {@@ -241,7 +243,21 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {}}+ private func isSuspended(_ status: LiveStreamSession.Status) -> Bool {+ if case .suspended = status { return true }+ return false+ }+private func statusChanged(_ key: StreamKey, _ status: LiveStreamSession.Status) {+ // A warm session no slot shows that stops streaming (the Space+ // stopped, the machine went away, the daemon restarted) is let go+ // now: reconnecting and backing off for nobody would hold the+ // transport and its capture on a Space nobody is looking at. The+ // slot that comes back opens a fresh stream and says why if it can't.+ if isUnattended(key) {+ if status != .streaming, !isSuspended(status) { dropWarm(key) }+ return+ }guard case let .failed(reason) = status else { return }for s in surfaces.values where s.key == key { setPhase(s, .failed(reason)) }}@@ -345,10 +361,14 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {surface.view.removeFromSuperview()if surfaces.isEmpty { unwatchWindow() }guard let stream = streams[surface.key] else { return }- guard grace, surface.key.tier == .full, stream.session != nil, slotGrace > .zero else {+ // Only a session that is streaming now goes warm: one that is+ // reconnecting or failed has nothing to come back to.+ let healthy = stream.session.map { $0.status == .streaming || isSuspended($0.status) } ?? false+ guard grace, surface.key.tier == .full, healthy, !paused, slotGrace > .zero else {return letGo(stream, key: surface.key)}let key = surface.key+ goWarm(key)Task { @MainActor [weak self, weak stream] intry? await Task.sleep(for: self?.slotGrace ?? .zero)guard let self, let stream else { return }@@ -356,10 +376,50 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {}}- /// 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)+ /// How long a viewer's session outlives its slot. A page that moves the+ /// viewer (call view to thread view and back) mounts its new slot at+ /// once, and a person who leaves the Space and comes back (Spaces, another+ /// page, then the Space again) comes within a minute: either way the new+ /// slot binds to the same live session and shows its last frame, with no+ /// reconnect. It was 1.5 s, so every real visit away reopened the stream+ /// from scratch (list the Spaces, ask for a ticket, dial, wait for a+ /// keyframe).+ ///+ /// Bounded in time, and never kept for nothing: a warm session whose+ /// transport drops (the Space stopped, the machine went away) is+ /// released at once, not reconnected for nobody (`statusChanged`); at+ /// most `maxWarm` Spaces stay warm, the oldest going first; a hidden+ /// window, a closed window and a page load release them all.+ var slotGrace: Duration = .seconds(45)++ /// The most viewer sessions kept warm with no slot at once.+ var maxWarm = 3++ /// Viewer streams with no slot, oldest first (the order they went warm).+ private var warm: [StreamKey] = []++ /// A stream no slot shows and no panel holds: warm, waiting for its+ /// slot to come back.+ private func isUnattended(_ key: StreamKey) -> Bool {+ guard let stream = streams[key], stream.holds == 0 else { return false }+ return !surfaces.values.contains { $0.key == key }+ }++ /// Stops a warm stream now (its grace timers find it gone and do nothing).+ private func dropWarm(_ key: StreamKey) {+ warm.removeAll { $0 == key }+ guard let stream = streams[key], isUnattended(key) else { return }+ stream.users = 1+ letGo(stream, key: key)+ }++ /// Keeps `key` warm, and lets the oldest warm streams go beyond `maxWarm`.+ private func goWarm(_ key: StreamKey) {+ warm.removeAll { $0 == key }+ warm.append(key)+ warm.removeAll { !isUnattended($0) }+ while warm.count > maxWarm { dropWarm(warm[0]) }+ }/// One user fewer; the last one stops the session.private func letGo(_ stream: Stream, key: StreamKey) {@@ -505,6 +565,9 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {func setPaused(_ hidden: Bool) {guard hidden != paused else { return }paused = hidden+ // A hidden window keeps nothing warm: its sessions stop, and a warm+ // one has no slot to start again for.+ if hidden { for key in warm { dropWarm(key) } }for stream in streams.values {// The picture-in-picture panel shows a held stream: it keeps going.guard let session = stream.session, stream.holds == 0 else { continue }diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swiftindex 2a09957820..d0662ac535 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift@@ -553,6 +553,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) }+ // Shorter than the default, so the move back below does not wait it out.+ s.slotGrace = .milliseconds(300)s.handle(message([entry("call", space: "a")]))await settle { host.phases("call").contains("live") }let callSlot = try #require(s.surfaces["call"])@@ -604,6 +606,147 @@ struct WebUIVideoSurfacesTests {#expect(s.stats().isEmpty)}+ // MARK: - Coming back to a Space (warm sessions)++ /// Regression: leaving a Space for another page and returning sat on+ /// "Connecting…" for as long as a fresh open takes, because the viewer's+ /// session outlived its slot by only 1.5 s. Returning within the grace+ /// binds the new slot to the live session: live on its first word, no+ /// second open.+ @Test func comingBackToASpaceWithinTheGraceIsLiveAtOnceOnTheSameSession() 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) }+ // The default is a minute or so, not the old 1.5 s.+ #expect(s.slotGrace >= .seconds(30) && s.slotGrace <= .seconds(120))+ s.slotGrace = .seconds(30)+ s.handle(message([entry("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ let first = try #require(s.surfaces["v1"])+ let session = try #require(s.sessionFor(first))++ // The page goes to another route: its slot is removed. Well past the old grace.+ s.handle(message([], remove: ["v1"]))+ try? await Task.sleep(for: .milliseconds(1800))+ #expect(s.stats().count == 1)+ #expect(session.status == .streaming)++ let returned = Date()+ s.handle(message([entry("v2", space: "a")]))+ await settle(tries: 5) { !host.phases("v2").isEmpty }+ #expect(host.phases("v2") == ["live"])+ // The timing guard: generous, it only catches a renegotiation creeping back in.+ #expect(Date().timeIntervalSince(returned) < 1.0)+ let slot2 = try #require(s.surfaces["v2"])+ #expect(s.sessionFor(slot2) === session)+ #expect(host.opened.count == 1)+ s.removeAll()+ }++ @Test func comingBackAfterTheGraceOpensAFreshStream() 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("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ let oldSlot = try #require(s.surfaces["v1"])+ let old = try #require(s.sessionFor(oldSlot))+ s.handle(message([], remove: ["v1"]))+ await settle { s.stats().isEmpty }+ #expect(s.stats().isEmpty)+ s.handle(message([entry("v2", space: "a")]))+ await settle { host.phases("v2").contains("live") }+ #expect(host.opened.count == 2)+ let slot2 = try #require(s.surfaces["v2"])+ #expect(s.sessionFor(slot2) !== old)+ s.removeAll()+ }++ /// A warm session is never kept for a Space that stopped or a machine+ /// that went away: its transport drops, and it is released at once+ /// instead of reconnecting for nobody.+ @Test func aWarmSessionWhoseSpaceStoppedIsReleasedNotReconnected() async throws {+ let host = Host()+ let units = AccessUnit.split(Self.tinyH264)+ let provider = SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30)+ let s = surfaces(host) { _, _ in provider }+ s.slotGrace = .seconds(30)+ s.handle(message([entry("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ let slot = try #require(s.surfaces["v1"])+ let session = try #require(s.sessionFor(slot))+ s.handle(message([], remove: ["v1"]))+ #expect(s.stats().count == 1)++ provider.lastMedia?.dropTransport()+ await settle { s.stats().isEmpty }+ #expect(s.stats().isEmpty)+ await settle { session.status == .idle }+ #expect(session.status == .idle)++ // Coming back opens again (and would say why if it could not).+ s.handle(message([entry("v2", space: "a")]))+ await settle { host.phases("v2").contains("live") }+ #expect(host.opened.count == 2)+ s.removeAll()+ }++ @Test func aSessionThatAlreadyDroppedIsNotKeptWarm() async throws {+ let host = Host()+ let units = AccessUnit.split(Self.tinyH264)+ let provider = SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30)+ let s = surfaces(host) { _, _ in provider }+ s.slotGrace = .seconds(30)+ s.handle(message([entry("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ let slot = try #require(s.surfaces["v1"])+ let session = try #require(s.sessionFor(slot))+ provider.lastMedia?.dropTransport()+ await settle { session.status != .streaming }+ s.handle(message([], remove: ["v1"]))+ #expect(s.stats().isEmpty)+ s.removeAll()+ }++ @Test func aHiddenWindowAndAClosedWindowKeepNothingWarm() 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 = .seconds(30)+ s.handle(message([entry("v1", space: "a")]))+ await settle { host.phases("v1").contains("live") }+ s.handle(message([], remove: ["v1"]))+ #expect(s.stats().count == 1)+ s.setPaused(true)+ #expect(s.stats().isEmpty)+ s.setPaused(false)++ // Closed window: every warm session goes.+ s.handle(message([entry("v2", space: "a")]))+ await settle { host.phases("v2").contains("live") }+ s.handle(message([], remove: ["v2"]))+ #expect(s.stats().count == 1)+ s.removeAll()+ #expect(s.stats().isEmpty)+ }++ @Test func atMostMaxWarmViewerSessionsStayWarmOldestFirst() 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 = .seconds(30)+ s.maxWarm = 2+ for space in ["a", "b", "c"] {+ s.handle(message([entry("v-\(space)", space: space)]))+ await settle { host.phases("v-\(space)").contains("live") }+ s.handle(message([], remove: ["v-\(space)"]))+ }+ let warm = Set(s.stats().compactMap { $0["spaceId"] as? String })+ #expect(warm == ["b", "c"])+ s.removeAll()+ }+// 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 15acf69520..4620bd1239 100644--- a/apps/cua-spaces-macos/docs/native-video.md+++ b/apps/cua-spaces-macos/docs/native-video.md@@ -82,7 +82,9 @@ 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. 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.+**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 warm for `slotGrace` (45 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 a person leaves a Space for the Spaces page and comes back: the new slot binds to the same live session and shows its current frame at once, with no reconnect (it was 1.5 s, so every real visit away reopened the stream). A warm session is bounded: at most `maxWarm` (3) Spaces stay warm, the oldest going first; one whose transport drops (the Space stopped, the machine went away) is released at once rather than reconnected for nobody; a hidden window, a closed window and a page load release every one; and one that was already reconnecting or failed when its slot left is not kept.++Opening a stream no longer lists every Space on every machine first (`SpacesConnection.attachForStream`): that list waited for the relay directory, so a slow or unreachable relay delayed or failed the desktop of a Space on this Mac.### Input and keyboard focusdiff --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 fa728e2719..fb3c18bdd3 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@@ -72,6 +72,12 @@ export interface StreamSurfaceProps {* cover says it didn't, why, and offers Try again: the viewer never waits* silently. */export const CONNECT_TIMEOUT_MS = 20_000;+/** How long "Connecting…" may go on before the cover says it is taking longer+ * than usual (a Space that was just turned on, a machine far away). */+export const SLOW_CONNECT_MS = 4_000;+/** The cover's second line once a connect is slow: plain words, and it goes+ * with the picture. */+export const SLOW_CONNECT_HINT = "Still connecting. This is taking longer than usual.";/** Why, when it timed out. */export const CONNECT_TIMEOUT_REASON = "No picture arrived from the desktop within 20 seconds.";@@ -126,6 +132,7 @@ export function StreamSurface({ spaceId, os, aspectRatio = 16 / 10, canStream, p// Still no picture after CONNECT_TIMEOUT_MS: failed, with the reason and// Try again (a picture that arrives later still shows).const timedOut = useTimedOut(slot?.phase === "connecting", CONNECT_TIMEOUT_MS, `${spaceId}:${attempt}`);+ const slow = useTimedOut(slot?.phase === "connecting", SLOW_CONNECT_MS, `${spaceId}:${attempt}`);const phase: StreamPhase = !slot ? "nosession" : slot.phase === "live" ? "streaming" : slot.phase === "failed" || timedOut ? "failed" : "connecting";const cover = useDesktopCover({ canStream, previewText, autoConnect, connectRequested: requested, stream: phase, access });const thumbnail = useSpaceThumbnail(spaceId, videoHere && canStream && !replaced && !access);@@ -172,6 +179,7 @@ export function StreamSurface({ spaceId, os, aspectRatio = 16 / 10, canStream, pcover={cover}thumbnail={access ? null : thumbnail}reason={cover.kind === "status" ? reason : null}+ hint={cover.kind === "connecting" && slow ? SLOW_CONNECT_HINT : null}onButton={press}onAction={onAccessAction}onOpen={slot?.phase === "failed" ? () => void open() : undefined}@@ -241,6 +249,7 @@ function DesktopCoverView({cover,thumbnail,reason,+ hint,onButton,onAction,onOpen,@@ -250,6 +259,8 @@ function DesktopCoverView({thumbnail: string | null;/** Why it could not connect, under the line. */reason?: string | null;+ /** While it connects slowly: that it is still going. */+ hint?: string | null;onButton: () => void;onAction?: () => void;/** The stream failed here: its own window instead. */@@ -280,6 +291,11 @@ function DesktopCoverView({{reason}</p>) : null}+ {hint ? (+ <p data-cover-hint="" className="mt-1 max-w-md text-xs text-white/60">+ {hint}+ </p>+ ) : null}{cover.action ? (<buttontype="button"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 8f4f5c91f4..d4c1b38dab 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@@ -17,7 +17,7 @@ import type { SlotStatus } from "@/lib/video-slots";import { resetVideoSlotLoader } from "./use-video-slot";import { NO_VIDEO_HERE, webCodecsHost } from "./webcodecs-host";import { VideoStats } from "./video-stats";-import { needsActivation, resetWebCodecsSlots, sessionConfig, streamTarget, WebCodecsSlots, type SessionFactory } from "./webcodecs-slots";+import { MAX_PARKED, needsActivation, PARK_MS, resetWebCodecsSlots, sessionConfig, streamTarget, WebCodecsSlots, type SessionFactory } from "./webcodecs-slots";// The production MediaSession, replaced: jsdom has no WebSocket media or VideoDecoder.const sessions: { options: Parameters<SessionFactory>[0]; started: number; stopped: number }[] = [];@@ -250,6 +250,122 @@ describe("WebCodecsSlots", () => {});});+// Leaving a Space and coming back reconnected from scratch (a ticket, a+// socket, a keyframe) every time. A live viewer is parked for PARK_MS and the+// next viewer slot for that Space adopts it, live at once.+describe("a viewer that leaves and comes back", () => {+ function setup() {+ const { desktop, calls } = fakeDesktop();+ const slots = new WebCodecsSlots(desktop, document);+ const mount = (options: Parameters<WebCodecsSlots["register"]>[1] = viewer) => {+ const el = document.createElement("div");+ document.body.append(el);+ const seen: SlotStatus[] = [];+ const stop = slots.register(el, options, (s) => seen.push(s));+ registered.push(stop);+ return { el, seen, stop, last: () => seen.at(-1) };+ };+ return { slots, calls, mount };+ }++ async function live(mounted: ReturnType<ReturnType<typeof setup>["mount"]>) {+ await flush();+ act(() => sessions.at(-1)!.options.onFrame?.(1280, 800));+ expect(mounted.last()).toMatchObject({ phase: "live" });+ }++ afterEach(() => vi.useRealTimers());++ it("keeps the live session while away, and the next slot is live on its first word with no new ticket", async () => {+ const { calls, mount } = setup();+ const first = mount();+ await live(first);+ first.stop();+ // Parked: running, off the page.+ expect(sessions[0]!.stopped).toBe(0);+ expect(document.querySelector("canvas")).toBeNull();++ const back = mount({ ...viewer, radius: 8 });+ expect(back.seen).toEqual([{ phase: "live", focused: false }]);+ expect(back.el.querySelector<HTMLCanvasElement>('canvas[data-webcodecs="full"]')?.style.opacity).toBe("1");+ await flush();+ expect(calls).toHaveLength(1);+ expect(sessions).toHaveLength(1);+ expect(sessions[0]!.started).toBe(1);+ expect(sessions[0]!.stopped).toBe(0);+ back.stop();+ });++ it("closes the parked session after the grace, and a later slot opens a fresh one", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const { calls, mount } = setup();+ const first = mount();+ await live(first);+ first.stop();+ act(() => void vi.advanceTimersByTime(PARK_MS - 1_000));+ expect(sessions[0]!.stopped).toBe(0);+ act(() => void vi.advanceTimersByTime(1_000));+ expect(sessions[0]!.stopped).toBe(1);++ const again = mount();+ expect(again.seen).toEqual([]);+ await vi.advanceTimersByTimeAsync(10);+ expect(calls).toHaveLength(2);+ expect(sessions).toHaveLength(2);+ });++ it("lets a parked session go when its stream ends (the Space stopped) and opens fresh on return", async () => {+ const { calls, mount } = setup();+ const first = mount();+ await live(first);+ first.stop();+ act(() => sessions[0]!.options.onGone?.("the Space stopped"));+ expect(sessions[0]!.stopped).toBe(1);+ const again = mount();+ // Not live from the dead session: connecting, with a new ticket.+ expect(again.seen).toEqual([]);+ await flush();+ expect(calls).toHaveLength(2);+ });++ it("keeps nothing parked while the page is hidden, or for a session that was not live", async () => {+ const { mount } = setup();+ const a = mount();+ await live(a);+ a.stop();+ hidden = true;+ act(() => void document.dispatchEvent(new Event("visibilitychange")));+ expect(sessions[0]!.stopped).toBe(1);+ hidden = false;++ // Connecting (no frame yet) when it leaves: closed, not parked.+ const b = mount({ ...viewer, spaceId: "local:b" });+ await flush();+ b.stop();+ expect(sessions[1]!.stopped).toBe(1);+ });++ it("parks tiles and windows never, and at most MAX_PARKED Spaces, the oldest first", async () => {+ const { mount } = setup();+ const t = mount(tile);+ await live(t);+ t.stop();+ expect(sessions[0]!.stopped).toBe(1);+ const w = mount({ ...viewer, windowId: "w1" });+ await live(w);+ w.stop();+ expect(sessions[1]!.stopped).toBe(1);++ for (let i = 0; i <= MAX_PARKED; i++) {+ const m = mount({ ...viewer, spaceId: `local:p${i}` });+ await live(m);+ m.stop();+ }+ const stopped = sessions.slice(2).map((s) => s.stopped);+ expect(stopped).toEqual([1, ...Array(MAX_PARKED).fill(0)]);+ });+});+describe("decoding and input like the Swift app's video tiers", () => {it("asks every slot for the hardware decoder; the viewer sends ⌘ as Control to a Linux or Windows Space from a Mac", () => {expect(sessionConfig({ interactive: false, os: "linux" }, "darwin")).toEqual({ hardwareAcceleration: "prefer-hardware", metaAsControl: false, wholeCommandChords: false, scrollNeedsFocus: false });diff --git a/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts b/apps/cua-spaces-web/src/components/video/webcodecs-slots.tsindex bc5fb62f71..d09b0ca9a7 100644--- a/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts+++ b/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts@@ -38,6 +38,14 @@* in the background, and the session opens again with activation when the* Space says that window needs it (`would_require_activation`).*+ * Leaving a Space and coming back reuses the live session: a viewer slot+ * (the desktop, not a window) whose picture is live is parked for+ * `PARK_MS` instead of closed, with its canvas and decoder still running, and+ * the next viewer slot for that Space adopts it and is live on the spot. A+ * parked session is released when its stream ends (the Space stopped, the+ * machine went away), when the page is hidden, past `MAX_PARKED` Spaces+ * (the oldest first), and after `PARK_MS`.+ ** The viewer slots (`full`: the Space page's desktop, a PiP window) draw* presence over the picture (`presence.ts`): the other participants'* cursors and yours, shown only while the slot is live.@@ -121,6 +129,16 @@ interface Slot {detach: (() => void)[];}+/** How long a viewer's live session outlives its slot (the Mac app's `slotGrace`). */+export const PARK_MS = 45_000;+/** The most Spaces kept parked at once. */+export const MAX_PARKED = 3;++/** What a parked session is found by: only the desktop viewer parks. */+function parkKey(options: Pick<SlotOptions, "spaceId" | "tier" | "windowId">): string | null {+ return options.tier === "full" && !options.windowId ? options.spaceId : null;+}+/** Tells one ticket request from the next (the bridge envelope's id). */let ticketSeq = 0;@@ -139,6 +157,9 @@ export class WebCodecsSlots {/** Watches for a modal dialog opening or closing (while any slot is mounted). */private modalWatch: MutationObserver | null = null;private modal = false;+ /** Live viewer sessions of Spaces the page left, by Space id, oldest first. */+ private readonly parked = new Map<string, { slot: Slot; timer: ReturnType<typeof setTimeout> }>();+ private watchingVisibility = false;/** The video bench's counters, while the shell asks for them. */readonly stats: VideoStats | null;@@ -155,6 +176,9 @@ export class WebCodecsSlots {/** Starts `el`'s video; the returned function stops it and removes the canvas. */register(el: HTMLElement, options: SlotOptions, listener: (status: SlotStatus) => void): () => void {+ const key = parkKey(options);+ const parked = key ? this.takeParked(key) : null;+ if (parked) return this.adopt(parked, el, options, listener);const id = `${options.spaceId}#${options.tier}#${++this.next}`;const canvas = this.doc.createElement("canvas");canvas.dataset.webcodecs = options.tier;@@ -178,30 +202,123 @@ export class WebCodecsSlots {});}this.stats?.open(id, options.spaceId, options.tier);- this.slots.set(id, slot);- if (this.slots.size === 1) {+ this.track(slot);+ this.open(slot);+ return this.unregister(slot);+ }++ /** Starts watching for a slot: the page's visibility, and modal dialogs. */+ private track(slot: Slot): void {+ this.slots.set(slot.id, slot);+ if (!this.watchingVisibility) {+ this.watchingVisibility = true;this.doc.addEventListener("visibilitychange", this.onVisibility);- this.watchModal();}+ if (this.slots.size === 1) this.watchModal();if (this.modal) this.stepBack(slot, true);- if (options.interactive) this.wireFocus(slot);- this.open(slot);- return () => {- if (!this.slots.delete(id)) return;- this.close(slot);- for (const off of slot.detach.splice(0)) off();- slot.presence?.detach();- canvas.remove();- this.stats?.close(id);- if (this.slots.size === 0) {+ if (slot.options.interactive) this.wireFocus(slot);+ }++ /** Stops the watching nothing needs any more. */+ private untrack(): void {+ if (this.slots.size === 0) {+ this.modalWatch?.disconnect();+ this.modalWatch = null;+ this.modal = false;+ if (this.parked.size === 0 && this.watchingVisibility) {+ this.watchingVisibility = false;this.doc.removeEventListener("visibilitychange", this.onVisibility);- this.modalWatch?.disconnect();- this.modalWatch = null;- this.modal = false;}+ }+ }++ private unregister(slot: Slot): () => void {+ return () => {+ if (!this.slots.delete(slot.id)) return;+ if (this.canPark(slot)) this.park(slot);+ else this.teardown(slot);+ this.untrack();};}+ private teardown(slot: Slot): void {+ this.close(slot);+ for (const off of slot.detach.splice(0)) off();+ slot.presence?.detach();+ slot.presence = null;+ slot.canvas.remove();+ this.stats?.close(slot.id);+ }++ /** A live desktop viewer, on a visible page, outlives its slot for `PARK_MS`. */+ private canPark(slot: Slot): boolean {+ return parkKey(slot.options) !== null && PARK_MS > 0 && slot.session !== null && slot.status.phase === "live" && this.doc.visibilityState !== "hidden";+ }++ private park(slot: Slot): void {+ const key = parkKey(slot.options)!;+ this.discardParked(key);+ // No slot to show or take input: its keys, presence and canvas leave the page, the session goes on.+ for (const off of slot.detach.splice(0)) off();+ if (this.doc.activeElement === slot.canvas) slot.canvas.blur();+ slot.presence?.detach();+ slot.presence = null;+ slot.canvas.remove();+ slot.listener = () => {};+ const timer = setTimeout(() => this.discardParked(key), PARK_MS);+ this.parked.set(key, { slot, timer });+ while (this.parked.size > MAX_PARKED) this.discardParked(this.parked.keys().next().value!);+ }++ /** Takes the Space's parked session out of the parking (the caller shows it). */+ private takeParked(key: string): Slot | null {+ const entry = this.parked.get(key);+ if (!entry) return null;+ clearTimeout(entry.timer);+ this.parked.delete(key);+ return entry.slot;+ }++ /** Closes the Space's parked session, if any. */+ private discardParked(key: string): void {+ const slot = this.takeParked(key);+ if (!slot) return;+ this.teardown(slot);+ this.untrack();+ }++ private isParked(slot: Slot): boolean {+ const key = parkKey(slot.options);+ return key !== null && this.parked.get(key)?.slot === slot;+ }++ /** A new slot for a Space with a parked session: it shows that session, live at once. */+ private adopt(slot: Slot, el: HTMLElement, options: SlotOptions, listener: (status: SlotStatus) => void): () => void {+ slot.el = el;+ slot.options = options;+ slot.listener = listener;+ const inset = options.inset ?? 0;+ Object.assign(slot.canvas.style, {+ inset: `${inset}px`,+ width: `calc(100% - ${2 * inset}px)`,+ height: `calc(100% - ${2 * inset}px)`,+ borderRadius: `${options.radius}px`,+ });+ el.append(slot.canvas);+ if (options.tier === "full") {+ slot.presence = this.createPresence(this.desktop, slot.canvas, el, {+ spaceId: options.spaceId,+ ...(options.windowId ? { windowId: options.windowId } : {}),+ interactive: options.interactive,+ });+ slot.presence.setLive(slot.status.phase === "live");+ }+ slot.status = { ...slot.status, focused: false };+ this.track(slot);+ listener(slot.status);+ return this.unregister(slot);+ }+/*** While a modal dialog is open no slot takes the pointer or the keys: the* canvas stops catching pointer events and gives the keyboard back to the@@ -265,7 +382,7 @@ export class WebCodecsSlots {private open(slot: Slot): void {if (this.doc.visibilityState === "hidden") return;const gen = ++slot.generation;- const current = () => gen === slot.generation && this.slots.get(slot.id) === slot;+ const current = () => gen === slot.generation && (this.slots.get(slot.id) === slot || this.isParked(slot));this.set(slot, { phase: "connecting" });const { interactive } = slot.options;const target = streamTarget(slot.options, slot.activate);@@ -310,6 +427,13 @@ export class WebCodecsSlots {/** `opening`: no ticket came, so no stream ever existed. */private fail(slot: Slot, reason: string, opening = false): void {+ // A parked session that ended (the Space stopped, the machine went+ // away) is let go; nothing is shown for it.+ if (this.isParked(slot)) {+ this.stats?.failed(slot.id, reason);+ this.discardParked(parkKey(slot.options)!);+ return;+ }this.close(slot);this.stats?.failed(slot.id, reason);this.set(slot, { phase: "failed", reason, ...(opening ? { opening } : {}) });@@ -325,6 +449,7 @@ export class WebCodecsSlots {private onVisibility = (): void => {const hidden = this.doc.visibilityState === "hidden";+ if (hidden) for (const key of [...this.parked.keys()]) this.discardParked(key);for (const slot of this.slots.values()) {if (hidden) {if (slot.session || slot.status.phase === "connecting") {diff --git a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx b/apps/cua-spaces-web/src/lib/stream-surface.test.tsxindex 13bd37722f..447c0f4da2 100644--- a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx+++ b/apps/cua-spaces-web/src/lib/stream-surface.test.tsx@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createDemoAdapter } from "@/bridge/adapters/demo";import { noCore } from "@/bridge/__tests__/testCore";import { BridgeProvider, type Space } from "@/bridge";-import { CONNECT_TIMEOUT_MS, CONNECT_TIMEOUT_REASON, StreamSurface } from "@/components/space-detail/stream-surface";+import { CONNECT_TIMEOUT_MS, CONNECT_TIMEOUT_REASON, SLOW_CONNECT_HINT, SLOW_CONNECT_MS, StreamSurface } from "@/components/space-detail/stream-surface";import { ToastProvider } from "@/components/ui/toast";import { canStreamTile } from "@/components/video/tile-video";import { resetVideoSlotLoader } from "@/components/video/use-video-slot";@@ -586,6 +586,49 @@ describe("<StreamSurface> native video", () => {expect(container.querySelector("[data-desktop-cover]")).toBeNull();});+ // "Connecting…" alone for many seconds reads as hung: after SLOW_CONNECT_MS+ // the cover says, in plain words, that it is still going (and the failure+ // at CONNECT_TIMEOUT_MS still ends it).+ it("says it is still connecting once the wait is slow, and drops the line with the picture", async () => {+ expect(SLOW_CONNECT_MS).toBeLessThan(CONNECT_TIMEOUT_MS);+ expect(SLOW_CONNECT_HINT).not.toContain("\u00b7");+ vi.useFakeTimers({ shouldAdvanceTime: true });+ hostDrawsVideo();+ const { container, getByText } = mount();+ await waitFor(() => expect(updates()).not.toHaveLength(0));+ const first = updates()[0]!;+ expect(getByText("Connecting…")).toBeTruthy();+ expect(container.querySelector("[data-cover-hint]")).toBeNull();+ act(() => void vi.advanceTimersByTime(SLOW_CONNECT_MS - 500));+ expect(container.querySelector("[data-cover-hint]")).toBeNull();+ act(() => void vi.advanceTimersByTime(500));+ expect(container.querySelector("[data-cover-hint]")?.textContent).toBe(SLOW_CONNECT_HINT);+ expect(getByText("Connecting…")).toBeTruthy();+ act(() => hostEvent("video.surface", { surfaceId: first.surfaceId, state: "live" }));+ expect(container.querySelector("[data-cover-hint]")).toBeNull();+ expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy();+ });++ // The warm return: the host's session is still live, so its first word for+ // the new slot is "live". Leaving and coming back must go from the mount to+ // live with no wait of the page's own (no fixed delay, no settings round+ // trip): generous bound, it catches a delay creeping back in.+ it("goes from mounting to live as soon as the host says so, with no wait of its own", async () => {+ hostDrawsVideo();+ const first = mount();+ await waitFor(() => expect(updates()).not.toHaveLength(0));+ first.unmount();+ expect(posted.some((m) => m.type === "surfaces" && m.remove.length > 0)).toBe(true);+ posted.length = 0;+ const started = performance.now();+ const { container } = mount();+ await waitFor(() => expect(updates()).not.toHaveLength(0));+ act(() => hostEvent("video.surface", { surfaceId: updates()[0]!.surfaceId, state: "live" }));+ expect(container.querySelector('[data-stream-state="live"]')).toBeTruthy();+ expect(container.querySelector("[data-desktop-cover]")).toBeNull();+ expect(performance.now() - started).toBeLessThan(1_500);+ });+it("starts the wait over on Try again after a timeout", async () => {vi.useFakeTimers({ shouldAdvanceTime: true });hostDrawsVideo();diff --git a/libs/cua/crates/cua-spaces-ext/tests/e2e_docker_stream_timing.rs b/libs/cua/crates/cua-spaces-ext/tests/e2e_docker_stream_timing.rsnew file mode 100644index 0000000000..e30bdfd01d--- /dev/null+++ b/libs/cua/crates/cua-spaces-ext/tests/e2e_docker_stream_timing.rs@@ -0,0 +1,151 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Stream connect timing against a real linux container (opt-in: set+//! `CUA_SPACES_E2E_URL` and `CUA_SPACES_E2E_TOKEN`, as for+//! `e2e_docker_stream`; skipped without them).+//!+//! It opens the Desktop stream the way the apps do, closes it, and opens it+//! again, printing the time of each phase (run with `--nocapture`):+//! the ticket (`StreamService.OpenMedia`, which also waits for the first+//! frame inside the guest), the media socket attach, and the first frame+//! reaching the client. The thresholds are generous: they catch a fixed+//! sleep or a retry loop creeping into the path, not machine noise.++use cua_spaces::stream::{FrameSink, StreamEvent, StreamOptions, StreamTarget, VideoFrame};+use cua_spaces::{Space, Spaces};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++#[derive(Default)]+struct FirstFrame {+ at: Mutex<Option<Instant>>,+}++impl FrameSink for FirstFrame {+ fn on_frame(&self, _f: VideoFrame) {+ self.at.lock().unwrap().get_or_insert_with(Instant::now);+ }+ fn on_event(&self, _e: StreamEvent) {}+}++fn target() -> Option<(String, String)> {+ let url = std::env::var("CUA_SPACES_E2E_URL")+ .ok()+ .filter(|s| !s.is_empty())?;+ Some((+ url,+ std::env::var("CUA_SPACES_E2E_TOKEN").unwrap_or_default(),+ ))+}++async fn connect(reg: &std::path::Path) -> (Spaces, Space) {+ cua_spaces_ext::stream::register();+ let (url, token) = target().unwrap();+ let spaces = Spaces::builder()+ .home(reg)+ .download_dir(reg.join("downloads"))+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay))+ .probe_timeout(Duration::from_secs(20))+ .build();+ let t = Instant::now();+ let info = spaces+ .add(&url, Some(token), Some("timing".into()))+ .await+ .unwrap();+ let space = spaces.space(&info.id).await.unwrap();+ eprintln!(+ "TIMING add+resolve {:>6.0} ms",+ t.elapsed().as_secs_f64() * 1e3+ );+ (spaces, space)+}++fn ms(d: Duration) -> f64 {+ d.as_secs_f64() * 1e3+}++fn options() -> StreamOptions {+ StreamOptions {+ max_fps: 30,+ ..Default::default()+ }+}++#[tokio::test]+async fn desktop_stream_connect_phases() {+ if target().is_none() {+ eprintln!("skipped: set CUA_SPACES_E2E_URL (see run-docker-e2e.sh)");+ return;+ }+ let reg = tempfile::tempdir().unwrap();+ let (_spaces, space) = connect(reg.path()).await;+ let mut totals = Vec::new();+ // The viewer joins presence before it opens its stream (so the Space+ // attributes its input), so the join is part of every cold open.+ for round in 0..2 {+ let t = Instant::now();+ let presence = space+ .join_presence(+ cua_spaces::presence::Identity {+ id: format!("timing-{round}"),+ display_name: "Timing".into(),+ color: String::new(),+ agent: false,+ },+ Duration::from_secs(10),+ )+ .await+ .unwrap();+ eprintln!(+ "TIMING presence join round {round}: {:>6.0} ms",+ ms(t.elapsed())+ );+ let t = Instant::now();+ let _ = presence.leave().await;+ eprintln!(+ "TIMING presence leave round {round}: {:>6.0} ms",+ ms(t.elapsed())+ );+ }+ for round in 0..4 {+ // Phase 1 and 2 split: the ticket alone (and give it back), then the+ // whole open with a first-frame clock.+ let t = Instant::now();+ let ticket = space+ .open_stream(StreamTarget::Display(None), options())+ .await+ .unwrap();+ let ticket_ms = ms(t.elapsed());+ space.close_stream(&ticket.media_session_id).await.unwrap();++ let sink = Arc::new(FirstFrame::default());+ let t = Instant::now();+ let session = space+ .stream_session(StreamTarget::Display(None), options(), sink.clone(), None)+ .await+ .unwrap();+ let open_ms = ms(t.elapsed());+ let mut first = None;+ for _ in 0..200 {+ if let Some(at) = *sink.at.lock().unwrap() {+ first = Some(at);+ break;+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ let first_ms = ms(first.expect("a first frame arrives").duration_since(t));+ let t = Instant::now();+ session.close().await.unwrap();+ let close_ms = ms(t.elapsed());+ eprintln!(+ "TIMING round {round}: ticket {ticket_ms:>6.0} ms | open (ticket + socket) {open_ms:>6.0} ms | first frame {first_ms:>6.0} ms | close {close_ms:>5.0} ms"+ );+ totals.push(first_ms);+ }+ // Generous: a fixed multi-second sleep or retry loop would break these.+ assert!(totals[0] < 15_000.0, "first connect took {} ms", totals[0]);+ for (i, t) in totals.iter().enumerate().skip(1) {+ assert!(*t < 10_000.0, "reconnect {i} took {t} ms");+ }+}diff --git a/libs/spaces-sdk-swift/Sources/CuaSpaces/SpacesConnection.swift b/libs/spaces-sdk-swift/Sources/CuaSpaces/SpacesConnection.swiftindex 62a173bc15..9e1720a7e7 100644--- a/libs/spaces-sdk-swift/Sources/CuaSpaces/SpacesConnection.swift+++ b/libs/spaces-sdk-swift/Sources/CuaSpaces/SpacesConnection.swift@@ -177,6 +177,37 @@ public actor SpacesConnection {return try await space(for: info)}+ /// A handle for streaming `id`, without `attach(to:)`'s costs.+ ///+ /// `attach(to:)` lists every Space the account can see, which waits for+ /// the relay directory and the team facts (a slow or unreachable relay+ /// delayed, or failed, opening the desktop of a Space on this Mac), then+ /// asks the guest for its `$HOME`, which a stream never uses. This+ /// resolves just the one Space in the SDK (its own connection cache and+ /// relay presence check decide whether to dial again) and takes its+ /// facts from that handshake. A Space the SDK cannot resolve (still+ /// being created, not registered, or no cua SDK behind this connection)+ /// takes the `attach(to:requireReady:)` path, whose errors say why.+ public func attachForStream(to id: SpaceID) async throws -> Space {+ guard let handle = try? await resolveFresh(id) else {+ return try await attach(to: id, requireReady: false)+ }+ let facts = handle.info()+ let info = SpaceInfo(id: id, provider: SpaceProvider(rawProvider: facts.provider),+ operatingSystem: facts.os, state: .ready, rawPhase: "ready", ipAddress: nil)+ return Space(info: info, connection: self)+ }++ /// Resolves `id` in the SDK again (cheap: the SDK keeps its own live+ /// connection per Space) and keeps the handle.+ private func resolveFresh(_ id: SpaceID) async throws -> CuaSDK.Space? {+ guard let native else { return nil }+ await dropCachesFromAnotherDaemon()+ let handle = try await native.space(space: id.rawValue)+ handles[id] = handle+ return handle+ }+/// A handle, with the guest's real `$HOME` when the SDK can ask for it.private func space(for info: SpaceInfo) async throws -> Space {guard info.isReady, let handle = try? await nativeSpace(info.id) else {diff --git a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/CuaBackedTests.swift b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/CuaBackedTests.swiftindex f5c5b12964..738af46175 100644--- a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/CuaBackedTests.swift+++ b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/CuaBackedTests.swift@@ -106,6 +106,14 @@ struct Fixtures {XCTAssertEqual(listed.map(\.id), [space.id])XCTAssertTrue(listed[0].isReady)+ // Opening a stream resolves just this Space (no list of every Space,+ // no guest round trip), and it is the same Space.+ let forStream = try await connection.attachForStream(to: space.id)+ XCTAssertEqual(forStream.id, space.id)+ XCTAssertEqual(forStream.provider, .direct)+ XCTAssertTrue(forStream.isReady)+ XCTAssertEqual(forStream.info.operatingSystem, listed[0].operatingSystem)+// §1, live: many calls in a row, each answered with its own shape.for i in 0..<12 {let out = try await space.bash("echo step-\(i)")diff --git a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/DaemonRestartTests.swift b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/DaemonRestartTests.swiftindex 8342fff05b..7d4cb637b6 100644--- a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/DaemonRestartTests.swift+++ b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/DaemonRestartTests.swift@@ -44,6 +44,18 @@ import Testing#expect(await backend.callCount("stream_endpoint") == 2, "and cached for that daemon")}+ /// Opening a stream resolves the one Space (`attachForStream`) rather+ /// than listing every Space on every machine; with no cua SDK behind the+ /// connection (this fake) it takes `attach`'s path and its errors.+ @Test func testAttachForStreamWithoutTheSDKFallsBackToAttach() async throws {+ let space = try await connection.attachForStream(to: "local:cua-space-test")+ #expect(space.id == "local:cua-space-test")+ #expect(await backend.callCount("list_spaces") >= 1)+ await #expect(throws: (any Error).self) {+ _ = try await connection.attachForStream(to: "local:not-here")+ }+ }+@Test func testADaemonThatDoesNotAnswerKeepsNothing() async throws {let space = try await connection.attach(to: "local:cua-space-test")_ = try await space.streamEndpoint()