Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(cua-spaces-web): Machines page trusts the relay's online answer and refreshes every 30 s (CUA-3581) (#6637)

Francesco Bonaccib42bb2c7781a
diff --git a/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx b/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx
index 66e12d0eaa..509579c29d 100644
--- a/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/machines-page.test.tsx
@@ -10,7 +10,7 @@
import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";
import type { MachineRow, MachinesView } from "@/bridge/contracts/host";
import { readNewSpaceSession, resetNewSpaceSession } from "@/bridge/new-space";
@@ -574,3 +574,96 @@ describe.skipIf(!wasmBuilt)("the Machines page (real routes, wasm core)", () =>
await waitFor(() => expect(document.querySelector("[data-cloud-deny]")).toBeNull());
});
});
+
+/**
+ * A computer powered off. The host's list and view still count its relay connection (online, Remove disabled) while the
+ * relay's own answer already says offline; the page trusts the relay and re-reads every 30 s, as the Spaces tree does.
+ * A hand-made view, so these do not need the wasm core.
+ */
+describe("the Machines page when a computer powers off", () => {
+ afterEach(() => vi.useRealTimers());
+
+ const machine = (): MachinesView["machines"][number] =>
+ ({
+ id: "studio-pc",
+ name: "Studio PC",
+ line: "Windows · Cua relay",
+ online: true,
+ os: "windows",
+ current: false,
+ team: false,
+ status: "Online",
+ toggles: [],
+ spacesTitle: "Spaces",
+ spaces: [],
+ newSpace: { label: "New Space here", on: "host:studio-pc", enabled: true },
+ detailsTitle: "Details",
+ details: [],
+ remove: {
+ label: "Remove from account",
+ enabled: false,
+ help: "It is online: remove it on that computer.",
+ host: false,
+ machine: "studio-pc",
+ confirm: { title: "Remove Studio PC?", message: "", confirmLabel: "Remove", cancelLabel: "Cancel" },
+ },
+ }) as MachinesView["machines"][number];
+
+ const view = (): MachinesView => ({ summary: "1 machine, 1 online", groups: [{ id: "yours", title: "Your machines", collapsed: false, ids: ["studio-pc"] }], machines: [machine()], order: ["yours"] });
+
+ const step = (space: string, name: string, online: boolean, role: string) => ({ space, name, online, role });
+
+ async function mountPoweredOff(relayOnline: { value: boolean }) {
+ return mountApp("/machines", {
+ failsCreates: false,
+ listsGhost: false,
+ answer: (op, out) => (op === "machines.list" ? [...(out as MachineRow[]), { id: "studio-pc", name: "Studio PC", via: "relay", online: true, os: "windows", limits: [] }] : out),
+ intercept: (op) =>
+ op === "spaces.resolveDefault"
+ ? { space: "relay:studio-pc", reason: "setting", defaultSpace: "relay:studio-pc", defaultOnline: relayOnline.value, order: [step("relay:studio-pc", "Studio PC", relayOnline.value, "default"), step("relay:this-mac", "This Mac", true, "here")] }
+ : undefined,
+ machinesView: view,
+ });
+ }
+
+ const row = () => document.querySelector<HTMLElement>('[data-machine-id="studio-pc"]')!;
+
+ it("flips the row to Offline within one refresh, with text a screen reader reads", async () => {
+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
+ const relay = { value: true };
+ const { router } = await mountPoweredOff(relay);
+ await router.load();
+ await waitFor(() => expect(row()).toBeTruthy());
+ expect(row().getAttribute("data-online")).toBe("true");
+ expect(within(row()).getByText("Online")).toBeTruthy();
+
+ relay.value = false;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ await waitFor(() => expect(row().getAttribute("data-online")).toBe("false"));
+ expect(within(row()).getByText("Offline")).toBeTruthy();
+ expect(within(row()).queryByText("Online")).toBeNull();
+ });
+
+ it("enables Remove from account once the relay calls the computer offline", async () => {
+ const relay = { value: false };
+ const { router } = await mountPoweredOff(relay);
+ await router.load();
+ await waitFor(() => expect(row().getAttribute("data-online")).toBe("false"));
+ act(() => row().click());
+ const detail = await detailOf("Studio PC");
+ const remove = detail.querySelector<HTMLButtonElement>('[data-machine-remove="studio-pc"]')!;
+ expect(remove.disabled).toBe(false);
+ });
+
+ it("keeps Remove disabled while the relay still calls it online", async () => {
+ const relay = { value: true };
+ const { router } = await mountPoweredOff(relay);
+ await router.load();
+ await waitFor(() => expect(row()).toBeTruthy());
+ act(() => row().click());
+ const detail = await detailOf("Studio PC");
+ expect(detail.querySelector<HTMLButtonElement>('[data-machine-remove="studio-pc"]')!.disabled).toBe(true);
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts b/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts
index d4c4253c1e..a22c03ecaf 100644
--- a/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts
+++ b/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts
@@ -1,17 +1,15 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { useEffect, useMemo } from "react";
+import { useMemo } from "react";
-import { useAgents, useBridge, useMachines, useSession, useSpaces, useSpacesDefault, useSpacesTree, type SpacesDefaultHook } from "@/bridge";
+import { useAgents, useBridge, useSession, useSpaces, useSpacesTree, type SpacesDefaultHook } from "@/bridge";
+import { useMachinesLive } from "@/hooks/use-machines-live";
import { useHiddenSpaceIds } from "@/lib/prepare/store";
import { buildSpacesTree, type SpacesTree } from "@/lib/spaces-tree";
const NO_RUNS: ReadonlyMap<string, number> = new Map();
-/** How often the tree reads the computers again while it is on (the host answers from memory and asks the relay only when its copy is stale). */
-export const MACHINES_REFRESH_MS = 30_000;
-
/** Running agent tasks by Space id, from the runs in your running Spaces. */
export function useRunningBySpace(): ReadonlyMap<string, number> {
const { data } = useAgents();
@@ -30,23 +28,15 @@ export function useRunningBySpace(): ReadonlyMap<string, number> {
export function useSpacesTreeData(running: ReadonlyMap<string, number> = NO_RUNS): { on: boolean; tree: SpacesTree | null; loaded: boolean; defaults: SpacesDefaultHook } {
const on = useSpacesTree();
const { data: spaces, listStatus } = useSpaces();
- const { data: machines, refresh: refreshMachines } = useMachines();
// The sidebar counts the tree on every page, so nothing else asks for the computers again: without this a computer that went
// offline keeps its green dot (and "Online, Default") while Home already says it is offline.
- useEffect(() => {
- if (!on) return;
- const t = setInterval(() => void refreshMachines().catch(() => {}), MACHINES_REFRESH_MS);
- return () => clearInterval(t);
- }, [on]);
+ const { machines, defaults, relayOnline } = useMachinesLive(on);
const { data: session } = useSession();
const { core } = useBridge();
// The Space being prepared for Home's box is no Space of yours yet.
const warming = useHiddenSpaceIds(core);
- const defaults = useSpacesDefault(on);
// The setting names the default; until it's read (or when it names none) the relay's own answer does.
const defaultSpace = defaults.settings?.defaultSpace ?? defaults.resolved?.defaultSpace ?? null;
- const order = defaults.resolved?.order;
- const relayOnline = useMemo(() => new Map((order ?? []).filter((o) => o.role !== "here").map((o) => [o.space, o.online] as const)), [order]);
const tree = useMemo(
() =>
on && spaces && machines
diff --git a/apps/cua-spaces-web/src/hooks/use-machines-live.ts b/apps/cua-spaces-web/src/hooks/use-machines-live.ts
new file mode 100644
index 0000000000..050b57a317
--- /dev/null
+++ b/apps/cua-spaces-web/src/hooks/use-machines-live.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useEffect, useMemo, useRef } from "react";
+
+import { useMachines, useSpacesDefault, type SpacesDefaultHook } from "@/bridge";
+import { buildRelayOnline } from "@/lib/spaces-tree";
+
+/** How often the computers are read again while a screen that shows their status is on (the host answers from memory and asks the relay only when its copy is stale). */
+export const MACHINES_REFRESH_MS = 30_000;
+
+/**
+ * The computers kept fresh, with the relay's own online answer for each (the same data as Home's fallback line).
+ * The computer list counts a relay connection that hasn't been dropped yet, so a computer that powered off stays
+ * "online" there for minutes; the relay's answer is what to trust. Used by the Spaces tree and the Machines page.
+ * `on` false reads and refreshes nothing.
+ */
+export function useMachinesLive(on: boolean) {
+ const { data: machines, refresh } = useMachines();
+ const defaults: SpacesDefaultHook = useSpacesDefault(on);
+ // Both are read again on every tick: the relay's answer is its own read, not a by-product of the list's.
+ const tick = useRef(() => Promise.all([refresh(), defaults.refresh()]));
+ tick.current = () => Promise.all([refresh(), defaults.refresh()]);
+ useEffect(() => {
+ if (!on) return;
+ const t = setInterval(() => void tick.current().catch(() => {}), MACHINES_REFRESH_MS);
+ return () => clearInterval(t);
+ }, [on]);
+ const order = defaults.resolved?.order;
+ const relayOnline = useMemo(() => buildRelayOnline(order), [order]);
+ return { machines, defaults, relayOnline };
+}
diff --git a/apps/cua-spaces-web/src/lib/machines-relay-status.ts b/apps/cua-spaces-web/src/lib/machines-relay-status.ts
new file mode 100644
index 0000000000..1d6dc42e9c
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/machines-relay-status.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import type { Machine, MachinesView } from "@/bridge";
+import { relayCallsOffline } from "@/lib/spaces-tree";
+
+/**
+ * The Machines page's view with the relay's own online answer applied. The host's view counts a relay connection that
+ * hasn't been dropped yet, so a computer that powered off stays "Online" for minutes and "Remove from account" stays
+ * disabled. A computer the relay calls offline shows offline, and (it being another machine) can be removed.
+ */
+export function withRelayStatus(view: MachinesView, machines: readonly Machine[], relayOnline: ReadonlyMap<string, boolean> | undefined): MachinesView {
+ if (!relayOnline || relayOnline.size === 0) return view;
+ const offline = new Set(machines.filter((m) => relayCallsOffline(m, relayOnline)).map((m) => m.id));
+ if (!view.machines.some((m) => m.online && offline.has(m.id))) return view;
+ return {
+ ...view,
+ machines: view.machines.map((m) =>
+ m.online && offline.has(m.id)
+ ? {
+ ...m,
+ online: false,
+ status: "Offline",
+ remove: m.remove && !m.remove.host && m.remove.machine ? { ...m.remove, enabled: true, help: null } : m.remove,
+ }
+ : m,
+ ),
+ };
+}
diff --git a/apps/cua-spaces-web/src/lib/spaces-tree.ts b/apps/cua-spaces-web/src/lib/spaces-tree.ts
index 7821cb8c10..62fcfe51ac 100644
--- a/apps/cua-spaces-web/src/lib/spaces-tree.ts
+++ b/apps/cua-spaces-web/src/lib/spaces-tree.ts
@@ -90,6 +90,17 @@ export function computerSpaceId(m: Pick<Machine, "id" | "current" | "relayId" |
return m.connection === "direct" ? null : `relay:${m.id}`;
}
+/** The relay's own online answer per computer Space id, from the resolved default's order (This Mac is not the relay's to answer). */
+export function buildRelayOnline(order: readonly { space: string; online: boolean; role?: string }[] | undefined): Map<string, boolean> {
+ return new Map((order ?? []).filter((o) => o.role !== "here").map((o) => [o.space, o.online] as const));
+}
+
+/** Whether the relay calls this computer offline, whatever the computer list still counts. */
+export function relayCallsOffline(m: Pick<Machine, "id" | "current" | "relayId" | "connection">, relayOnline: ReadonlyMap<string, boolean> | undefined): boolean {
+ const id = computerSpaceId(m);
+ return id !== null && !m.current && relayOnline?.get(id) === false;
+}
+
/**
* A computer row left in the Spaces list after its machine went (Remove from
* account, or a machine the relay forgot): `relay:<machine>` named by its raw
@@ -201,7 +212,7 @@ export function buildSpacesTree({ spaces, machines, defaultSpace, running = new
const kids = listed.filter((s) => !placed.has(s.id) && (m.current ? s.provider === "local" || (m.relayId !== undefined && s.host === m.relayId) : s.host === m.id));
// This Mac before it is shared, with no Space on it: not a Space yet (the empty state offers "Add this Mac").
if (m.current && !id && !m.connection && kids.length === 0) continue;
- const online = reachable(m) && !(id !== null && !m.current && relayOnline?.get(id) === false);
+ const online = reachable(m) && !relayCallsOffline(m, relayOnline);
const isDefault = key === defaultKey;
const word = online ? "Online" : m.online && m.notSharing ? "Not sharing" : offlineWord(m, now);
const node: TreeNode = {
diff --git a/apps/cua-spaces-web/src/routes/machines/index.tsx b/apps/cua-spaces-web/src/routes/machines/index.tsx
index 9c09d19032..d4a8e414e2 100644
--- a/apps/cua-spaces-web/src/routes/machines/index.tsx
+++ b/apps/cua-spaces-web/src/routes/machines/index.tsx
@@ -38,9 +38,11 @@ import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { toast } from "@/components/ui/toast";
+import { useMachinesLive } from "@/hooks/use-machines-live";
import { useNewSpace } from "@/hooks/use-new-space";
import { showDesktop } from "@/lib/hidden-desktops";
import { machineOs, selectedMachine } from "@/lib/machines";
+import { withRelayStatus } from "@/lib/machines-relay-status";
import { cn } from "@/lib/utils";
export const Route = createFileRoute("/machines/")({
@@ -91,8 +93,10 @@ function MachinesPage() {
const { data: machines = [], isLoading, error, view: fullView, checkHealth, remove } = useMachines();
const { account, pending, now } = useMachinesAccount();
const actions = usePendingActions();
+ // The list re-reads every 30 s, and a computer the relay calls offline shows offline (and can be removed) at once, as in the tree.
+ const { relayOnline } = useMachinesLive(true);
// A machine waiting to be added is in the top group, not in the list below.
- const view = useMemo(() => (fullView ? withoutPending(fullView, pending) : fullView), [fullView, pending]);
+ const view = useMemo(() => (fullView ? withRelayStatus(withoutPending(fullView, pending), machines, relayOnline) : fullView), [fullView, pending, machines, relayOnline]);
// Each machine's issues come from its own daemon: asked on opening the
// page and every minute while it stays open.
useEffect(() => {
@@ -445,7 +449,7 @@ function MachineRow({
hidden={hidden}
aria-selected={selected}
data-machine-id={m.id}
- data-online={(row?.online ?? m.online) ? "true" : "false"}
+ data-online={m.online ? "true" : "false"}
data-not-sharing={row?.notSharing ? "true" : undefined}
onClick={onSelect}
onKeyDown={(e) => {
@@ -460,6 +464,7 @@ function MachineRow({
)}
>
<StatusDot online={m.online} health={m.health} />
+ <span className="sr-only">{m.online ? "Online" : "Offline"}</span>
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
<span className="truncate text-[13px] font-medium">{m.name}</span>