Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(spaces-web): Spaces filter box, ⌘K machine keywords, power errors on tiles (#5101)

ddupont1ec1c09bd2ce
diff --git a/apps/cua-spaces-web/src/__tests__/spaces-filter.test.tsx b/apps/cua-spaces-web/src/__tests__/spaces-filter.test.tsx
new file mode 100644
index 0000000000..f720d91167
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/spaces-filter.test.tsx
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Finding a Space on the Spaces page and in ⌘K, as the SwiftUI sidebar's
+// search does it (the core's name/detail/id rule, plus the machine), and a
+// failed start or stop said on the Space's tile (real routes, wasm core,
+// the demo host).
+
+import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import { useUiStore } from "@/stores/ui";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+stubBrowserApis();
+
+const tileNames = () => Array.from(document.querySelectorAll<HTMLElement>("[data-space-id]")).map((t) => t.getAttribute("data-space-id"));
+
+const filterBox = () =>
+ waitFor(() => {
+ const el = document.querySelector<HTMLInputElement>("[data-spaces-filter]");
+ if (!el) throw new Error("no filter box");
+ return el;
+ });
+
+describe.skipIf(!wasmBuilt)("Spaces filter box, ⌘K keywords and tile power errors", () => {
+ it("filters the tiles by name, id or machine, says when nothing matches, and Escape clears it", async () => {
+ await mountApp("/spaces", { failsCreates: false, listsGhost: false });
+ await waitFor(() => expect(tileNames()).toContain("relay:mac-mini/qa-windows"));
+ const all = tileNames().length;
+ const box = await filterBox();
+
+ fireEvent.change(box, { target: { value: " QA-win " } });
+ await waitFor(() => expect(tileNames()).toEqual(["relay:mac-mini/qa-windows"]));
+
+ // The machine the Space runs on.
+ fireEvent.change(box, { target: { value: "linux box" } });
+ await waitFor(() => expect(tileNames().length).toBeGreaterThan(0));
+ expect(tileNames().every((id) => id?.startsWith("relay:linux-box/"))).toBe(true);
+
+ fireEvent.change(box, { target: { value: "nothing-like-this" } });
+ await waitFor(() => expect(tileNames()).toEqual([]));
+ expect(document.body.textContent).toContain("No matches");
+
+ fireEvent.keyDown(box, { key: "Escape" });
+ await waitFor(() => expect(tileNames().length).toBe(all));
+ });
+
+ it("finds a Space in ⌘K by the machine it runs on", async () => {
+ await mountApp("/spaces", { failsCreates: false, listsGhost: false });
+ await waitFor(() => expect(tileNames()).toContain("relay:mac-mini/qa-windows"));
+ act(() => useUiStore.getState().setPaletteOpen(true));
+ const input = await waitFor(() => {
+ const el = document.querySelector<HTMLInputElement>('[data-command-palette] input');
+ if (!el) throw new Error("no palette");
+ return el;
+ });
+ fireEvent.change(input, { target: { value: "mac mini" } });
+ await waitFor(() => expect(document.getElementById("palette-space:open:relay:mac-mini/qa-windows")).not.toBeNull());
+ act(() => useUiStore.getState().setPaletteOpen(false));
+ });
+
+ it("says on the tile why its last stop failed", async () => {
+ await mountApp("/spaces", {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op) => {
+ if (op === "spaces.setPower") throw new Error("the machine did not answer");
+ return undefined;
+ },
+ });
+ const link = await waitFor(() => {
+ const el = document.querySelector<HTMLElement>('[data-space-id="relay:mac-mini/qa-windows"]');
+ if (!el) throw new Error("no tile");
+ return el;
+ });
+ const tile = link.parentElement!;
+ expect(tile.querySelector("[data-power-error]")).toBeNull();
+ const power = await waitFor(() => {
+ const b = tile.querySelector<HTMLButtonElement>("[data-tile-power]");
+ if (!b) throw new Error("no power button");
+ return b;
+ });
+ fireEvent.click(power);
+ await waitFor(() => expect(tile.querySelector("[data-power-error]")?.textContent).toContain("the machine did not answer"));
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/command-palette.tsx b/apps/cua-spaces-web/src/components/shell/command-palette.tsx
index 274b5eac0c..a8fa71d34b 100644
--- a/apps/cua-spaces-web/src/components/shell/command-palette.tsx
+++ b/apps/cua-spaces-web/src/components/shell/command-palette.tsx
@@ -19,13 +19,13 @@ import {
} from "lucide-react";
import { useState, type KeyboardEvent } from "react";
-import { useBridge, useChecklist, useKeyvault, useSession, useSpaces } from "@/bridge";
+import { useBridge, useChecklist, useKeyvault, useMachines, useSession, useSpaces } from "@/bridge";
import { OsIcon } from "@/components/os-icon";
import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { Kbd, Shortcut } from "@/components/ui/kbd";
import { toast, toastError } from "@/components/ui/toast";
import { filterCommands, type PaletteCommand } from "@/lib/commands";
-import { osLabel, realSpaces, spaceState } from "@/lib/spaces";
+import { machineName, osLabel, paletteKeywords, realSpaces, spaceState } from "@/lib/spaces";
import { bindingFor } from "@/lib/keybindings";
import { useTheme } from "@/lib/theme";
import { cn } from "@/lib/utils";
@@ -54,6 +54,7 @@ function PaletteBody({ onClose }: { onClose: () => void }) {
const router = useRouter();
const navigate = useNavigate();
const { data: spaces = [], startSpace, stopSpace } = useSpaces();
+ const { data: machines = [] } = useMachines();
const newSpace = useNewSpace();
const { data: keyvault, lockItems } = useKeyvault();
const { data: session, signIn, signOut } = useSession();
@@ -147,7 +148,7 @@ function PaletteBody({ onClose }: { onClose: () => void }) {
},
...realSpaces(spaces).flatMap((s): Command[] => {
const state = spaceState(s);
- const meta = { group: "Spaces", hint: osLabel(s), keywords: `${s.os} ${state}`, icon: <OsIcon os={s.os} className="size-3.5 text-muted-foreground" /> };
+ const meta = { group: "Spaces", hint: osLabel(s), keywords: paletteKeywords(s, state, machineName(machines, s)), icon: <OsIcon os={s.os} className="size-3.5 text-muted-foreground" /> };
const out: Command[] = [{ ...meta, id: `space:open:${s.id}`, label: `Open ${s.name}`, run: () => openSpace(s.id) }];
if (state === "stopped") {
out.push({ ...meta, id: `space:start:${s.id}`, label: `Start ${s.name}`, run: () => void startSpace(s.id).catch(toastError(`Couldn't start ${s.name}`)) });
diff --git a/apps/cua-spaces-web/src/lib/spaces.ts b/apps/cua-spaces-web/src/lib/spaces.ts
index ef9bf55142..0edc40aaab 100644
--- a/apps/cua-spaces-web/src/lib/spaces.ts
+++ b/apps/cua-spaces-web/src/lib/spaces.ts
@@ -52,10 +52,30 @@ export type SpaceFilter = "all" | "running" | "stopped" | "creating";
const ORDER: Record<SpaceState, number> = { failed: 0, creating: 0, running: 1, stopped: 2, deleting: 3 };
+/**
+ * Whether the filter box's `query` keeps `space`: the core's rule
+ * (`sidebar.matches`, the SwiftUI sidebar search's): any of its name,
+ * detail, id or machine holds the trimmed query, ignoring case. Without the
+ * core, the same rule here.
+ */
+export function matchesQuery(
+ core: { tryCall<T>(op: string, args?: Record<string, unknown>): T | undefined } | undefined,
+ space: Pick<Space, "id" | "name" | "detail">,
+ machine: string,
+ query: string,
+): boolean {
+ if (query.trim() === "") return true;
+ const fields = [space.name, space.detail ?? "", space.id, machine];
+ const kept = core?.tryCall<boolean>("sidebar.matches", { query, fields });
+ if (typeof kept === "boolean") return kept;
+ const needle = query.trim().toLowerCase();
+ return fields.some((f) => f.toLowerCase().includes(needle));
+}
+
/** Filter by state, then: creating first, running next, then stopped; most recent first within each. */
-export function visibleSpaces(spaces: readonly Space[], filter: SpaceFilter): Space[] {
+export function visibleSpaces(spaces: readonly Space[], filter: SpaceFilter, keep: (space: Space) => boolean = () => true): Space[] {
return spaces
- .filter((s) => filter === "all" || spaceState(s) === filter)
+ .filter((s) => (filter === "all" || spaceState(s) === filter) && keep(s))
.toSorted((a, b) => ORDER[spaceState(a)] - ORDER[spaceState(b)] || b.lastUsedAt - a.lastUsedAt);
}
@@ -80,6 +100,16 @@ export function machineName(machines: readonly Machine[], space: Pick<Space, "id
return space.provider === "cloud" || space.provider === undefined ? "Cua Cloud" : "Unknown machine";
}
+/** What a Space's ⌘K entries also match: its OS, state, detail and the machine it runs on. */
+export function paletteKeywords(space: Pick<Space, "os" | "detail" | "hostName">, state: SpaceState, machine: string): string {
+ return [...new Set([space.os, state, space.detail, space.hostName, machine].filter((w): w is string => Boolean(w)))].join(" ");
+}
+
+/** Why the Space's last power action failed (the core's `sidebar::power_error`), for its tile. */
+export function powerError(space: Pick<Space, "status" | "power">): string | null {
+ return canPower(space) ? (space.power?.error ?? null) || null : null;
+}
+
/** This Mac's macOS Spaces that run or are being created (Apple's limit). */
export function busyMacosSpaces(spaces: readonly Pick<Space, "id" | "os" | "provider" | "status" | "power" | "progress">[]): number {
return spaces.filter((s) => s.os === "macos" && s.provider === "local" && ["running", "creating"].includes(spaceState(s))).length;
diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsx
index bc77469d99..fcdddf0011 100644
--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx
@@ -2,7 +2,7 @@
// Copyright (c) 2026 Cua AI, Inc.
import { createFileRoute, Link } from "@tanstack/react-router";
-import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon } from "lucide-react";
+import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon, SearchIcon } from "lucide-react";
import { useEffect, useRef, useState, type DragEvent } from "react";
import { emptyHome, useBridge, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space } from "@/bridge";
@@ -15,12 +15,13 @@ import { StateLabel } from "@/components/state-dot";
import { useTileVideo } from "@/components/video/tile-video";
import { useNewSpace } from "@/hooks/use-new-space";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import { Segmented } from "@/components/ui/segmented";
import { toast, toastError } from "@/components/ui/toast";
import { creatingLine, thisComputerText } from "@/lib/host-labels";
import { plural } from "@/lib/plural";
import { cn } from "@/lib/utils";
-import { createError, createProgress, machineName, powerButton, realSpaces, spacePlace, spaceState, visibleSpaces, type SpaceFilter } from "@/lib/spaces";
+import { createError, createProgress, machineName, matchesQuery, powerButton, powerError, realSpaces, spacePlace, spaceState, visibleSpaces, type SpaceFilter } from "@/lib/spaces";
export const Route = createFileRoute("/spaces/")({ component: SpacesPage });
@@ -37,6 +38,7 @@ function SpacesPage() {
const spaces = realSpaces(all);
const { data: machines = [] } = useMachines();
const [filter, setFilter] = useState<SpaceFilter>("all");
+ const [query, setQuery] = useState("");
const newSpace = useNewSpace();
// Asks for the host's options while the list is empty: its architecture
// decides the macOS tile, and New Space opens with them in.
@@ -44,7 +46,7 @@ function SpacesPage() {
const { core } = useBridge();
const { env } = useNewSpaceWizard();
const home = emptyHome(core, env.hostArch);
- const shown = visibleSpaces(spaces, filter);
+ const shown = visibleSpaces(spaces, filter, (s) => matchesQuery(core, s, machineName(machines, s), query));
const access = useSpaceAccess(spaces);
const running = spaces.filter((s) => spaceState(s) === "running").length;
@@ -60,8 +62,27 @@ function SpacesPage() {
}
/>
<GettingStarted />
- <div className="mb-4">
+ <div className="mb-4 flex items-center gap-3">
<Segmented aria-label="Filter by state" value={filter} options={FILTERS} onValueChange={setFilter} />
+ {/* Find a Space by name, detail, id or machine (the SwiftUI sidebar's search). */}
+ <div className="relative ml-auto w-56">
+ <SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape" && query) {
+ e.preventDefault();
+ setQuery("");
+ }
+ }}
+ placeholder="Filter"
+ aria-label="Filter Spaces"
+ data-spaces-filter=""
+ className="pl-8"
+ />
+ </div>
</div>
{error ? (
<EmptyState icon={<MonitorIcon />} title="Couldn't load Spaces">
@@ -83,6 +104,10 @@ function SpacesPage() {
>
Create one on {thisComputerText()} or on Cua Cloud.
</EmptyState>
+ ) : shown.length === 0 && query.trim() ? (
+ <EmptyState icon={<SearchIcon />} title="No matches">
+ No {filter === "all" ? "" : `${filter} `}Space matches “{query.trim()}”.
+ </EmptyState>
) : shown.length === 0 ? (
<EmptyState icon={<MonitorIcon />} title={`No ${filter} Spaces`}>
Pick another filter to see the rest.
@@ -259,6 +284,11 @@ function SpaceLink({ space, machine, windowOver = false }: { space: Space; machi
<p data-create-error="" title={createError(space)!} className="mt-1 line-clamp-2 text-xs text-destructive">
{createError(space)}
</p>
+ ) : powerError(space) ? (
+ // The last start or stop failed: why, inline, as the SwiftUI sidebar row says it.
+ <p data-power-error="" title={powerError(space)!} className="mt-1 line-clamp-2 text-xs text-destructive">
+ {powerError(space)}
+ </p>
) : null}
</div>
<StateLabel state={spaceState(space)} space={space} className="mt-px shrink-0" />
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index 4d59ab12bc..2d509351ce 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -50,6 +50,7 @@ pub const METHODS: &[&str] = &[
"creates.isDeleting",
"creates.isPowering",
"sidebar.build",
+ "sidebar.matches",
"sidebar.detail",
"sidebar.detailCopy",
"sidebar.deleteFailedText",
@@ -373,6 +374,13 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
.unwrap_or_default(),
&a.get::<String>("id")?,
)),
+ "sidebar.matches" => {
+ let fields = a.get::<Vec<String>>("fields")?;
+ out(sidebar::matches(
+ &a.get::<Option<String>>("query")?.unwrap_or_default(),
+ &fields.iter().map(String::as_str).collect::<Vec<_>>(),
+ ))
+ }
"sidebar.build" => out(sidebar::sidebar(
&a.get::<Vec<Space>>("spaces")?,
&a.get::<Option<String>>("query")?.unwrap_or_default(),
diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
index e45150618b..c726ea4dc4 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
@@ -300,17 +300,20 @@ pub fn effective_selection<'a>(spaces: &'a [Space], selected_id: &str) -> Option
.or_else(|| spaces.iter().find(|s| s.id != THIS_MACHINE_ID))
}
+/// Whether a search `query` keeps a row with these `fields` (a Space's
+/// name, detail and id): an empty query keeps every row, else any field
+/// holds the trimmed query, ignoring case. The sidebar's search and the
+/// web UI's Spaces filter box both use it.
+pub fn matches(query: &str, fields: &[&str]) -> bool {
+ let needle = query.trim().to_lowercase();
+ needle.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&needle))
+}
+
/// Builds the sidebar for `spaces` filtered by `query`.
pub fn sidebar(spaces: &[Space], query: &str, selected_id: &str) -> SidebarView {
- let needle = query.trim().to_lowercase();
let visible: Vec<&Space> = spaces
.iter()
- .filter(|s| {
- needle.is_empty()
- || [&s.name, &s.detail, &s.id]
- .iter()
- .any(|f| f.to_lowercase().contains(&needle))
- })
+ .filter(|s| matches(query, &[&s.name, &s.detail, &s.id]))
.collect();
let selected = effective_selection(spaces, selected_id).map(|s| s.id.clone());
let sel = selected.as_deref();
@@ -336,7 +339,7 @@ pub fn sidebar(spaces: &[Space], query: &str, selected_id: &str) -> SidebarView
})
.collect();
let empty_text = sections.is_empty().then(|| {
- if needle.is_empty() {
+ if query.trim().is_empty() {
"No Spaces yet".to_string()
} else {
"No matches".to_string()
@@ -1161,6 +1164,18 @@ mod tests {
/// Only This machine is not a Space to open: an empty id selects nothing,
/// choosing it does, and a real Space wins over it.
+ #[test]
+ fn matches_name_detail_or_id_ignoring_case_and_spaces() {
+ let f = ["Design Review", "Agent testing", "relay:mini/space-1"];
+ assert!(matches("", &f));
+ assert!(matches(" ", &f));
+ assert!(matches(" design ", &f));
+ assert!(matches("TESTING", &f));
+ assert!(matches("mini/", &f));
+ assert!(!matches("ubuntu", &f));
+ assert!(!matches("x", &[]));
+ }
+
#[test]
fn this_machine_alone_selects_nothing() {
use crate::host::this_machine_space;